diff --git a/.gitignore b/.gitignore index 4a644470b..c777002a9 100644 --- a/.gitignore +++ b/.gitignore @@ -87,3 +87,5 @@ mustgather-example.yaml saas-must-gather-operator-bundle # IDE .idea +# Binaries used by make +bin/ diff --git a/Makefile b/Makefile index 9c5105d72..ff2e02c25 100644 --- a/Makefile +++ b/Makefile @@ -5,3 +5,23 @@ include boilerplate/generated-includes.mk .PHONY: boilerplate-update boilerplate-update: @boilerplate/update + +OPENAPI_GEN_PKG := k8s.io/kube-openapi/cmd/openapi-gen +CONTROLLER_GEN_PKG := sigs.k8s.io/controller-tools/cmd/controller-gen + +# go-install-tool will 'go install' any package $2 and install it to $1. +define go-install-tool +@{ \ +set -e ;\ +echo "Downloading $(2)" ;\ +GOBIN=$(shell dirname $(1)) go install $(2) ;\ +echo "Installed in $(1)" ;\ +rm -rf $$TMP_DIR ;\ +} +endef + +.PHONY: install-tools +install-tools: + $(call go-install-tool, $(shell pwd)/bin/controller-gen, $(CONTROLLER_GEN_PKG)) + $(call go-install-tool, $(shell pwd)/bin/openapi-gen, $(OPENAPI_GEN_PKG)) + diff --git a/api/v1alpha1/zz_generated.openapi.go b/api/v1alpha1/zz_generated.openapi.go index 01c5587b8..3c2db349c 100644 --- a/api/v1alpha1/zz_generated.openapi.go +++ b/api/v1alpha1/zz_generated.openapi.go @@ -3,50 +3,12 @@ // Code generated by openapi-gen. DO NOT EDIT. -// This file was autogenerated by openapi-gen. Do not edit it manually! - package v1alpha1 import ( common "k8s.io/kube-openapi/pkg/common" - spec "k8s.io/kube-openapi/pkg/validation/spec" ) func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { - return map[string]common.OpenAPIDefinition{ - "github.com/openshift/must-gather-operator/api/v1alpha1.ProxySpec": schema_openshift_must_gather_operator_api_v1alpha1_ProxySpec(ref), - } -} - -func schema_openshift_must_gather_operator_api_v1alpha1_ProxySpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "httpProxy": { - SchemaProps: spec.SchemaProps{ - Description: "httpProxy is the URL of the proxy for HTTP requests. Empty means unset and will not result in an env var.", - Type: []string{"string"}, - Format: "", - }, - }, - "httpsProxy": { - SchemaProps: spec.SchemaProps{ - Description: "httpsProxy is the URL of the proxy for HTTPS requests. Empty means unset and will not result in an env var.", - Type: []string{"string"}, - Format: "", - }, - }, - "noProxy": { - SchemaProps: spec.SchemaProps{ - Description: "noProxy is the list of domains for which the proxy should not be used. Empty means unset and will not result in an env var.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } + return map[string]common.OpenAPIDefinition{} } diff --git a/boilerplate/openshift/golang-osd-operator/standard.mk b/boilerplate/openshift/golang-osd-operator/standard.mk index a77c9e87a..df0973789 100644 --- a/boilerplate/openshift/golang-osd-operator/standard.mk +++ b/boilerplate/openshift/golang-osd-operator/standard.mk @@ -202,8 +202,8 @@ rm -rf $$TMP_DIR ;\ } endef -CONTROLLER_GEN = controller-gen -OPENAPI_GEN = openapi-gen +CONTROLLER_GEN = ../bin/controller-gen +OPENAPI_GEN = ./bin/openapi-gen KUSTOMIZE = kustomize YQ = yq @@ -216,13 +216,13 @@ op-generate: .PHONY: openapi-generate openapi-generate: find ./api -maxdepth 2 -mindepth 1 -type d | xargs -t -I% \ - $(OPENAPI_GEN) --logtostderr=true \ - -i % \ - -o "" \ - -O zz_generated.openapi \ - -p % \ - -h /dev/null \ - -r "-" + $(OPENAPI_GEN) \ + --logtostderr \ + --output-dir ./api/v1alpha1 \ + --output-pkg my.module/api/v1alpha1 \ + --output-file zz_generated.openapi.go \ + --go-header-file /dev/null \ + --report-filename - .PHONY: manifests manifests: diff --git a/deploy/crds/managed.openshift.io_mustgathers.yaml b/deploy/crds/managed.openshift.io_mustgathers.yaml index ae44b31a3..bdb12e6a9 100644 --- a/deploy/crds/managed.openshift.io_mustgathers.yaml +++ b/deploy/crds/managed.openshift.io_mustgathers.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.18.1-0.20250818134112-b624019bbe8d + controller-gen.kubebuilder.io/version: v0.18.0 name: mustgathers.managed.openshift.io spec: group: managed.openshift.io diff --git a/go.mod b/go.mod index 9101f8f7e..fa3ef8b90 100644 --- a/go.mod +++ b/go.mod @@ -5,8 +5,8 @@ go 1.24.0 require ( github.com/blang/semver/v4 v4.0.0 github.com/go-logr/logr v1.4.2 - github.com/onsi/ginkgo/v2 v2.22.0 - github.com/onsi/gomega v1.36.1 + github.com/onsi/ginkgo/v2 v2.23.3 + github.com/onsi/gomega v1.37.0 github.com/openshift/api v0.0.0-20240522145529-93d6bda14341 github.com/openshift/operator-custom-metrics v0.5.0 github.com/openshift/osde2e-common v0.0.0-20240604133256-b7200cad0cca @@ -16,8 +16,9 @@ require ( k8s.io/api v0.33.3 k8s.io/apimachinery v0.33.3 k8s.io/client-go v0.33.3 - k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff + k8s.io/kube-openapi v0.0.0-20250814151709-d7b6acb124c3 sigs.k8s.io/controller-runtime v0.21.0 + sigs.k8s.io/controller-tools v0.18.0 ) require ( @@ -32,6 +33,7 @@ require ( github.com/evanphx/json-patch v5.7.0+incompatible // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d // indirect + github.com/fatih/color v1.18.0 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/go-errors/errors v1.4.2 // indirect @@ -40,19 +42,23 @@ require ( github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect + github.com/gobuffalo/flect v1.0.3 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/gnostic-models v0.6.9 // indirect + github.com/google/gnostic-models v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect + github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/huandu/xstrings v1.3.3 // indirect github.com/imdario/mergo v0.3.15 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/copystructure v1.0.0 // indirect github.com/mitchellh/reflectwalk v1.0.0 // indirect github.com/moby/spdystream v0.5.0 // indirect @@ -68,21 +74,25 @@ require ( github.com/prometheus/procfs v0.15.1 // indirect github.com/shopspring/decimal v1.2.0 // indirect github.com/spf13/cast v1.3.1 // indirect - github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/cobra v1.9.1 // indirect + github.com/spf13/pflag v1.0.6 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/crypto v0.36.0 // indirect - golang.org/x/net v0.38.0 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect + go.yaml.in/yaml/v3 v3.0.3 // indirect + golang.org/x/crypto v0.37.0 // indirect + golang.org/x/mod v0.24.0 // indirect + golang.org/x/net v0.39.0 // indirect golang.org/x/oauth2 v0.27.0 // indirect - golang.org/x/sync v0.12.0 // indirect - golang.org/x/sys v0.31.0 // indirect - golang.org/x/term v0.30.0 // indirect - golang.org/x/text v0.23.0 // indirect + golang.org/x/sync v0.13.0 // indirect + golang.org/x/sys v0.32.0 // indirect + golang.org/x/term v0.31.0 // indirect + golang.org/x/text v0.24.0 // indirect golang.org/x/time v0.9.0 // indirect - golang.org/x/tools v0.26.0 // indirect + golang.org/x/tools v0.32.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect google.golang.org/protobuf v1.36.5 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect @@ -91,6 +101,8 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.33.0 // indirect k8s.io/cli-runtime v0.28.2 // indirect + k8s.io/code-generator v0.33.0 // indirect + k8s.io/gengo/v2 v2.0.0-20250604051438-85fd79dbfd9f // indirect k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kubectl v0.28.2 // indirect k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect @@ -100,5 +112,6 @@ require ( sigs.k8s.io/kustomize/kyaml v0.14.3-0.20230601165947-6ce0bf390ce3 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.2.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/go.sum b/go.sum index a3a20dc20..1ec58d931 100644 --- a/go.sum +++ b/go.sum @@ -22,6 +22,7 @@ github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWR github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -37,6 +38,8 @@ github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjT github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d h1:105gxyaGwCFad8crR9dcMQWvV9Hvulu6hwUh4tWPJnM= github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= @@ -57,6 +60,8 @@ github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+Gr github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4= +github.com/gobuffalo/flect v1.0.3/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -71,8 +76,8 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= -github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= +github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= +github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -85,8 +90,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= +github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= +github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -99,6 +104,8 @@ github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -118,6 +125,11 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= @@ -139,10 +151,10 @@ github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= -github.com/onsi/ginkgo/v2 v2.22.0 h1:Yed107/8DjTr0lKCNt7Dn8yQ6ybuDRQoMGrNFKzMfHg= -github.com/onsi/ginkgo/v2 v2.22.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= -github.com/onsi/gomega v1.36.1 h1:bJDPBO7ibjxcbHMgSCoo4Yj18UWbKDlLwX1x9sybDcw= -github.com/onsi/gomega v1.36.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= +github.com/onsi/ginkgo/v2 v2.23.3 h1:edHxnszytJ4lD9D5Jjc4tiDkPBZ3siDeJJkUZJJVkp0= +github.com/onsi/ginkgo/v2 v2.23.3/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= +github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= +github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= github.com/openshift/api v0.0.0-20240522145529-93d6bda14341 h1:JQpzgk+p24rkgNbNsrNR0yLm63WTKapuT60INU5BqT8= github.com/openshift/api v0.0.0-20240522145529-93d6bda14341/go.mod h1:qNtV0315F+f8ld52TLtPvrfivZpdimOzTi3kn9IVbtU= github.com/openshift/operator-custom-metrics v0.5.0 h1:iRZ6e3HvGSxw1dZgnY5emEN6fg9u/OhHfEC+u3ovhSE= @@ -170,14 +182,17 @@ github.com/redhat-cop/operator-utils v1.3.7 h1:RNOa+PP+Rdlg8uAhDvHGnZ+UkPSJzXwG9 github.com/redhat-cop/operator-utils v1.3.7/go.mod h1:s4R0YY8lVlHkC78GLV20PPuZmywjSbTwZKCHwWUQ3P8= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -209,13 +224,17 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= +go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE= +go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= +golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -223,6 +242,8 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= +golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -234,8 +255,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= +golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= @@ -245,8 +266,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= -golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= +golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -256,21 +277,23 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= -golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= +golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= +golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= +golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -282,8 +305,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= -golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= +golang.org/x/tools v0.32.0 h1:Q7N1vhpkQv7ybVzLFtTjvQya2ewbwNDZzUgfXGqtMWU= +golang.org/x/tools v0.32.0/go.mod h1:ZxrU41P/wAbZD8EDa6dDCa6XfpkhJ7HFMjHJXfBDu8s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -336,16 +359,22 @@ k8s.io/cli-runtime v0.28.2 h1:64meB2fDj10/ThIMEJLO29a1oujSm0GQmKzh1RtA/uk= k8s.io/cli-runtime v0.28.2/go.mod h1:bTpGOvpdsPtDKoyfG4EG041WIyFZLV9qq4rPlkyYfDA= k8s.io/client-go v0.33.3 h1:M5AfDnKfYmVJif92ngN532gFqakcGi6RvaOF16efrpA= k8s.io/client-go v0.33.3/go.mod h1:luqKBQggEf3shbxHY4uVENAxrDISLOarxpTKMiUuujg= +k8s.io/code-generator v0.33.0 h1:B212FVl6EFqNmlgdOZYWNi77yBv+ed3QgQsMR8YQCw4= +k8s.io/code-generator v0.33.0/go.mod h1:KnJRokGxjvbBQkSJkbVuBbu6z4B0rC7ynkpY5Aw6m9o= +k8s.io/gengo/v2 v2.0.0-20250604051438-85fd79dbfd9f h1:SLb+kxmzfA87x4E4brQzB33VBbT2+x7Zq9ROIHmGn9Q= +k8s.io/gengo/v2 v2.0.0-20250604051438-85fd79dbfd9f/go.mod h1:EJykeLsmFC60UQbYJezXkEsG2FLrt0GPNkU5iK5GWxU= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= -k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= +k8s.io/kube-openapi v0.0.0-20250814151709-d7b6acb124c3 h1:liMHz39T5dJO1aOKHLvwaCjDbf07wVh6yaUlTpunnkE= +k8s.io/kube-openapi v0.0.0-20250814151709-d7b6acb124c3/go.mod h1:UZ2yyWbFTpuhSbFhv24aGNOdoRdJZgsIObGBUaYVsts= k8s.io/kubectl v0.28.2 h1:fOWOtU6S0smdNjG1PB9WFbqEIMlkzU5ahyHkc7ESHgM= k8s.io/kubectl v0.28.2/go.mod h1:6EQWTPySF1fn7yKoQZHYf9TPwIl2AygHEcJoxFekr64= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/controller-runtime v0.21.0 h1:CYfjpEuicjUecRk+KAeyYh+ouUBn4llGyDYytIGcJS8= sigs.k8s.io/controller-runtime v0.21.0/go.mod h1:OSg14+F65eWqIu4DceX7k/+QRAbTTvxeQSNSOQpukWM= +sigs.k8s.io/controller-tools v0.18.0 h1:rGxGZCZTV2wJreeRgqVoWab/mfcumTMmSwKzoM9xrsE= +sigs.k8s.io/controller-tools v0.18.0/go.mod h1:gLKoiGBriyNh+x1rWtUQnakUYEujErjXs9pf+x/8n1U= sigs.k8s.io/e2e-framework v0.3.0 h1:eqQALBtPCth8+ulTs6lcPK7ytV5rZSSHJzQHZph4O7U= sigs.k8s.io/e2e-framework v0.3.0/go.mod h1:C+ef37/D90Dc7Xq1jQnNbJYscrUGpxrWog9bx2KIa+c= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= @@ -359,5 +388,7 @@ sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= +sigs.k8s.io/structured-merge-diff/v6 v6.2.0 h1:msyqjP8Nyd5sF3QSmJouFSzcBIdwq4ct8d1/7VSBHIQ= +sigs.k8s.io/structured-merge-diff/v6 v6.2.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/tools.go b/tools.go deleted file mode 100644 index 3d5e5c0bc..000000000 --- a/tools.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build tools - -// Place any runtime dependencies as imports in this file. -// Go modules will be forced to download and install them. -package tools diff --git a/tools/tools.go b/tools/tools.go new file mode 100644 index 000000000..59c9f7c65 --- /dev/null +++ b/tools/tools.go @@ -0,0 +1,10 @@ +// Place any runtime dependencies as imports in this file. +// Go modules will be forced to download and install them. +package tools + +import ( + // kube-openapi: openapi-gen binary is used in `make generate` + _ "k8s.io/kube-openapi/cmd/openapi-gen" + // controller-gen: binary is used in API generations + _ "sigs.k8s.io/controller-tools/cmd/controller-gen" +) diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md new file mode 100644 index 000000000..25fdaf639 --- /dev/null +++ b/vendor/github.com/fatih/color/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Fatih Arslan + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md new file mode 100644 index 000000000..d135bfe02 --- /dev/null +++ b/vendor/github.com/fatih/color/README.md @@ -0,0 +1,189 @@ +# color [![](https://github.com/fatih/color/workflows/build/badge.svg)](https://github.com/fatih/color/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/color)](https://pkg.go.dev/github.com/fatih/color) + +Color lets you use colorized outputs in terms of [ANSI Escape +Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It +has support for Windows too! The API can be used in several ways, pick one that +suits you. + +![Color](https://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg) + +## Install + +``` +go get github.com/fatih/color +``` + +## Examples + +### Standard colors + +```go +// Print with default helper functions +color.Cyan("Prints text in cyan.") + +// A newline will be appended automatically +color.Blue("Prints %s in blue.", "text") + +// These are using the default foreground colors +color.Red("We have red") +color.Magenta("And many others ..") + +``` + +### RGB colors + +If your terminal supports 24-bit colors, you can use RGB color codes. + +```go +color.RGB(255, 128, 0).Println("foreground orange") +color.RGB(230, 42, 42).Println("foreground red") + +color.BgRGB(255, 128, 0).Println("background orange") +color.BgRGB(230, 42, 42).Println("background red") +``` + +### Mix and reuse colors + +```go +// Create a new color object +c := color.New(color.FgCyan).Add(color.Underline) +c.Println("Prints cyan text with an underline.") + +// Or just add them to New() +d := color.New(color.FgCyan, color.Bold) +d.Printf("This prints bold cyan %s\n", "too!.") + +// Mix up foreground and background colors, create new mixes! +red := color.New(color.FgRed) + +boldRed := red.Add(color.Bold) +boldRed.Println("This will print text in bold red.") + +whiteBackground := red.Add(color.BgWhite) +whiteBackground.Println("Red text with white background.") + +// Mix with RGB color codes +color.RGB(255, 128, 0).AddBgRGB(0, 0, 0).Println("orange with black background") + +color.BgRGB(255, 128, 0).AddRGB(255, 255, 255).Println("orange background with white foreground") +``` + +### Use your own output (io.Writer) + +```go +// Use your own io.Writer output +color.New(color.FgBlue).Fprintln(myWriter, "blue color!") + +blue := color.New(color.FgBlue) +blue.Fprint(writer, "This will print text in blue.") +``` + +### Custom print functions (PrintFunc) + +```go +// Create a custom print function for convenience +red := color.New(color.FgRed).PrintfFunc() +red("Warning") +red("Error: %s", err) + +// Mix up multiple attributes +notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() +notice("Don't forget this...") +``` + +### Custom fprint functions (FprintFunc) + +```go +blue := color.New(color.FgBlue).FprintfFunc() +blue(myWriter, "important notice: %s", stars) + +// Mix up with multiple attributes +success := color.New(color.Bold, color.FgGreen).FprintlnFunc() +success(myWriter, "Don't forget this...") +``` + +### Insert into noncolor strings (SprintFunc) + +```go +// Create SprintXxx functions to mix strings with other non-colorized strings: +yellow := color.New(color.FgYellow).SprintFunc() +red := color.New(color.FgRed).SprintFunc() +fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error")) + +info := color.New(color.FgWhite, color.BgGreen).SprintFunc() +fmt.Printf("This %s rocks!\n", info("package")) + +// Use helper functions +fmt.Println("This", color.RedString("warning"), "should be not neglected.") +fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.") + +// Windows supported too! Just don't forget to change the output to color.Output +fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) +``` + +### Plug into existing code + +```go +// Use handy standard colors +color.Set(color.FgYellow) + +fmt.Println("Existing text will now be in yellow") +fmt.Printf("This one %s\n", "too") + +color.Unset() // Don't forget to unset + +// You can mix up parameters +color.Set(color.FgMagenta, color.Bold) +defer color.Unset() // Use it in your function + +fmt.Println("All text will now be bold magenta.") +``` + +### Disable/Enable color + +There might be a case where you want to explicitly disable/enable color output. the +`go-isatty` package will automatically disable color output for non-tty output streams +(for example if the output were piped directly to `less`). + +The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment +variable is set to a non-empty string. + +`Color` has support to disable/enable colors programmatically both globally and +for single color definitions. For example suppose you have a CLI app and a +`-no-color` bool flag. You can easily disable the color output with: + +```go +var flagNoColor = flag.Bool("no-color", false, "Disable color output") + +if *flagNoColor { + color.NoColor = true // disables colorized output +} +``` + +It also has support for single color definitions (local). You can +disable/enable color output on the fly: + +```go +c := color.New(color.FgCyan) +c.Println("Prints cyan text") + +c.DisableColor() +c.Println("This is printed without any color") + +c.EnableColor() +c.Println("This prints again cyan...") +``` + +## GitHub Actions + +To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams. + + +## Credits + +* [Fatih Arslan](https://github.com/fatih) +* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable) + +## License + +The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go new file mode 100644 index 000000000..ee39b408e --- /dev/null +++ b/vendor/github.com/fatih/color/color.go @@ -0,0 +1,685 @@ +package color + +import ( + "fmt" + "io" + "os" + "strconv" + "strings" + "sync" + + "github.com/mattn/go-colorable" + "github.com/mattn/go-isatty" +) + +var ( + // NoColor defines if the output is colorized or not. It's dynamically set to + // false or true based on the stdout's file descriptor referring to a terminal + // or not. It's also set to true if the NO_COLOR environment variable is + // set (regardless of its value). This is a global option and affects all + // colors. For more control over each color block use the methods + // DisableColor() individually. + NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" || + (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) + + // Output defines the standard output of the print functions. By default, + // os.Stdout is used. + Output = colorable.NewColorableStdout() + + // Error defines a color supporting writer for os.Stderr. + Error = colorable.NewColorableStderr() + + // colorsCache is used to reduce the count of created Color objects and + // allows to reuse already created objects with required Attribute. + colorsCache = make(map[Attribute]*Color) + colorsCacheMu sync.Mutex // protects colorsCache +) + +// noColorIsSet returns true if the environment variable NO_COLOR is set to a non-empty string. +func noColorIsSet() bool { + return os.Getenv("NO_COLOR") != "" +} + +// Color defines a custom color object which is defined by SGR parameters. +type Color struct { + params []Attribute + noColor *bool +} + +// Attribute defines a single SGR Code +type Attribute int + +const escape = "\x1b" + +// Base attributes +const ( + Reset Attribute = iota + Bold + Faint + Italic + Underline + BlinkSlow + BlinkRapid + ReverseVideo + Concealed + CrossedOut +) + +const ( + ResetBold Attribute = iota + 22 + ResetItalic + ResetUnderline + ResetBlinking + _ + ResetReversed + ResetConcealed + ResetCrossedOut +) + +var mapResetAttributes map[Attribute]Attribute = map[Attribute]Attribute{ + Bold: ResetBold, + Faint: ResetBold, + Italic: ResetItalic, + Underline: ResetUnderline, + BlinkSlow: ResetBlinking, + BlinkRapid: ResetBlinking, + ReverseVideo: ResetReversed, + Concealed: ResetConcealed, + CrossedOut: ResetCrossedOut, +} + +// Foreground text colors +const ( + FgBlack Attribute = iota + 30 + FgRed + FgGreen + FgYellow + FgBlue + FgMagenta + FgCyan + FgWhite + + // used internally for 256 and 24-bit coloring + foreground +) + +// Foreground Hi-Intensity text colors +const ( + FgHiBlack Attribute = iota + 90 + FgHiRed + FgHiGreen + FgHiYellow + FgHiBlue + FgHiMagenta + FgHiCyan + FgHiWhite +) + +// Background text colors +const ( + BgBlack Attribute = iota + 40 + BgRed + BgGreen + BgYellow + BgBlue + BgMagenta + BgCyan + BgWhite + + // used internally for 256 and 24-bit coloring + background +) + +// Background Hi-Intensity text colors +const ( + BgHiBlack Attribute = iota + 100 + BgHiRed + BgHiGreen + BgHiYellow + BgHiBlue + BgHiMagenta + BgHiCyan + BgHiWhite +) + +// New returns a newly created color object. +func New(value ...Attribute) *Color { + c := &Color{ + params: make([]Attribute, 0), + } + + if noColorIsSet() { + c.noColor = boolPtr(true) + } + + c.Add(value...) + return c +} + +// RGB returns a new foreground color in 24-bit RGB. +func RGB(r, g, b int) *Color { + return New(foreground, 2, Attribute(r), Attribute(g), Attribute(b)) +} + +// BgRGB returns a new background color in 24-bit RGB. +func BgRGB(r, g, b int) *Color { + return New(background, 2, Attribute(r), Attribute(g), Attribute(b)) +} + +// AddRGB is used to chain foreground RGB SGR parameters. Use as many as parameters to combine +// and create custom color objects. Example: .Add(34, 0, 12).Add(255, 128, 0). +func (c *Color) AddRGB(r, g, b int) *Color { + c.params = append(c.params, foreground, 2, Attribute(r), Attribute(g), Attribute(b)) + return c +} + +// AddRGB is used to chain background RGB SGR parameters. Use as many as parameters to combine +// and create custom color objects. Example: .Add(34, 0, 12).Add(255, 128, 0). +func (c *Color) AddBgRGB(r, g, b int) *Color { + c.params = append(c.params, background, 2, Attribute(r), Attribute(g), Attribute(b)) + return c +} + +// Set sets the given parameters immediately. It will change the color of +// output with the given SGR parameters until color.Unset() is called. +func Set(p ...Attribute) *Color { + c := New(p...) + c.Set() + return c +} + +// Unset resets all escape attributes and clears the output. Usually should +// be called after Set(). +func Unset() { + if NoColor { + return + } + + fmt.Fprintf(Output, "%s[%dm", escape, Reset) +} + +// Set sets the SGR sequence. +func (c *Color) Set() *Color { + if c.isNoColorSet() { + return c + } + + fmt.Fprint(Output, c.format()) + return c +} + +func (c *Color) unset() { + if c.isNoColorSet() { + return + } + + Unset() +} + +// SetWriter is used to set the SGR sequence with the given io.Writer. This is +// a low-level function, and users should use the higher-level functions, such +// as color.Fprint, color.Print, etc. +func (c *Color) SetWriter(w io.Writer) *Color { + if c.isNoColorSet() { + return c + } + + fmt.Fprint(w, c.format()) + return c +} + +// UnsetWriter resets all escape attributes and clears the output with the give +// io.Writer. Usually should be called after SetWriter(). +func (c *Color) UnsetWriter(w io.Writer) { + if c.isNoColorSet() { + return + } + + if NoColor { + return + } + + fmt.Fprintf(w, "%s[%dm", escape, Reset) +} + +// Add is used to chain SGR parameters. Use as many as parameters to combine +// and create custom color objects. Example: Add(color.FgRed, color.Underline). +func (c *Color) Add(value ...Attribute) *Color { + c.params = append(c.params, value...) + return c +} + +// Fprint formats using the default formats for its operands and writes to w. +// Spaces are added between operands when neither is a string. +// It returns the number of bytes written and any write error encountered. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + c.SetWriter(w) + defer c.UnsetWriter(w) + + return fmt.Fprint(w, a...) +} + +// Print formats using the default formats for its operands and writes to +// standard output. Spaces are added between operands when neither is a +// string. It returns the number of bytes written and any write error +// encountered. This is the standard fmt.Print() method wrapped with the given +// color. +func (c *Color) Print(a ...interface{}) (n int, err error) { + c.Set() + defer c.unset() + + return fmt.Fprint(Output, a...) +} + +// Fprintf formats according to a format specifier and writes to w. +// It returns the number of bytes written and any write error encountered. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + c.SetWriter(w) + defer c.UnsetWriter(w) + + return fmt.Fprintf(w, format, a...) +} + +// Printf formats according to a format specifier and writes to standard output. +// It returns the number of bytes written and any write error encountered. +// This is the standard fmt.Printf() method wrapped with the given color. +func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { + c.Set() + defer c.unset() + + return fmt.Fprintf(Output, format, a...) +} + +// Fprintln formats using the default formats for its operands and writes to w. +// Spaces are always added between operands and a newline is appended. +// On Windows, users should wrap w with colorable.NewColorable() if w is of +// type *os.File. +func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.wrap(sprintln(a...))) +} + +// Println formats using the default formats for its operands and writes to +// standard output. Spaces are always added between operands and a newline is +// appended. It returns the number of bytes written and any write error +// encountered. This is the standard fmt.Print() method wrapped with the given +// color. +func (c *Color) Println(a ...interface{}) (n int, err error) { + return fmt.Fprintln(Output, c.wrap(sprintln(a...))) +} + +// Sprint is just like Print, but returns a string instead of printing it. +func (c *Color) Sprint(a ...interface{}) string { + return c.wrap(fmt.Sprint(a...)) +} + +// Sprintln is just like Println, but returns a string instead of printing it. +func (c *Color) Sprintln(a ...interface{}) string { + return c.wrap(sprintln(a...)) + "\n" +} + +// Sprintf is just like Printf, but returns a string instead of printing it. +func (c *Color) Sprintf(format string, a ...interface{}) string { + return c.wrap(fmt.Sprintf(format, a...)) +} + +// FprintFunc returns a new function that prints the passed arguments as +// colorized with color.Fprint(). +func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) { + return func(w io.Writer, a ...interface{}) { + c.Fprint(w, a...) + } +} + +// PrintFunc returns a new function that prints the passed arguments as +// colorized with color.Print(). +func (c *Color) PrintFunc() func(a ...interface{}) { + return func(a ...interface{}) { + c.Print(a...) + } +} + +// FprintfFunc returns a new function that prints the passed arguments as +// colorized with color.Fprintf(). +func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) { + return func(w io.Writer, format string, a ...interface{}) { + c.Fprintf(w, format, a...) + } +} + +// PrintfFunc returns a new function that prints the passed arguments as +// colorized with color.Printf(). +func (c *Color) PrintfFunc() func(format string, a ...interface{}) { + return func(format string, a ...interface{}) { + c.Printf(format, a...) + } +} + +// FprintlnFunc returns a new function that prints the passed arguments as +// colorized with color.Fprintln(). +func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) { + return func(w io.Writer, a ...interface{}) { + c.Fprintln(w, a...) + } +} + +// PrintlnFunc returns a new function that prints the passed arguments as +// colorized with color.Println(). +func (c *Color) PrintlnFunc() func(a ...interface{}) { + return func(a ...interface{}) { + c.Println(a...) + } +} + +// SprintFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprint(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output, example: +// +// put := New(FgYellow).SprintFunc() +// fmt.Fprintf(color.Output, "This is a %s", put("warning")) +func (c *Color) SprintFunc() func(a ...interface{}) string { + return func(a ...interface{}) string { + return c.wrap(fmt.Sprint(a...)) + } +} + +// SprintfFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprintf(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output. +func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { + return func(format string, a ...interface{}) string { + return c.wrap(fmt.Sprintf(format, a...)) + } +} + +// SprintlnFunc returns a new function that returns colorized strings for the +// given arguments with fmt.Sprintln(). Useful to put into or mix into other +// string. Windows users should use this in conjunction with color.Output. +func (c *Color) SprintlnFunc() func(a ...interface{}) string { + return func(a ...interface{}) string { + return c.wrap(sprintln(a...)) + "\n" + } +} + +// sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m" +// an example output might be: "1;36" -> bold cyan +func (c *Color) sequence() string { + format := make([]string, len(c.params)) + for i, v := range c.params { + format[i] = strconv.Itoa(int(v)) + } + + return strings.Join(format, ";") +} + +// wrap wraps the s string with the colors attributes. The string is ready to +// be printed. +func (c *Color) wrap(s string) string { + if c.isNoColorSet() { + return s + } + + return c.format() + s + c.unformat() +} + +func (c *Color) format() string { + return fmt.Sprintf("%s[%sm", escape, c.sequence()) +} + +func (c *Color) unformat() string { + //return fmt.Sprintf("%s[%dm", escape, Reset) + //for each element in sequence let's use the specific reset escape, or the generic one if not found + format := make([]string, len(c.params)) + for i, v := range c.params { + format[i] = strconv.Itoa(int(Reset)) + ra, ok := mapResetAttributes[v] + if ok { + format[i] = strconv.Itoa(int(ra)) + } + } + + return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";")) +} + +// DisableColor disables the color output. Useful to not change any existing +// code and still being able to output. Can be used for flags like +// "--no-color". To enable back use EnableColor() method. +func (c *Color) DisableColor() { + c.noColor = boolPtr(true) +} + +// EnableColor enables the color output. Use it in conjunction with +// DisableColor(). Otherwise, this method has no side effects. +func (c *Color) EnableColor() { + c.noColor = boolPtr(false) +} + +func (c *Color) isNoColorSet() bool { + // check first if we have user set action + if c.noColor != nil { + return *c.noColor + } + + // if not return the global option, which is disabled by default + return NoColor +} + +// Equals returns a boolean value indicating whether two colors are equal. +func (c *Color) Equals(c2 *Color) bool { + if c == nil && c2 == nil { + return true + } + if c == nil || c2 == nil { + return false + } + if len(c.params) != len(c2.params) { + return false + } + + for _, attr := range c.params { + if !c2.attrExists(attr) { + return false + } + } + + return true +} + +func (c *Color) attrExists(a Attribute) bool { + for _, attr := range c.params { + if attr == a { + return true + } + } + + return false +} + +func boolPtr(v bool) *bool { + return &v +} + +func getCachedColor(p Attribute) *Color { + colorsCacheMu.Lock() + defer colorsCacheMu.Unlock() + + c, ok := colorsCache[p] + if !ok { + c = New(p) + colorsCache[p] = c + } + + return c +} + +func colorPrint(format string, p Attribute, a ...interface{}) { + c := getCachedColor(p) + + if !strings.HasSuffix(format, "\n") { + format += "\n" + } + + if len(a) == 0 { + c.Print(format) + } else { + c.Printf(format, a...) + } +} + +func colorString(format string, p Attribute, a ...interface{}) string { + c := getCachedColor(p) + + if len(a) == 0 { + return c.SprintFunc()(format) + } + + return c.SprintfFunc()(format, a...) +} + +// Black is a convenient helper function to print with black foreground. A +// newline is appended to format by default. +func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) } + +// Red is a convenient helper function to print with red foreground. A +// newline is appended to format by default. +func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) } + +// Green is a convenient helper function to print with green foreground. A +// newline is appended to format by default. +func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) } + +// Yellow is a convenient helper function to print with yellow foreground. +// A newline is appended to format by default. +func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) } + +// Blue is a convenient helper function to print with blue foreground. A +// newline is appended to format by default. +func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) } + +// Magenta is a convenient helper function to print with magenta foreground. +// A newline is appended to format by default. +func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) } + +// Cyan is a convenient helper function to print with cyan foreground. A +// newline is appended to format by default. +func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) } + +// White is a convenient helper function to print with white foreground. A +// newline is appended to format by default. +func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) } + +// BlackString is a convenient helper function to return a string with black +// foreground. +func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) } + +// RedString is a convenient helper function to return a string with red +// foreground. +func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) } + +// GreenString is a convenient helper function to return a string with green +// foreground. +func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) } + +// YellowString is a convenient helper function to return a string with yellow +// foreground. +func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) } + +// BlueString is a convenient helper function to return a string with blue +// foreground. +func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) } + +// MagentaString is a convenient helper function to return a string with magenta +// foreground. +func MagentaString(format string, a ...interface{}) string { + return colorString(format, FgMagenta, a...) +} + +// CyanString is a convenient helper function to return a string with cyan +// foreground. +func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) } + +// WhiteString is a convenient helper function to return a string with white +// foreground. +func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) } + +// HiBlack is a convenient helper function to print with hi-intensity black foreground. A +// newline is appended to format by default. +func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) } + +// HiRed is a convenient helper function to print with hi-intensity red foreground. A +// newline is appended to format by default. +func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) } + +// HiGreen is a convenient helper function to print with hi-intensity green foreground. A +// newline is appended to format by default. +func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) } + +// HiYellow is a convenient helper function to print with hi-intensity yellow foreground. +// A newline is appended to format by default. +func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) } + +// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A +// newline is appended to format by default. +func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) } + +// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground. +// A newline is appended to format by default. +func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) } + +// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A +// newline is appended to format by default. +func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) } + +// HiWhite is a convenient helper function to print with hi-intensity white foreground. A +// newline is appended to format by default. +func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) } + +// HiBlackString is a convenient helper function to return a string with hi-intensity black +// foreground. +func HiBlackString(format string, a ...interface{}) string { + return colorString(format, FgHiBlack, a...) +} + +// HiRedString is a convenient helper function to return a string with hi-intensity red +// foreground. +func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) } + +// HiGreenString is a convenient helper function to return a string with hi-intensity green +// foreground. +func HiGreenString(format string, a ...interface{}) string { + return colorString(format, FgHiGreen, a...) +} + +// HiYellowString is a convenient helper function to return a string with hi-intensity yellow +// foreground. +func HiYellowString(format string, a ...interface{}) string { + return colorString(format, FgHiYellow, a...) +} + +// HiBlueString is a convenient helper function to return a string with hi-intensity blue +// foreground. +func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) } + +// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta +// foreground. +func HiMagentaString(format string, a ...interface{}) string { + return colorString(format, FgHiMagenta, a...) +} + +// HiCyanString is a convenient helper function to return a string with hi-intensity cyan +// foreground. +func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) } + +// HiWhiteString is a convenient helper function to return a string with hi-intensity white +// foreground. +func HiWhiteString(format string, a ...interface{}) string { + return colorString(format, FgHiWhite, a...) +} + +// sprintln is a helper function to format a string with fmt.Sprintln and trim the trailing newline. +func sprintln(a ...interface{}) string { + return strings.TrimSuffix(fmt.Sprintln(a...), "\n") +} diff --git a/vendor/github.com/fatih/color/color_windows.go b/vendor/github.com/fatih/color/color_windows.go new file mode 100644 index 000000000..be01c558e --- /dev/null +++ b/vendor/github.com/fatih/color/color_windows.go @@ -0,0 +1,19 @@ +package color + +import ( + "os" + + "golang.org/x/sys/windows" +) + +func init() { + // Opt-in for ansi color support for current process. + // https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences + var outMode uint32 + out := windows.Handle(os.Stdout.Fd()) + if err := windows.GetConsoleMode(out, &outMode); err != nil { + return + } + outMode |= windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING + _ = windows.SetConsoleMode(out, outMode) +} diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go new file mode 100644 index 000000000..9491ad541 --- /dev/null +++ b/vendor/github.com/fatih/color/doc.go @@ -0,0 +1,134 @@ +/* +Package color is an ANSI color package to output colorized or SGR defined +output to the standard output. The API can be used in several way, pick one +that suits you. + +Use simple and default helper functions with predefined foreground colors: + + color.Cyan("Prints text in cyan.") + + // a newline will be appended automatically + color.Blue("Prints %s in blue.", "text") + + // More default foreground colors.. + color.Red("We have red") + color.Yellow("Yellow color too!") + color.Magenta("And many others ..") + + // Hi-intensity colors + color.HiGreen("Bright green color.") + color.HiBlack("Bright black means gray..") + color.HiWhite("Shiny white color!") + +However, there are times when custom color mixes are required. Below are some +examples to create custom color objects and use the print functions of each +separate color object. + + // Create a new color object + c := color.New(color.FgCyan).Add(color.Underline) + c.Println("Prints cyan text with an underline.") + + // Or just add them to New() + d := color.New(color.FgCyan, color.Bold) + d.Printf("This prints bold cyan %s\n", "too!.") + + + // Mix up foreground and background colors, create new mixes! + red := color.New(color.FgRed) + + boldRed := red.Add(color.Bold) + boldRed.Println("This will print text in bold red.") + + whiteBackground := red.Add(color.BgWhite) + whiteBackground.Println("Red text with White background.") + + // Use your own io.Writer output + color.New(color.FgBlue).Fprintln(myWriter, "blue color!") + + blue := color.New(color.FgBlue) + blue.Fprint(myWriter, "This will print text in blue.") + +You can create PrintXxx functions to simplify even more: + + // Create a custom print function for convenient + red := color.New(color.FgRed).PrintfFunc() + red("warning") + red("error: %s", err) + + // Mix up multiple attributes + notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() + notice("don't forget this...") + +You can also FprintXxx functions to pass your own io.Writer: + + blue := color.New(FgBlue).FprintfFunc() + blue(myWriter, "important notice: %s", stars) + + // Mix up with multiple attributes + success := color.New(color.Bold, color.FgGreen).FprintlnFunc() + success(myWriter, don't forget this...") + +Or create SprintXxx functions to mix strings with other non-colorized strings: + + yellow := New(FgYellow).SprintFunc() + red := New(FgRed).SprintFunc() + + fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error")) + + info := New(FgWhite, BgGreen).SprintFunc() + fmt.Printf("this %s rocks!\n", info("package")) + +Windows support is enabled by default. All Print functions work as intended. +However, only for color.SprintXXX functions, user should use fmt.FprintXXX and +set the output to color.Output: + + fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) + + info := New(FgWhite, BgGreen).SprintFunc() + fmt.Fprintf(color.Output, "this %s rocks!\n", info("package")) + +Using with existing code is possible. Just use the Set() method to set the +standard output to the given parameters. That way a rewrite of an existing +code is not required. + + // Use handy standard colors. + color.Set(color.FgYellow) + + fmt.Println("Existing text will be now in Yellow") + fmt.Printf("This one %s\n", "too") + + color.Unset() // don't forget to unset + + // You can mix up parameters + color.Set(color.FgMagenta, color.Bold) + defer color.Unset() // use it in your function + + fmt.Println("All text will be now bold magenta.") + +There might be a case where you want to disable color output (for example to +pipe the standard output of your app to somewhere else). `Color` has support to +disable colors both globally and for single color definition. For example +suppose you have a CLI app and a `--no-color` bool flag. You can easily disable +the color output with: + + var flagNoColor = flag.Bool("no-color", false, "Disable color output") + + if *flagNoColor { + color.NoColor = true // disables colorized output + } + +You can also disable the color by setting the NO_COLOR environment variable to any value. + +It also has support for single color definitions (local). You can +disable/enable color output on the fly: + + c := color.New(color.FgCyan) + c.Println("Prints cyan text") + + c.DisableColor() + c.Println("This is printed without any color") + + c.EnableColor() + c.Println("This prints again cyan...") +*/ +package color diff --git a/vendor/github.com/gobuffalo/flect/.gitignore b/vendor/github.com/gobuffalo/flect/.gitignore new file mode 100644 index 000000000..368971859 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/.gitignore @@ -0,0 +1,29 @@ +*.log +.DS_Store +doc +tmp +pkg +*.gem +*.pid +coverage +coverage.data +build/* +*.pbxuser +*.mode1v3 +.svn +profile +.console_history +.sass-cache/* +.rake_tasks~ +*.log.lck +solr/ +.jhw-cache/ +jhw.* +*.sublime* +node_modules/ +dist/ +generated/ +.vendor/ +bin/* +gin-bin +.idea/ diff --git a/vendor/github.com/gobuffalo/flect/.gometalinter.json b/vendor/github.com/gobuffalo/flect/.gometalinter.json new file mode 100644 index 000000000..e4f65a36e --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/.gometalinter.json @@ -0,0 +1,3 @@ +{ + "Enable": ["vet", "golint", "goimports", "deadcode", "gotype", "ineffassign", "misspell", "nakedret", "unconvert", "megacheck", "varcheck"] +} diff --git a/vendor/github.com/gobuffalo/flect/LICENSE b/vendor/github.com/gobuffalo/flect/LICENSE new file mode 100644 index 000000000..649efd437 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Mark Bates + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/gobuffalo/flect/Makefile b/vendor/github.com/gobuffalo/flect/Makefile new file mode 100644 index 000000000..0ac539f1c --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/Makefile @@ -0,0 +1,61 @@ +TAGS ?= "" +GO_BIN ?= "go" + +install: + $(GO_BIN) install -tags ${TAGS} -v . + make tidy + +tidy: +ifeq ($(GO111MODULE),on) + $(GO_BIN) mod tidy +else + echo skipping go mod tidy +endif + +deps: + $(GO_BIN) get -tags ${TAGS} -t ./... + make tidy + +build: + $(GO_BIN) build -v . + make tidy + +test: + $(GO_BIN) test -cover -tags ${TAGS} ./... + make tidy + +ci-deps: + $(GO_BIN) get -tags ${TAGS} -t ./... + +ci-test: + $(GO_BIN) test -tags ${TAGS} -race ./... + +lint: + go get github.com/golangci/golangci-lint/cmd/golangci-lint + golangci-lint run --enable-all + make tidy + +update: +ifeq ($(GO111MODULE),on) + rm go.* + $(GO_BIN) mod init + $(GO_BIN) mod tidy +else + $(GO_BIN) get -u -tags ${TAGS} +endif + make test + make install + make tidy + +release-test: + $(GO_BIN) test -tags ${TAGS} -race ./... + make tidy + +release: + $(GO_BIN) get github.com/gobuffalo/release + make tidy + release -y -f version.go --skip-packr + make tidy + + + diff --git a/vendor/github.com/gobuffalo/flect/README.md b/vendor/github.com/gobuffalo/flect/README.md new file mode 100644 index 000000000..14547e227 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/README.md @@ -0,0 +1,63 @@ +# Flect + +[![Go Reference](https://pkg.go.dev/badge/github.com/gobuffalo/flect.svg)](https://pkg.go.dev/github.com/gobuffalo/flect) +[![Standard Test](https://github.com/gobuffalo/flect/actions/workflows/standard-go-test.yml/badge.svg)](https://github.com/gobuffalo/flect/actions/workflows/standard-go-test.yml) +[![Go Report Card](https://goreportcard.com/badge/github.com/gobuffalo/flect)](https://goreportcard.com/report/github.com/gobuffalo/flect) + +This is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original. + +Flect provides word inflection features such as `Singularize` and `Pluralize` +for English nouns and text utility features such as `Camelize`, `Capitalize`, +`Humanize`, and more. + +Due to the flexibly-complex nature of English noun inflection, it is almost +impossible to cover all exceptions (such as identical/irregular plural). +With this reason along with the main purpose of Flect, which is to make it +easy to develop web application in Go, Flect has limitations with its own +rules. + +* It covers regular rule (adding -s or -es and of the word) +* It covers well-known irregular rules (such as -is to -es, -f to -ves, etc) + * https://en.wiktionary.org/wiki/Appendix:English_irregular_nouns#Rules +* It covers well-known irregular words (such as children, men, etc) +* If a word can be countable and uncountable like milk or time, it will be + treated as countable. +* If a word has more than one plural forms, which means it has at least one + irregular plural, we tried to find most popular one. (The selected plural + could be odd to you, please feel free to open an issue with back data) + * For example, we selected "stadiums" over "stadia", "dwarfs" over "dwarves" + * One or combination of en.wiktionary.org, britannica.com, and + trends.google.com are used to check the recent usage trends. +* However, we cannot cover all cases and some of our cases could not fit with + your situation. You can override the default with functions such as + `InsertPlural()`, `InsertSingular()`, or `LoadInfrections()`. +* If you have a json file named `inflections.json` in your application root, + the file will be automatically loaded as your custom inflection dictionary. + +## Installation + +```console +$ go get github.com/gobuffalo/flect +``` + + +## Packages + +### `github.com/gobuffalo/flect` + +The `github.com/gobuffalo/flect` package contains "basic" inflection tools, like pluralization, singularization, etc... + +#### The `Ident` Type + +In addition to helpful methods that take in a `string` and return a `string`, there is an `Ident` type that can be used to create new, custom, inflection rules. + +The `Ident` type contains two fields. + +* `Original` - This is the original `string` that was used to create the `Ident` +* `Parts` - This is a `[]string` that represents all of the "parts" of the string, that have been split apart, making the segments easier to work with + +Examples of creating new inflection rules using `Ident` can be found in the `github.com/gobuffalo/flect/name` package. + +### `github.com/gobuffalo/flect/name` + +The `github.com/gobuffalo/flect/name` package contains more "business" inflection rules like creating proper names, table names, etc... diff --git a/vendor/github.com/gobuffalo/flect/SHOULDERS.md b/vendor/github.com/gobuffalo/flect/SHOULDERS.md new file mode 100644 index 000000000..75222c6bc --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/SHOULDERS.md @@ -0,0 +1,12 @@ +# Flect Stands on the Shoulders of Giants + +Flect does not try to reinvent the wheel! Instead, it uses the already great wheels developed by the Go community and puts them all together in the best way possible. Without these giants, this project would not be possible. Please make sure to check them out and thank them for all of their hard work. + +Thank you to the following **GIANTS**: + +* [github.com/davecgh/go-spew](https://godoc.org/github.com/davecgh/go-spew) +* [github.com/pmezard/go-difflib](https://godoc.org/github.com/pmezard/go-difflib) +* [github.com/stretchr/objx](https://godoc.org/github.com/stretchr/objx) +* [github.com/stretchr/testify](https://godoc.org/github.com/stretchr/testify) +* [gopkg.in/check.v1](https://godoc.org/gopkg.in/check.v1) +* [gopkg.in/yaml.v3](https://godoc.org/gopkg.in/yaml.v3) diff --git a/vendor/github.com/gobuffalo/flect/acronyms.go b/vendor/github.com/gobuffalo/flect/acronyms.go new file mode 100644 index 000000000..b169724a4 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/acronyms.go @@ -0,0 +1,152 @@ +package flect + +import "sync" + +var acronymsMoot = &sync.RWMutex{} + +var baseAcronyms = map[string]bool{ + "OK": true, + "UTF8": true, + "HTML": true, + "JSON": true, + "JWT": true, + "ID": true, + "UUID": true, + "SQL": true, + "ACK": true, + "ACL": true, + "ADSL": true, + "AES": true, + "ANSI": true, + "API": true, + "ARP": true, + "ATM": true, + "BGP": true, + "BSS": true, + "CCITT": true, + "CHAP": true, + "CIDR": true, + "CIR": true, + "CLI": true, + "CPE": true, + "CPU": true, + "CRC": true, + "CRT": true, + "CSMA": true, + "CMOS": true, + "DCE": true, + "DEC": true, + "DES": true, + "DHCP": true, + "DNS": true, + "DRAM": true, + "DSL": true, + "DSLAM": true, + "DTE": true, + "DMI": true, + "EHA": true, + "EIA": true, + "EIGRP": true, + "EOF": true, + "ESS": true, + "FCC": true, + "FCS": true, + "FDDI": true, + "FTP": true, + "GBIC": true, + "gbps": true, + "GEPOF": true, + "HDLC": true, + "HTTP": true, + "HTTPS": true, + "IANA": true, + "ICMP": true, + "IDF": true, + "IDS": true, + "IEEE": true, + "IETF": true, + "IMAP": true, + "IP": true, + "IPS": true, + "ISDN": true, + "ISP": true, + "kbps": true, + "LACP": true, + "LAN": true, + "LAPB": true, + "LAPF": true, + "LLC": true, + "MAC": true, + "Mbps": true, + "MC": true, + "MDF": true, + "MIB": true, + "MoCA": true, + "MPLS": true, + "MTU": true, + "NAC": true, + "NAT": true, + "NBMA": true, + "NIC": true, + "NRZ": true, + "NRZI": true, + "NVRAM": true, + "OSI": true, + "OSPF": true, + "OUI": true, + "PAP": true, + "PAT": true, + "PC": true, + "PIM": true, + "PCM": true, + "PDU": true, + "POP3": true, + "POTS": true, + "PPP": true, + "PPTP": true, + "PTT": true, + "PVST": true, + "RAM": true, + "RARP": true, + "RFC": true, + "RIP": true, + "RLL": true, + "ROM": true, + "RSTP": true, + "RTP": true, + "RCP": true, + "SDLC": true, + "SFD": true, + "SFP": true, + "SLARP": true, + "SLIP": true, + "SMTP": true, + "SNA": true, + "SNAP": true, + "SNMP": true, + "SOF": true, + "SRAM": true, + "SSH": true, + "SSID": true, + "STP": true, + "SYN": true, + "TDM": true, + "TFTP": true, + "TIA": true, + "TOFU": true, + "UDP": true, + "URL": true, + "URI": true, + "USB": true, + "UTP": true, + "VC": true, + "VLAN": true, + "VLSM": true, + "VPN": true, + "W3C": true, + "WAN": true, + "WEP": true, + "WiFi": true, + "WPA": true, + "WWW": true, +} diff --git a/vendor/github.com/gobuffalo/flect/camelize.go b/vendor/github.com/gobuffalo/flect/camelize.go new file mode 100644 index 000000000..d8851c8f5 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/camelize.go @@ -0,0 +1,44 @@ +package flect + +import ( + "strings" + "unicode" +) + +// Camelize returns a camelize version of a string +// bob dylan = bobDylan +// widget_id = widgetID +// WidgetID = widgetID +func Camelize(s string) string { + return New(s).Camelize().String() +} + +// Camelize returns a camelize version of a string +// bob dylan = bobDylan +// widget_id = widgetID +// WidgetID = widgetID +func (i Ident) Camelize() Ident { + var out []string + for i, part := range i.Parts { + var x string + var capped bool + for _, c := range part { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + if i == 0 { + x += string(unicode.ToLower(c)) + continue + } + if !capped { + capped = true + x += string(unicode.ToUpper(c)) + continue + } + x += string(c) + } + } + if x != "" { + out = append(out, x) + } + } + return New(strings.Join(out, "")) +} diff --git a/vendor/github.com/gobuffalo/flect/capitalize.go b/vendor/github.com/gobuffalo/flect/capitalize.go new file mode 100644 index 000000000..78334fc0f --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/capitalize.go @@ -0,0 +1,24 @@ +package flect + +import "unicode" + +// Capitalize will cap the first letter of string +// user = User +// bob dylan = Bob dylan +// widget_id = Widget_id +func Capitalize(s string) string { + return New(s).Capitalize().String() +} + +// Capitalize will cap the first letter of string +// user = User +// bob dylan = Bob dylan +// widget_id = Widget_id +func (i Ident) Capitalize() Ident { + if len(i.Parts) == 0 { + return New("") + } + runes := []rune(i.Original) + runes[0] = unicode.ToTitle(runes[0]) + return New(string(runes)) +} diff --git a/vendor/github.com/gobuffalo/flect/custom_data.go b/vendor/github.com/gobuffalo/flect/custom_data.go new file mode 100644 index 000000000..efb445f67 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/custom_data.go @@ -0,0 +1,88 @@ +package flect + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" +) + +func init() { + loadCustomData("inflections.json", "INFLECT_PATH", "could not read inflection file", LoadInflections) + loadCustomData("acronyms.json", "ACRONYMS_PATH", "could not read acronyms file", LoadAcronyms) +} + +//CustomDataParser are functions that parse data like acronyms or +//plurals in the shape of a io.Reader it receives. +type CustomDataParser func(io.Reader) error + +func loadCustomData(defaultFile, env, readErrorMessage string, parser CustomDataParser) { + pwd, _ := os.Getwd() + path, found := os.LookupEnv(env) + if !found { + path = filepath.Join(pwd, defaultFile) + } + + if _, err := os.Stat(path); err != nil { + return + } + + b, err := ioutil.ReadFile(path) + if err != nil { + fmt.Printf("%s %s (%s)\n", readErrorMessage, path, err) + return + } + + if err = parser(bytes.NewReader(b)); err != nil { + fmt.Println(err) + } +} + +//LoadAcronyms loads rules from io.Reader param +func LoadAcronyms(r io.Reader) error { + m := []string{} + err := json.NewDecoder(r).Decode(&m) + + if err != nil { + return fmt.Errorf("could not decode acronyms JSON from reader: %s", err) + } + + acronymsMoot.Lock() + defer acronymsMoot.Unlock() + + for _, acronym := range m { + baseAcronyms[acronym] = true + } + + return nil +} + +//LoadInflections loads rules from io.Reader param +func LoadInflections(r io.Reader) error { + m := map[string]string{} + + err := json.NewDecoder(r).Decode(&m) + if err != nil { + return fmt.Errorf("could not decode inflection JSON from reader: %s", err) + } + + pluralMoot.Lock() + defer pluralMoot.Unlock() + singularMoot.Lock() + defer singularMoot.Unlock() + + for s, p := range m { + if strings.Contains(s, " ") || strings.Contains(p, " ") { + // flect works with parts, so multi-words should not be allowed + return fmt.Errorf("inflection elements should be a single word") + } + singleToPlural[s] = p + pluralToSingle[p] = s + } + + return nil +} diff --git a/vendor/github.com/gobuffalo/flect/dasherize.go b/vendor/github.com/gobuffalo/flect/dasherize.go new file mode 100644 index 000000000..c7a8a33e3 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/dasherize.go @@ -0,0 +1,34 @@ +package flect + +import ( + "strings" + "unicode" +) + +// Dasherize returns an alphanumeric, lowercased, dashed string +// Donald E. Knuth = donald-e-knuth +// Test with + sign = test-with-sign +// admin/WidgetID = admin-widget-id +func Dasherize(s string) string { + return New(s).Dasherize().String() +} + +// Dasherize returns an alphanumeric, lowercased, dashed string +// Donald E. Knuth = donald-e-knuth +// Test with + sign = test-with-sign +// admin/WidgetID = admin-widget-id +func (i Ident) Dasherize() Ident { + var parts []string + + for _, part := range i.Parts { + var x string + for _, c := range part { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + x += string(c) + } + } + parts = xappend(parts, x) + } + + return New(strings.ToLower(strings.Join(parts, "-"))) +} diff --git a/vendor/github.com/gobuffalo/flect/flect.go b/vendor/github.com/gobuffalo/flect/flect.go new file mode 100644 index 000000000..ee81b6f2b --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/flect.go @@ -0,0 +1,43 @@ +/* +Package flect is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original. +*/ +package flect + +import ( + "strings" + "unicode" +) + +var spaces = []rune{'_', ' ', ':', '-', '/'} + +func isSpace(c rune) bool { + for _, r := range spaces { + if r == c { + return true + } + } + return unicode.IsSpace(c) +} + +func xappend(a []string, ss ...string) []string { + for _, s := range ss { + s = strings.TrimSpace(s) + for _, x := range spaces { + s = strings.Trim(s, string(x)) + } + if _, ok := baseAcronyms[strings.ToUpper(s)]; ok { + s = strings.ToUpper(s) + } + if s != "" { + a = append(a, s) + } + } + return a +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/vendor/github.com/gobuffalo/flect/humanize.go b/vendor/github.com/gobuffalo/flect/humanize.go new file mode 100644 index 000000000..5100bfb7e --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/humanize.go @@ -0,0 +1,36 @@ +package flect + +import ( + "strings" +) + +// Humanize returns first letter of sentence capitalized. +// Common acronyms are capitalized as well. +// Other capital letters in string are left as provided. +// +// employee_salary = Employee salary +// employee_id = employee ID +// employee_mobile_number = Employee mobile number +// first_Name = First Name +// firstName = First Name +func Humanize(s string) string { + return New(s).Humanize().String() +} + +// Humanize First letter of sentence capitalized +func (i Ident) Humanize() Ident { + if len(i.Original) == 0 { + return New("") + } + + if strings.TrimSpace(i.Original) == "" { + return i + } + + parts := xappend([]string{}, Titleize(i.Parts[0])) + if len(i.Parts) > 1 { + parts = xappend(parts, i.Parts[1:]...) + } + + return New(strings.Join(parts, " ")) +} diff --git a/vendor/github.com/gobuffalo/flect/ident.go b/vendor/github.com/gobuffalo/flect/ident.go new file mode 100644 index 000000000..9189e9a39 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/ident.go @@ -0,0 +1,122 @@ +package flect + +import ( + "encoding" + "strings" + "unicode" + "unicode/utf8" +) + +// Ident represents the string and it's parts +type Ident struct { + Original string + Parts []string +} + +// String implements fmt.Stringer and returns the original string +func (i Ident) String() string { + return i.Original +} + +// New creates a new Ident from the string +func New(s string) Ident { + i := Ident{ + Original: s, + Parts: toParts(s), + } + + return i +} + +func toParts(s string) []string { + parts := []string{} + s = strings.TrimSpace(s) + if len(s) == 0 { + return parts + } + if _, ok := baseAcronyms[strings.ToUpper(s)]; ok { + return []string{strings.ToUpper(s)} + } + var prev rune + var x strings.Builder + x.Grow(len(s)) + for _, c := range s { + // fmt.Println("### cs ->", cs) + // fmt.Println("### unicode.IsControl(c) ->", unicode.IsControl(c)) + // fmt.Println("### unicode.IsDigit(c) ->", unicode.IsDigit(c)) + // fmt.Println("### unicode.IsGraphic(c) ->", unicode.IsGraphic(c)) + // fmt.Println("### unicode.IsLetter(c) ->", unicode.IsLetter(c)) + // fmt.Println("### unicode.IsLower(c) ->", unicode.IsLower(c)) + // fmt.Println("### unicode.IsMark(c) ->", unicode.IsMark(c)) + // fmt.Println("### unicode.IsPrint(c) ->", unicode.IsPrint(c)) + // fmt.Println("### unicode.IsPunct(c) ->", unicode.IsPunct(c)) + // fmt.Println("### unicode.IsSpace(c) ->", unicode.IsSpace(c)) + // fmt.Println("### unicode.IsTitle(c) ->", unicode.IsTitle(c)) + // fmt.Println("### unicode.IsUpper(c) ->", unicode.IsUpper(c)) + if !utf8.ValidRune(c) { + continue + } + + if isSpace(c) { + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) + prev = c + continue + } + + if unicode.IsUpper(c) && !unicode.IsUpper(prev) { + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) + prev = c + continue + } + if unicode.IsUpper(c) && baseAcronyms[strings.ToUpper(x.String())] { + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) + prev = c + continue + } + if unicode.IsLetter(c) || unicode.IsDigit(c) || unicode.IsPunct(c) || c == '`' { + prev = c + x.WriteRune(c) + continue + } + + parts = xappend(parts, x.String()) + x.Reset() + prev = c + } + parts = xappend(parts, x.String()) + + return parts +} + +var _ encoding.TextUnmarshaler = &Ident{} +var _ encoding.TextMarshaler = &Ident{} + +// LastPart returns the last part/word of the original string +func (i *Ident) LastPart() string { + if len(i.Parts) == 0 { + return "" + } + return i.Parts[len(i.Parts)-1] +} + +// ReplaceSuffix creates a new Ident with the original suffix replaced by new +func (i Ident) ReplaceSuffix(orig, new string) Ident { + return New(strings.TrimSuffix(i.Original, orig) + new) +} + +//UnmarshalText unmarshalls byte array into the Ident +func (i *Ident) UnmarshalText(data []byte) error { + (*i) = New(string(data)) + return nil +} + +//MarshalText marshals Ident into byte array +func (i Ident) MarshalText() ([]byte, error) { + return []byte(i.Original), nil +} diff --git a/vendor/github.com/gobuffalo/flect/lower_upper.go b/vendor/github.com/gobuffalo/flect/lower_upper.go new file mode 100644 index 000000000..930da58d8 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/lower_upper.go @@ -0,0 +1,13 @@ +package flect + +import "strings" + +// ToUpper is a convience wrapper for strings.ToUpper +func (i Ident) ToUpper() Ident { + return New(strings.ToUpper(i.Original)) +} + +// ToLower is a convience wrapper for strings.ToLower +func (i Ident) ToLower() Ident { + return New(strings.ToLower(i.Original)) +} diff --git a/vendor/github.com/gobuffalo/flect/ordinalize.go b/vendor/github.com/gobuffalo/flect/ordinalize.go new file mode 100644 index 000000000..1ce27b3a0 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/ordinalize.go @@ -0,0 +1,43 @@ +package flect + +import ( + "fmt" + "strconv" +) + +// Ordinalize converts a number to an ordinal version +// 42 = 42nd +// 45 = 45th +// 1 = 1st +func Ordinalize(s string) string { + return New(s).Ordinalize().String() +} + +// Ordinalize converts a number to an ordinal version +// 42 = 42nd +// 45 = 45th +// 1 = 1st +func (i Ident) Ordinalize() Ident { + number, err := strconv.Atoi(i.Original) + if err != nil { + return i + } + var s string + switch abs(number) % 100 { + case 11, 12, 13: + s = fmt.Sprintf("%dth", number) + default: + switch abs(number) % 10 { + case 1: + s = fmt.Sprintf("%dst", number) + case 2: + s = fmt.Sprintf("%dnd", number) + case 3: + s = fmt.Sprintf("%drd", number) + } + } + if s != "" { + return New(s) + } + return New(fmt.Sprintf("%dth", number)) +} diff --git a/vendor/github.com/gobuffalo/flect/pascalize.go b/vendor/github.com/gobuffalo/flect/pascalize.go new file mode 100644 index 000000000..6396d0d4e --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/pascalize.go @@ -0,0 +1,32 @@ +package flect + +import ( + "strings" +) + +// Pascalize returns a string with each segment capitalized +// user = User +// bob dylan = BobDylan +// widget_id = WidgetID +func Pascalize(s string) string { + return New(s).Pascalize().String() +} + +// Pascalize returns a string with each segment capitalized +// user = User +// bob dylan = BobDylan +// widget_id = WidgetID +func (i Ident) Pascalize() Ident { + c := i.Camelize() + if len(c.String()) == 0 { + return c + } + if len(i.Parts) == 0 { + return i + } + capLen := 1 + if _, ok := baseAcronyms[strings.ToUpper(i.Parts[0])]; ok { + capLen = len(i.Parts[0]) + } + return New(string(strings.ToUpper(c.Original[0:capLen])) + c.Original[capLen:]) +} diff --git a/vendor/github.com/gobuffalo/flect/plural_rules.go b/vendor/github.com/gobuffalo/flect/plural_rules.go new file mode 100644 index 000000000..3904e7974 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/plural_rules.go @@ -0,0 +1,417 @@ +package flect + +import "fmt" + +var pluralRules = []rule{} + +// AddPlural adds a rule that will replace the given suffix with the replacement suffix. +// The name is confusing. This function will be deprecated in the next release. +func AddPlural(suffix string, repl string) { + InsertPluralRule(suffix, repl) +} + +// InsertPluralRule inserts a rule that will replace the given suffix with +// the repl(acement) at the begining of the list of the pluralize rules. +func InsertPluralRule(suffix, repl string) { + pluralMoot.Lock() + defer pluralMoot.Unlock() + + pluralRules = append([]rule{{ + suffix: suffix, + fn: simpleRuleFunc(suffix, repl), + }}, pluralRules...) + + pluralRules = append([]rule{{ + suffix: repl, + fn: noop, + }}, pluralRules...) +} + +type word struct { + singular string + plural string + alternative string + unidirectional bool // plural to singular is not possible (or bad) + uncountable bool + exact bool +} + +// dictionary is the main table for singularize and pluralize. +// All words in the dictionary will be added to singleToPlural, pluralToSingle +// and singlePluralAssertions by init() functions. +var dictionary = []word{ + // identicals https://en.wikipedia.org/wiki/English_plurals#Nouns_with_identical_singular_and_plural + {singular: "aircraft", plural: "aircraft"}, + {singular: "beef", plural: "beef", alternative: "beefs"}, + {singular: "bison", plural: "bison"}, + {singular: "blues", plural: "blues", unidirectional: true}, + {singular: "chassis", plural: "chassis"}, + {singular: "deer", plural: "deer"}, + {singular: "fish", plural: "fish", alternative: "fishes"}, + {singular: "moose", plural: "moose"}, + {singular: "police", plural: "police"}, + {singular: "salmon", plural: "salmon", alternative: "salmons"}, + {singular: "series", plural: "series"}, + {singular: "sheep", plural: "sheep"}, + {singular: "shrimp", plural: "shrimp", alternative: "shrimps"}, + {singular: "species", plural: "species"}, + {singular: "swine", plural: "swine", alternative: "swines"}, + {singular: "trout", plural: "trout", alternative: "trouts"}, + {singular: "tuna", plural: "tuna", alternative: "tunas"}, + {singular: "you", plural: "you"}, + // -en https://en.wikipedia.org/wiki/English_plurals#Plurals_in_-(e)n + {singular: "child", plural: "children"}, + {singular: "ox", plural: "oxen", exact: true}, + // apophonic https://en.wikipedia.org/wiki/English_plurals#Apophonic_plurals + {singular: "foot", plural: "feet"}, + {singular: "goose", plural: "geese"}, + {singular: "man", plural: "men"}, + {singular: "human", plural: "humans"}, // not humen + {singular: "louse", plural: "lice", exact: true}, + {singular: "mouse", plural: "mice"}, + {singular: "tooth", plural: "teeth"}, + {singular: "woman", plural: "women"}, + // misc https://en.wikipedia.org/wiki/English_plurals#Miscellaneous_irregular_plurals + {singular: "die", plural: "dice", exact: true}, + {singular: "person", plural: "people"}, + + // Words from French that end in -u add an x; in addition to eau to eaux rule + {singular: "adieu", plural: "adieux", alternative: "adieus"}, + {singular: "fabliau", plural: "fabliaux"}, + {singular: "bureau", plural: "bureaus", alternative: "bureaux"}, // popular + + // Words from Greek that end in -on change -on to -a; in addition to hedron rule + {singular: "criterion", plural: "criteria"}, + {singular: "ganglion", plural: "ganglia", alternative: "ganglions"}, + {singular: "lexicon", plural: "lexica", alternative: "lexicons"}, + {singular: "mitochondrion", plural: "mitochondria", alternative: "mitochondrions"}, + {singular: "noumenon", plural: "noumena"}, + {singular: "phenomenon", plural: "phenomena"}, + {singular: "taxon", plural: "taxa"}, + + // Words from Latin that end in -um change -um to -a; in addition to some rules + {singular: "media", plural: "media"}, // popular case: media -> media + {singular: "medium", plural: "media", alternative: "mediums", unidirectional: true}, + {singular: "stadium", plural: "stadiums", alternative: "stadia"}, + {singular: "aquarium", plural: "aquaria", alternative: "aquariums"}, + {singular: "auditorium", plural: "auditoria", alternative: "auditoriums"}, + {singular: "symposium", plural: "symposia", alternative: "symposiums"}, + {singular: "curriculum", plural: "curriculums", alternative: "curricula"}, // ulum + {singular: "quota", plural: "quotas"}, + + // Words from Latin that end in -us change -us to -i or -era + {singular: "alumnus", plural: "alumni", alternative: "alumnuses"}, // -i + {singular: "bacillus", plural: "bacilli"}, + {singular: "cactus", plural: "cacti", alternative: "cactuses"}, + {singular: "coccus", plural: "cocci"}, + {singular: "focus", plural: "foci", alternative: "focuses"}, + {singular: "locus", plural: "loci", alternative: "locuses"}, + {singular: "nucleus", plural: "nuclei", alternative: "nucleuses"}, + {singular: "octopus", plural: "octupuses", alternative: "octopi"}, + {singular: "radius", plural: "radii", alternative: "radiuses"}, + {singular: "syllabus", plural: "syllabi"}, + {singular: "corpus", plural: "corpora", alternative: "corpuses"}, // -ra + {singular: "genus", plural: "genera"}, + + // Words from Latin that end in -a change -a to -ae + {singular: "alumna", plural: "alumnae"}, + {singular: "vertebra", plural: "vertebrae"}, + {singular: "differentia", plural: "differentiae"}, // -tia + {singular: "minutia", plural: "minutiae"}, + {singular: "vita", plural: "vitae"}, // -ita + {singular: "larva", plural: "larvae"}, // -va + {singular: "postcava", plural: "postcavae"}, + {singular: "praecava", plural: "praecavae"}, + {singular: "uva", plural: "uvae"}, + + // Words from Latin that end in -ex change -ex to -ices + {singular: "apex", plural: "apices", alternative: "apexes"}, + {singular: "codex", plural: "codices", alternative: "codexes"}, + {singular: "index", plural: "indices", alternative: "indexes"}, + {singular: "latex", plural: "latices", alternative: "latexes"}, + {singular: "vertex", plural: "vertices", alternative: "vertexes"}, + {singular: "vortex", plural: "vortices", alternative: "vortexes"}, + + // Words from Latin that end in -ix change -ix to -ices (eg, matrix becomes matrices) + {singular: "appendix", plural: "appendices", alternative: "appendixes"}, + {singular: "radix", plural: "radices", alternative: "radixes"}, + {singular: "helix", plural: "helices", alternative: "helixes"}, + + // Words from Latin that end in -is change -is to -es + {singular: "axis", plural: "axes", exact: true}, + {singular: "crisis", plural: "crises"}, + {singular: "ellipsis", plural: "ellipses", unidirectional: true}, // ellipse + {singular: "genesis", plural: "geneses"}, + {singular: "oasis", plural: "oases"}, + {singular: "thesis", plural: "theses"}, + {singular: "testis", plural: "testes"}, + {singular: "base", plural: "bases"}, // popular case + {singular: "basis", plural: "bases", unidirectional: true}, + + {singular: "alias", plural: "aliases", exact: true}, // no alia, no aliasis + {singular: "vedalia", plural: "vedalias"}, // no vedalium, no vedaliases + + // Words that end in -ch, -o, -s, -sh, -x, -z (can be conflict with the others) + {singular: "use", plural: "uses", exact: true}, // us vs use + {singular: "abuse", plural: "abuses"}, + {singular: "cause", plural: "causes"}, + {singular: "clause", plural: "clauses"}, + {singular: "cruse", plural: "cruses"}, + {singular: "excuse", plural: "excuses"}, + {singular: "fuse", plural: "fuses"}, + {singular: "house", plural: "houses"}, + {singular: "misuse", plural: "misuses"}, + {singular: "muse", plural: "muses"}, + {singular: "pause", plural: "pauses"}, + {singular: "ache", plural: "aches"}, + {singular: "topaz", plural: "topazes"}, + {singular: "buffalo", plural: "buffaloes", alternative: "buffalos"}, + {singular: "potato", plural: "potatoes"}, + {singular: "tomato", plural: "tomatoes"}, + + // uncountables + {singular: "equipment", uncountable: true}, + {singular: "information", uncountable: true}, + {singular: "jeans", uncountable: true}, + {singular: "money", uncountable: true}, + {singular: "news", uncountable: true}, + {singular: "rice", uncountable: true}, + + // exceptions: -f to -ves, not -fe + {singular: "dwarf", plural: "dwarfs", alternative: "dwarves"}, + {singular: "hoof", plural: "hoofs", alternative: "hooves"}, + {singular: "thief", plural: "thieves"}, + // exceptions: instead of -f(e) to -ves + {singular: "chive", plural: "chives"}, + {singular: "hive", plural: "hives"}, + {singular: "move", plural: "moves"}, + + // exceptions: instead of -y to -ies + {singular: "movie", plural: "movies"}, + {singular: "cookie", plural: "cookies"}, + + // exceptions: instead of -um to -a + {singular: "pretorium", plural: "pretoriums"}, + {singular: "agenda", plural: "agendas"}, // instead of plural of agendum + // exceptions: instead of -um to -a (chemical element names) + + // Words from Latin that end in -a change -a to -ae + {singular: "formula", plural: "formulas", alternative: "formulae"}, // also -um/-a + + // exceptions: instead of -o to -oes + {singular: "shoe", plural: "shoes"}, + {singular: "toe", plural: "toes", exact: true}, + {singular: "graffiti", plural: "graffiti"}, + + // abbreviations + {singular: "ID", plural: "IDs", exact: true}, +} + +// singleToPlural is the highest priority map for Pluralize(). +// singularToPluralSuffixList is used to build pluralRules for suffixes and +// compound words. +var singleToPlural = map[string]string{} + +// pluralToSingle is the highest priority map for Singularize(). +// singularToPluralSuffixList is used to build singularRules for suffixes and +// compound words. +var pluralToSingle = map[string]string{} + +// NOTE: This map should not be built as reverse map of singleToPlural since +// there are words that has the same plurals. + +// build singleToPlural and pluralToSingle with dictionary +func init() { + for _, wd := range dictionary { + if singleToPlural[wd.singular] != "" { + panic(fmt.Errorf("map singleToPlural already has an entry for %s", wd.singular)) + } + + if wd.uncountable && wd.plural == "" { + wd.plural = wd.singular + } + + if wd.plural == "" { + panic(fmt.Errorf("plural for %s is not provided", wd.singular)) + } + + singleToPlural[wd.singular] = wd.plural + + if !wd.unidirectional { + if pluralToSingle[wd.plural] != "" { + panic(fmt.Errorf("map pluralToSingle already has an entry for %s", wd.plural)) + } + pluralToSingle[wd.plural] = wd.singular + + if wd.alternative != "" { + if pluralToSingle[wd.alternative] != "" { + panic(fmt.Errorf("map pluralToSingle already has an entry for %s", wd.alternative)) + } + pluralToSingle[wd.alternative] = wd.singular + } + } + } +} + +type singularToPluralSuffix struct { + singular string + plural string +} + +// singularToPluralSuffixList is a list of "bidirectional" suffix rules for +// the irregular plurals follow such rules. +// +// NOTE: IMPORTANT! The order of items in this list is the rule priority, not +// alphabet order. The first match will be used to inflect. +var singularToPluralSuffixList = []singularToPluralSuffix{ + // https://en.wiktionary.org/wiki/Appendix:English_irregular_nouns#Rules + // Words that end in -f or -fe change -f or -fe to -ves + {"tive", "tives"}, // exception + {"eaf", "eaves"}, + {"oaf", "oaves"}, + {"afe", "aves"}, + {"arf", "arves"}, + {"rfe", "rves"}, + {"rf", "rves"}, + {"lf", "lves"}, + {"fe", "ves"}, // previously '[a-eg-km-z]fe' TODO: regex support + + // Words that end in -y preceded by a consonant change -y to -ies + {"ay", "ays"}, + {"ey", "eys"}, + {"oy", "oys"}, + {"quy", "quies"}, + {"uy", "uys"}, + {"y", "ies"}, // '[^aeiou]y' + + // Words from French that end in -u add an x (eg, château becomes châteaux) + {"eau", "eaux"}, // it seems like 'eau' is the most popular form of this rule + + // Words from Latin that end in -a change -a to -ae; before -on to -a and -um to -a + {"bula", "bulae"}, + {"dula", "bulae"}, + {"lula", "bulae"}, + {"nula", "bulae"}, + {"vula", "bulae"}, + + // Words from Greek that end in -on change -on to -a (eg, polyhedron becomes polyhedra) + // https://en.wiktionary.org/wiki/Category:English_irregular_plurals_ending_in_"-a" + {"hedron", "hedra"}, + + // Words from Latin that end in -um change -um to -a (eg, minimum becomes minima) + // https://en.wiktionary.org/wiki/Category:English_irregular_plurals_ending_in_"-a" + {"ium", "ia"}, // some exceptions especially chemical element names + {"seum", "seums"}, + {"eum", "ea"}, + {"oum", "oa"}, + {"stracum", "straca"}, + {"dum", "da"}, + {"elum", "ela"}, + {"ilum", "ila"}, + {"olum", "ola"}, + {"ulum", "ula"}, + {"llum", "lla"}, + {"ylum", "yla"}, + {"imum", "ima"}, + {"ernum", "erna"}, + {"gnum", "gna"}, + {"brum", "bra"}, + {"crum", "cra"}, + {"terum", "tera"}, + {"serum", "sera"}, + {"trum", "tra"}, + {"antum", "anta"}, + {"atum", "ata"}, + {"entum", "enta"}, + {"etum", "eta"}, + {"itum", "ita"}, + {"otum", "ota"}, + {"utum", "uta"}, + {"ctum", "cta"}, + {"ovum", "ova"}, + + // Words from Latin that end in -us change -us to -i or -era + // not easy to make a simple rule. just add them all to the dictionary + + // Words from Latin that end in -ex change -ex to -ices (eg, vortex becomes vortices) + // Words from Latin that end in -ix change -ix to -ices (eg, matrix becomes matrices) + // for example, -dix, -dex, and -dice will have the same plural form so + // making a simple rule is not possible for them + {"trix", "trices"}, // ignore a few words end in trice + + // Words from Latin that end in -is change -is to -es (eg, thesis becomes theses) + // -sis and -se has the same plural -ses so making a rule is not easy too. + {"iasis", "iases"}, + {"mesis", "meses"}, + {"kinesis", "kineses"}, + {"resis", "reses"}, + {"gnosis", "gnoses"}, // e.g. diagnosis + {"opsis", "opses"}, // e.g. synopsis + {"ysis", "yses"}, // e.g. analysis + + // Words that end in -ch, -o, -s, -sh, -x, -z + {"ouse", "ouses"}, + {"lause", "lauses"}, + {"us", "uses"}, // use/uses is in the dictionary + + {"ch", "ches"}, + {"io", "ios"}, + {"sh", "shes"}, + {"ss", "sses"}, + {"ez", "ezzes"}, + {"iz", "izzes"}, + {"tz", "tzes"}, + {"zz", "zzes"}, + {"ano", "anos"}, + {"lo", "los"}, + {"to", "tos"}, + {"oo", "oos"}, + {"o", "oes"}, + {"x", "xes"}, + + // for abbreviations + {"S", "Ses"}, + + // excluded rules: seems rare + // Words from Hebrew that add -im or -ot (eg, cherub becomes cherubim) + // - cherub (cherubs or cherubim), seraph (seraphs or seraphim) + // Words from Greek that end in -ma change -ma to -mata + // - The most of words end in -ma are in this category but it looks like + // just adding -s is more popular. + // Words from Latin that end in -nx change -nx to -nges + // - The most of words end in -nx are in this category but it looks like + // just adding -es is more popular. (sphinxes) + + // excluded rules: don't care at least for now: + // Words that end in -ful that add an s after the -ful + // Words that end in -s or -ese denoting a national of a particular country + // Symbols or letters, which often add -'s +} + +func init() { + for i := len(singularToPluralSuffixList) - 1; i >= 0; i-- { + InsertPluralRule(singularToPluralSuffixList[i].singular, singularToPluralSuffixList[i].plural) + InsertSingularRule(singularToPluralSuffixList[i].plural, singularToPluralSuffixList[i].singular) + } + + // build pluralRule and singularRule with dictionary for compound words + for _, wd := range dictionary { + if wd.exact { + continue + } + + if wd.uncountable && wd.plural == "" { + wd.plural = wd.singular + } + + InsertPluralRule(wd.singular, wd.plural) + + if !wd.unidirectional { + InsertSingularRule(wd.plural, wd.singular) + + if wd.alternative != "" { + InsertSingularRule(wd.alternative, wd.singular) + } + } + } +} diff --git a/vendor/github.com/gobuffalo/flect/pluralize.go b/vendor/github.com/gobuffalo/flect/pluralize.go new file mode 100644 index 000000000..d0ac77d3f --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/pluralize.go @@ -0,0 +1,72 @@ +package flect + +import ( + "strings" + "sync" +) + +var pluralMoot = &sync.RWMutex{} + +// Pluralize returns a plural version of the string +// user = users +// person = people +// datum = data +func Pluralize(s string) string { + return New(s).Pluralize().String() +} + +// PluralizeWithSize will pluralize a string taking a number number into account. +// PluralizeWithSize("user", 1) = user +// PluralizeWithSize("user", 2) = users +func PluralizeWithSize(s string, i int) string { + if i == 1 || i == -1 { + return New(s).Singularize().String() + } + return New(s).Pluralize().String() +} + +// Pluralize returns a plural version of the string +// user = users +// person = people +// datum = data +func (i Ident) Pluralize() Ident { + s := i.LastPart() + if len(s) == 0 { + return New("") + } + + pluralMoot.RLock() + defer pluralMoot.RUnlock() + + // check if the Original has an explicit entry in the map + if p, ok := singleToPlural[i.Original]; ok { + return i.ReplaceSuffix(i.Original, p) + } + if _, ok := pluralToSingle[i.Original]; ok { + return i + } + + ls := strings.ToLower(s) + if _, ok := pluralToSingle[ls]; ok { + return i + } + + if p, ok := singleToPlural[ls]; ok { + if s == Capitalize(s) { + p = Capitalize(p) + } + return i.ReplaceSuffix(s, p) + } + + for _, r := range pluralRules { + if strings.HasSuffix(s, r.suffix) { + return i.ReplaceSuffix(s, r.fn(s)) + } + } + + if strings.HasSuffix(ls, "s") { + return i + } + + return New(i.String() + "s") +} diff --git a/vendor/github.com/gobuffalo/flect/rule.go b/vendor/github.com/gobuffalo/flect/rule.go new file mode 100644 index 000000000..5428e6ed0 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/rule.go @@ -0,0 +1,17 @@ +package flect + +type ruleFn func(string) string + +type rule struct { + suffix string + fn ruleFn +} + +func simpleRuleFunc(suffix, repl string) func(string) string { + return func(s string) string { + s = s[:len(s)-len(suffix)] + return s + repl + } +} + +func noop(s string) string { return s } diff --git a/vendor/github.com/gobuffalo/flect/singular_rules.go b/vendor/github.com/gobuffalo/flect/singular_rules.go new file mode 100644 index 000000000..d59307b73 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/singular_rules.go @@ -0,0 +1,26 @@ +package flect + +var singularRules = []rule{} + +// AddSingular adds a rule that will replace the given suffix with the replacement suffix. +// The name is confusing. This function will be deprecated in the next release. +func AddSingular(ext string, repl string) { + InsertSingularRule(ext, repl) +} + +// InsertSingularRule inserts a rule that will replace the given suffix with +// the repl(acement) at the beginning of the list of the singularize rules. +func InsertSingularRule(suffix, repl string) { + singularMoot.Lock() + defer singularMoot.Unlock() + + singularRules = append([]rule{{ + suffix: suffix, + fn: simpleRuleFunc(suffix, repl), + }}, singularRules...) + + singularRules = append([]rule{{ + suffix: repl, + fn: noop, + }}, singularRules...) +} diff --git a/vendor/github.com/gobuffalo/flect/singularize.go b/vendor/github.com/gobuffalo/flect/singularize.go new file mode 100644 index 000000000..d00cf4f1e --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/singularize.go @@ -0,0 +1,69 @@ +package flect + +import ( + "strings" + "sync" +) + +var singularMoot = &sync.RWMutex{} + +// Singularize returns a singular version of the string +// users = user +// data = datum +// people = person +func Singularize(s string) string { + return New(s).Singularize().String() +} + +// SingularizeWithSize will singular a string taking a number number into account. +// SingularizeWithSize("user", 1) = user +// SingularizeWithSize("user", 2) = users +func SingularizeWithSize(s string, i int) string { + return PluralizeWithSize(s, i) +} + +// Singularize returns a singular version of the string +// users = user +// data = datum +// people = person +func (i Ident) Singularize() Ident { + s := i.LastPart() + if len(s) == 0 { + return i + } + + singularMoot.RLock() + defer singularMoot.RUnlock() + + // check if the Original has an explicit entry in the map + if p, ok := pluralToSingle[i.Original]; ok { + return i.ReplaceSuffix(i.Original, p) + } + if _, ok := singleToPlural[i.Original]; ok { + return i + } + + ls := strings.ToLower(s) + if p, ok := pluralToSingle[ls]; ok { + if s == Capitalize(s) { + p = Capitalize(p) + } + return i.ReplaceSuffix(s, p) + } + + if _, ok := singleToPlural[ls]; ok { + return i + } + + for _, r := range singularRules { + if strings.HasSuffix(s, r.suffix) { + return i.ReplaceSuffix(s, r.fn(s)) + } + } + + if strings.HasSuffix(s, "s") { + return i.ReplaceSuffix("s", "") + } + + return i +} diff --git a/vendor/github.com/gobuffalo/flect/titleize.go b/vendor/github.com/gobuffalo/flect/titleize.go new file mode 100644 index 000000000..0878ada8d --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/titleize.go @@ -0,0 +1,38 @@ +package flect + +import ( + "strings" + "unicode" +) + +// Titleize will capitalize the start of each part +// "Nice to see you!" = "Nice To See You!" +// "i've read a book! have you?" = "I've Read A Book! Have You?" +// "This is `code` ok" = "This Is `code` OK" +func Titleize(s string) string { + return New(s).Titleize().String() +} + +// Titleize will capitalize the start of each part +// "Nice to see you!" = "Nice To See You!" +// "i've read a book! have you?" = "I've Read A Book! Have You?" +// "This is `code` ok" = "This Is `code` OK" +func (i Ident) Titleize() Ident { + var parts []string + + // TODO: we need to reconsider the design. + // this approach preserves inline code block as is but it also + // preserves the other words start with a special character. + // I would prefer: "*wonderful* world" to be "*Wonderful* World" + for _, part := range i.Parts { + // CAUTION: in unicode, []rune(str)[0] is not rune(str[0]) + runes := []rune(part) + x := string(unicode.ToTitle(runes[0])) + if len(runes) > 1 { + x += string(runes[1:]) + } + parts = append(parts, x) + } + + return New(strings.Join(parts, " ")) +} diff --git a/vendor/github.com/gobuffalo/flect/underscore.go b/vendor/github.com/gobuffalo/flect/underscore.go new file mode 100644 index 000000000..d42859a59 --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/underscore.go @@ -0,0 +1,35 @@ +package flect + +import ( + "strings" + "unicode" +) + +// Underscore a string +// bob dylan --> bob_dylan +// Nice to see you! --> nice_to_see_you +// widgetID --> widget_id +func Underscore(s string) string { + return New(s).Underscore().String() +} + +// Underscore a string +// bob dylan --> bob_dylan +// Nice to see you! --> nice_to_see_you +// widgetID --> widget_id +func (i Ident) Underscore() Ident { + out := make([]string, 0, len(i.Parts)) + for _, part := range i.Parts { + var x strings.Builder + x.Grow(len(part)) + for _, c := range part { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + x.WriteRune(c) + } + } + if x.Len() > 0 { + out = append(out, x.String()) + } + } + return New(strings.ToLower(strings.Join(out, "_"))) +} diff --git a/vendor/github.com/gobuffalo/flect/version.go b/vendor/github.com/gobuffalo/flect/version.go new file mode 100644 index 000000000..79486ed2c --- /dev/null +++ b/vendor/github.com/gobuffalo/flect/version.go @@ -0,0 +1,4 @@ +package flect + +//Version holds Flect version number +const Version = "v1.0.0" diff --git a/vendor/github.com/google/gnostic-models/compiler/context.go b/vendor/github.com/google/gnostic-models/compiler/context.go index 1bfe96121..26b31e51e 100644 --- a/vendor/github.com/google/gnostic-models/compiler/context.go +++ b/vendor/github.com/google/gnostic-models/compiler/context.go @@ -15,7 +15,7 @@ package compiler import ( - yaml "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" ) // Context contains state of the compiler as it traverses a document. diff --git a/vendor/github.com/google/gnostic-models/compiler/extensions.go b/vendor/github.com/google/gnostic-models/compiler/extensions.go index 16ae66faa..efa07f2a9 100644 --- a/vendor/github.com/google/gnostic-models/compiler/extensions.go +++ b/vendor/github.com/google/gnostic-models/compiler/extensions.go @@ -20,9 +20,9 @@ import ( "os/exec" "strings" + yaml "go.yaml.in/yaml/v3" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" - yaml "gopkg.in/yaml.v3" extensions "github.com/google/gnostic-models/extensions" ) diff --git a/vendor/github.com/google/gnostic-models/compiler/helpers.go b/vendor/github.com/google/gnostic-models/compiler/helpers.go index 975d65e8f..a83261eb6 100644 --- a/vendor/github.com/google/gnostic-models/compiler/helpers.go +++ b/vendor/github.com/google/gnostic-models/compiler/helpers.go @@ -20,7 +20,7 @@ import ( "sort" "strconv" - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" "github.com/google/gnostic-models/jsonschema" ) diff --git a/vendor/github.com/google/gnostic-models/compiler/reader.go b/vendor/github.com/google/gnostic-models/compiler/reader.go index be0e8b40c..da409d6b3 100644 --- a/vendor/github.com/google/gnostic-models/compiler/reader.go +++ b/vendor/github.com/google/gnostic-models/compiler/reader.go @@ -24,7 +24,7 @@ import ( "strings" "sync" - yaml "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" ) var verboseReader = false diff --git a/vendor/github.com/google/gnostic-models/jsonschema/models.go b/vendor/github.com/google/gnostic-models/jsonschema/models.go index 4781bdc5f..a42b8e003 100644 --- a/vendor/github.com/google/gnostic-models/jsonschema/models.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/models.go @@ -16,7 +16,7 @@ // of JSON Schemas. package jsonschema -import "gopkg.in/yaml.v3" +import "go.yaml.in/yaml/v3" // The Schema struct models a JSON Schema and, because schemas are // defined hierarchically, contains many references to itself. diff --git a/vendor/github.com/google/gnostic-models/jsonschema/reader.go b/vendor/github.com/google/gnostic-models/jsonschema/reader.go index b8583d466..4f1fe0c08 100644 --- a/vendor/github.com/google/gnostic-models/jsonschema/reader.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/reader.go @@ -21,7 +21,7 @@ import ( "io/ioutil" "strconv" - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" ) // This is a global map of all known Schemas. diff --git a/vendor/github.com/google/gnostic-models/jsonschema/writer.go b/vendor/github.com/google/gnostic-models/jsonschema/writer.go index 340dc5f93..19f5ddeae 100644 --- a/vendor/github.com/google/gnostic-models/jsonschema/writer.go +++ b/vendor/github.com/google/gnostic-models/jsonschema/writer.go @@ -17,7 +17,7 @@ package jsonschema import ( "fmt" - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" ) const indentation = " " diff --git a/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go index d71fe6d54..de337d80c 100644 --- a/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go +++ b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.go @@ -21,7 +21,7 @@ import ( "regexp" "strings" - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" "github.com/google/gnostic-models/compiler" ) @@ -60,7 +60,7 @@ func NewAdditionalPropertiesItem(in *yaml.Node, context *compiler.Context) (*Add // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid AdditionalPropertiesItem") + message := "contains an invalid AdditionalPropertiesItem" err := compiler.NewError(context, message) errors = []error{err} } @@ -2543,7 +2543,7 @@ func NewNonBodyParameter(in *yaml.Node, context *compiler.Context) (*NonBodyPara // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid NonBodyParameter") + message := "contains an invalid NonBodyParameter" err := compiler.NewError(context, message) errors = []error{err} } @@ -3271,7 +3271,7 @@ func NewParameter(in *yaml.Node, context *compiler.Context) (*Parameter, error) // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid Parameter") + message := "contains an invalid Parameter" err := compiler.NewError(context, message) errors = []error{err} } @@ -3345,7 +3345,7 @@ func NewParametersItem(in *yaml.Node, context *compiler.Context) (*ParametersIte // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid ParametersItem") + message := "contains an invalid ParametersItem" err := compiler.NewError(context, message) errors = []error{err} } @@ -4561,7 +4561,7 @@ func NewResponseValue(in *yaml.Node, context *compiler.Context) (*ResponseValue, // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid ResponseValue") + message := "contains an invalid ResponseValue" err := compiler.NewError(context, message) errors = []error{err} } @@ -5030,7 +5030,7 @@ func NewSchemaItem(in *yaml.Node, context *compiler.Context) (*SchemaItem, error // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid SchemaItem") + message := "contains an invalid SchemaItem" err := compiler.NewError(context, message) errors = []error{err} } @@ -5160,7 +5160,7 @@ func NewSecurityDefinitionsItem(in *yaml.Node, context *compiler.Context) (*Secu // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid SecurityDefinitionsItem") + message := "contains an invalid SecurityDefinitionsItem" err := compiler.NewError(context, message) errors = []error{err} } @@ -6930,7 +6930,7 @@ func (m *BodyParameter) ToRawInfo() *yaml.Node { // always include this required field. info.Content = append(info.Content, compiler.NewScalarNodeForString("in")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.In)) - if m.Required != false { + if m.Required { info.Content = append(info.Content, compiler.NewScalarNodeForString("required")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Required)) } @@ -7149,7 +7149,7 @@ func (m *FileSchema) ToRawInfo() *yaml.Node { // always include this required field. info.Content = append(info.Content, compiler.NewScalarNodeForString("type")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.Type)) - if m.ReadOnly != false { + if m.ReadOnly { info.Content = append(info.Content, compiler.NewScalarNodeForString("readOnly")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ReadOnly)) } @@ -7176,7 +7176,7 @@ func (m *FormDataParameterSubSchema) ToRawInfo() *yaml.Node { if m == nil { return info } - if m.Required != false { + if m.Required { info.Content = append(info.Content, compiler.NewScalarNodeForString("required")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Required)) } @@ -7192,7 +7192,7 @@ func (m *FormDataParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("name")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.Name)) } - if m.AllowEmptyValue != false { + if m.AllowEmptyValue { info.Content = append(info.Content, compiler.NewScalarNodeForString("allowEmptyValue")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.AllowEmptyValue)) } @@ -7220,7 +7220,7 @@ func (m *FormDataParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -7228,7 +7228,7 @@ func (m *FormDataParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -7252,7 +7252,7 @@ func (m *FormDataParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -7306,7 +7306,7 @@ func (m *Header) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -7314,7 +7314,7 @@ func (m *Header) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -7338,7 +7338,7 @@ func (m *Header) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -7373,7 +7373,7 @@ func (m *HeaderParameterSubSchema) ToRawInfo() *yaml.Node { if m == nil { return info } - if m.Required != false { + if m.Required { info.Content = append(info.Content, compiler.NewScalarNodeForString("required")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Required)) } @@ -7413,7 +7413,7 @@ func (m *HeaderParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -7421,7 +7421,7 @@ func (m *HeaderParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -7445,7 +7445,7 @@ func (m *HeaderParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -7940,7 +7940,7 @@ func (m *Operation) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("schemes")) info.Content = append(info.Content, compiler.NewSequenceNodeForStringArray(m.Schemes)) } - if m.Deprecated != false { + if m.Deprecated { info.Content = append(info.Content, compiler.NewScalarNodeForString("deprecated")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Deprecated)) } @@ -8110,7 +8110,7 @@ func (m *PathParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -8118,7 +8118,7 @@ func (m *PathParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -8142,7 +8142,7 @@ func (m *PathParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -8218,7 +8218,7 @@ func (m *PrimitivesItems) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -8226,7 +8226,7 @@ func (m *PrimitivesItems) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -8250,7 +8250,7 @@ func (m *PrimitivesItems) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -8296,7 +8296,7 @@ func (m *QueryParameterSubSchema) ToRawInfo() *yaml.Node { if m == nil { return info } - if m.Required != false { + if m.Required { info.Content = append(info.Content, compiler.NewScalarNodeForString("required")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Required)) } @@ -8312,7 +8312,7 @@ func (m *QueryParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("name")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.Name)) } - if m.AllowEmptyValue != false { + if m.AllowEmptyValue { info.Content = append(info.Content, compiler.NewScalarNodeForString("allowEmptyValue")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.AllowEmptyValue)) } @@ -8340,7 +8340,7 @@ func (m *QueryParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -8348,7 +8348,7 @@ func (m *QueryParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -8372,7 +8372,7 @@ func (m *QueryParameterSubSchema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -8514,7 +8514,7 @@ func (m *Schema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("maximum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Maximum)) } - if m.ExclusiveMaximum != false { + if m.ExclusiveMaximum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMaximum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMaximum)) } @@ -8522,7 +8522,7 @@ func (m *Schema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minimum")) info.Content = append(info.Content, compiler.NewScalarNodeForFloat(m.Minimum)) } - if m.ExclusiveMinimum != false { + if m.ExclusiveMinimum { info.Content = append(info.Content, compiler.NewScalarNodeForString("exclusiveMinimum")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ExclusiveMinimum)) } @@ -8546,7 +8546,7 @@ func (m *Schema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("minItems")) info.Content = append(info.Content, compiler.NewScalarNodeForInt(m.MinItems)) } - if m.UniqueItems != false { + if m.UniqueItems { info.Content = append(info.Content, compiler.NewScalarNodeForString("uniqueItems")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.UniqueItems)) } @@ -8610,7 +8610,7 @@ func (m *Schema) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("discriminator")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.Discriminator)) } - if m.ReadOnly != false { + if m.ReadOnly { info.Content = append(info.Content, compiler.NewScalarNodeForString("readOnly")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.ReadOnly)) } @@ -8796,11 +8796,11 @@ func (m *Xml) ToRawInfo() *yaml.Node { info.Content = append(info.Content, compiler.NewScalarNodeForString("prefix")) info.Content = append(info.Content, compiler.NewScalarNodeForString(m.Prefix)) } - if m.Attribute != false { + if m.Attribute { info.Content = append(info.Content, compiler.NewScalarNodeForString("attribute")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Attribute)) } - if m.Wrapped != false { + if m.Wrapped { info.Content = append(info.Content, compiler.NewScalarNodeForString("wrapped")) info.Content = append(info.Content, compiler.NewScalarNodeForBool(m.Wrapped)) } diff --git a/vendor/github.com/google/gnostic-models/openapiv2/document.go b/vendor/github.com/google/gnostic-models/openapiv2/document.go index e96ac0d6d..89469a13e 100644 --- a/vendor/github.com/google/gnostic-models/openapiv2/document.go +++ b/vendor/github.com/google/gnostic-models/openapiv2/document.go @@ -15,7 +15,7 @@ package openapi_v2 import ( - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" "github.com/google/gnostic-models/compiler" ) diff --git a/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go index 4b1131ce1..662772dd9 100644 --- a/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go +++ b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go @@ -21,7 +21,7 @@ import ( "regexp" "strings" - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" "github.com/google/gnostic-models/compiler" ) @@ -60,7 +60,7 @@ func NewAdditionalPropertiesItem(in *yaml.Node, context *compiler.Context) (*Add // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid AdditionalPropertiesItem") + message := "contains an invalid AdditionalPropertiesItem" err := compiler.NewError(context, message) errors = []error{err} } @@ -113,7 +113,7 @@ func NewAnyOrExpression(in *yaml.Node, context *compiler.Context) (*AnyOrExpress // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid AnyOrExpression") + message := "contains an invalid AnyOrExpression" err := compiler.NewError(context, message) errors = []error{err} } @@ -227,7 +227,7 @@ func NewCallbackOrReference(in *yaml.Node, context *compiler.Context) (*Callback // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid CallbackOrReference") + message := "contains an invalid CallbackOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -979,7 +979,7 @@ func NewExampleOrReference(in *yaml.Node, context *compiler.Context) (*ExampleOr // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid ExampleOrReference") + message := "contains an invalid ExampleOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -1320,7 +1320,7 @@ func NewHeaderOrReference(in *yaml.Node, context *compiler.Context) (*HeaderOrRe // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid HeaderOrReference") + message := "contains an invalid HeaderOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -1713,7 +1713,7 @@ func NewLinkOrReference(in *yaml.Node, context *compiler.Context) (*LinkOrRefere // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid LinkOrReference") + message := "contains an invalid LinkOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -3090,7 +3090,7 @@ func NewParameterOrReference(in *yaml.Node, context *compiler.Context) (*Paramet // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid ParameterOrReference") + message := "contains an invalid ParameterOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -3606,7 +3606,7 @@ func NewRequestBodyOrReference(in *yaml.Node, context *compiler.Context) (*Reque // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid RequestBodyOrReference") + message := "contains an invalid RequestBodyOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -3743,7 +3743,7 @@ func NewResponseOrReference(in *yaml.Node, context *compiler.Context) (*Response // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid ResponseOrReference") + message := "contains an invalid ResponseOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -4310,7 +4310,7 @@ func NewSchemaOrReference(in *yaml.Node, context *compiler.Context) (*SchemaOrRe // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid SchemaOrReference") + message := "contains an invalid SchemaOrReference" err := compiler.NewError(context, message) errors = []error{err} } @@ -4543,7 +4543,7 @@ func NewSecuritySchemeOrReference(in *yaml.Node, context *compiler.Context) (*Se // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { - message := fmt.Sprintf("contains an invalid SecuritySchemeOrReference") + message := "contains an invalid SecuritySchemeOrReference" err := compiler.NewError(context, message) errors = []error{err} } diff --git a/vendor/github.com/google/gnostic-models/openapiv3/document.go b/vendor/github.com/google/gnostic-models/openapiv3/document.go index 1cee46773..499ff883c 100644 --- a/vendor/github.com/google/gnostic-models/openapiv3/document.go +++ b/vendor/github.com/google/gnostic-models/openapiv3/document.go @@ -15,7 +15,7 @@ package openapi_v3 import ( - "gopkg.in/yaml.v3" + yaml "go.yaml.in/yaml/v3" "github.com/google/gnostic-models/compiler" ) diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE new file mode 100644 index 000000000..5f920e973 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Alan Shreve (@inconshreveable) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md new file mode 100644 index 000000000..7a950d177 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/README.md @@ -0,0 +1,23 @@ +# mousetrap + +mousetrap is a tiny library that answers a single question. + +On a Windows machine, was the process invoked by someone double clicking on +the executable file while browsing in explorer? + +### Motivation + +Windows developers unfamiliar with command line tools will often "double-click" +the executable for a tool. Because most CLI tools print the help and then exit +when invoked without arguments, this is often very frustrating for those users. + +mousetrap provides a way to detect these invocations so that you can provide +more helpful behavior and instructions on how to run the CLI tool. To see what +this looks like, both from an organizational and a technical perspective, see +https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ + +### The interface + +The library exposes a single interface: + + func StartedByExplorer() (bool) diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go new file mode 100644 index 000000000..06a91f086 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/trap_others.go @@ -0,0 +1,16 @@ +//go:build !windows +// +build !windows + +package mousetrap + +// StartedByExplorer returns true if the program was invoked by the user +// double-clicking on the executable from explorer.exe +// +// It is conservative and returns false if any of the internal calls fail. +// It does not guarantee that the program was run from a terminal. It only can tell you +// whether it was launched from explorer.exe +// +// On non-Windows platforms, it always returns false. +func StartedByExplorer() bool { + return false +} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go new file mode 100644 index 000000000..0c5688021 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go @@ -0,0 +1,42 @@ +package mousetrap + +import ( + "syscall" + "unsafe" +) + +func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { + snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err + } + defer syscall.CloseHandle(snapshot) + var procEntry syscall.ProcessEntry32 + procEntry.Size = uint32(unsafe.Sizeof(procEntry)) + if err = syscall.Process32First(snapshot, &procEntry); err != nil { + return nil, err + } + for { + if procEntry.ProcessID == uint32(pid) { + return &procEntry, nil + } + err = syscall.Process32Next(snapshot, &procEntry) + if err != nil { + return nil, err + } + } +} + +// StartedByExplorer returns true if the program was invoked by the user double-clicking +// on the executable from explorer.exe +// +// It is conservative and returns false if any of the internal calls fail. +// It does not guarantee that the program was run from a terminal. It only can tell you +// whether it was launched from explorer.exe +func StartedByExplorer() bool { + pe, err := getProcessEntry(syscall.Getppid()) + if err != nil { + return false + } + return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) +} diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE new file mode 100644 index 000000000..91b5cef30 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Yasuhiro Matsumoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md new file mode 100644 index 000000000..ca0483711 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/README.md @@ -0,0 +1,48 @@ +# go-colorable + +[![Build Status](https://github.com/mattn/go-colorable/workflows/test/badge.svg)](https://github.com/mattn/go-colorable/actions?query=workflow%3Atest) +[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable) +[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) +[![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) + +Colorable writer for windows. + +For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) +This package is possible to handle escape sequence for ansi color on windows. + +## Too Bad! + +![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) + + +## So Good! + +![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) + +## Usage + +```go +logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) +logrus.SetOutput(colorable.NewColorableStdout()) + +logrus.Info("succeeded") +logrus.Warn("not correct") +logrus.Error("something error") +logrus.Fatal("panic") +``` + +You can compile above code on non-windows OSs. + +## Installation + +``` +$ go get github.com/mattn/go-colorable +``` + +# License + +MIT + +# Author + +Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go new file mode 100644 index 000000000..416d1bbbf --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -0,0 +1,38 @@ +//go:build appengine +// +build appengine + +package colorable + +import ( + "io" + "os" + + _ "github.com/mattn/go-isatty" +) + +// NewColorable returns new instance of Writer which handles escape sequence. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + return file +} + +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +func NewColorableStdout() io.Writer { + return os.Stdout +} + +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +func NewColorableStderr() io.Writer { + return os.Stderr +} + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go new file mode 100644 index 000000000..766d94603 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -0,0 +1,38 @@ +//go:build !windows && !appengine +// +build !windows,!appengine + +package colorable + +import ( + "io" + "os" + + _ "github.com/mattn/go-isatty" +) + +// NewColorable returns new instance of Writer which handles escape sequence. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + return file +} + +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +func NewColorableStdout() io.Writer { + return os.Stdout +} + +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +func NewColorableStderr() io.Writer { + return os.Stderr +} + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go new file mode 100644 index 000000000..1846ad5ab --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -0,0 +1,1047 @@ +//go:build windows && !appengine +// +build windows,!appengine + +package colorable + +import ( + "bytes" + "io" + "math" + "os" + "strconv" + "strings" + "sync" + "syscall" + "unsafe" + + "github.com/mattn/go-isatty" +) + +const ( + foregroundBlue = 0x1 + foregroundGreen = 0x2 + foregroundRed = 0x4 + foregroundIntensity = 0x8 + foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) + backgroundBlue = 0x10 + backgroundGreen = 0x20 + backgroundRed = 0x40 + backgroundIntensity = 0x80 + backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) + commonLvbUnderscore = 0x8000 + + cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 +) + +const ( + genericRead = 0x80000000 + genericWrite = 0x40000000 +) + +const ( + consoleTextmodeBuffer = 0x1 +) + +type wchar uint16 +type short int16 +type dword uint32 +type word uint16 + +type coord struct { + x short + y short +} + +type smallRect struct { + left short + top short + right short + bottom short +} + +type consoleScreenBufferInfo struct { + size coord + cursorPosition coord + attributes word + window smallRect + maximumWindowSize coord +} + +type consoleCursorInfo struct { + size dword + visible int32 +} + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") + procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") + procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") + procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") + procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") + procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") + procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") + procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") +) + +// Writer provides colorable Writer to the console +type Writer struct { + out io.Writer + handle syscall.Handle + althandle syscall.Handle + oldattr word + oldpos coord + rest bytes.Buffer + mutex sync.Mutex +} + +// NewColorable returns new instance of Writer which handles escape sequence from File. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + if isatty.IsTerminal(file.Fd()) { + var mode uint32 + if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 { + return file + } + var csbi consoleScreenBufferInfo + handle := syscall.Handle(file.Fd()) + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} + } + return file +} + +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +func NewColorableStdout() io.Writer { + return NewColorable(os.Stdout) +} + +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +func NewColorableStderr() io.Writer { + return NewColorable(os.Stderr) +} + +var color256 = map[int]int{ + 0: 0x000000, + 1: 0x800000, + 2: 0x008000, + 3: 0x808000, + 4: 0x000080, + 5: 0x800080, + 6: 0x008080, + 7: 0xc0c0c0, + 8: 0x808080, + 9: 0xff0000, + 10: 0x00ff00, + 11: 0xffff00, + 12: 0x0000ff, + 13: 0xff00ff, + 14: 0x00ffff, + 15: 0xffffff, + 16: 0x000000, + 17: 0x00005f, + 18: 0x000087, + 19: 0x0000af, + 20: 0x0000d7, + 21: 0x0000ff, + 22: 0x005f00, + 23: 0x005f5f, + 24: 0x005f87, + 25: 0x005faf, + 26: 0x005fd7, + 27: 0x005fff, + 28: 0x008700, + 29: 0x00875f, + 30: 0x008787, + 31: 0x0087af, + 32: 0x0087d7, + 33: 0x0087ff, + 34: 0x00af00, + 35: 0x00af5f, + 36: 0x00af87, + 37: 0x00afaf, + 38: 0x00afd7, + 39: 0x00afff, + 40: 0x00d700, + 41: 0x00d75f, + 42: 0x00d787, + 43: 0x00d7af, + 44: 0x00d7d7, + 45: 0x00d7ff, + 46: 0x00ff00, + 47: 0x00ff5f, + 48: 0x00ff87, + 49: 0x00ffaf, + 50: 0x00ffd7, + 51: 0x00ffff, + 52: 0x5f0000, + 53: 0x5f005f, + 54: 0x5f0087, + 55: 0x5f00af, + 56: 0x5f00d7, + 57: 0x5f00ff, + 58: 0x5f5f00, + 59: 0x5f5f5f, + 60: 0x5f5f87, + 61: 0x5f5faf, + 62: 0x5f5fd7, + 63: 0x5f5fff, + 64: 0x5f8700, + 65: 0x5f875f, + 66: 0x5f8787, + 67: 0x5f87af, + 68: 0x5f87d7, + 69: 0x5f87ff, + 70: 0x5faf00, + 71: 0x5faf5f, + 72: 0x5faf87, + 73: 0x5fafaf, + 74: 0x5fafd7, + 75: 0x5fafff, + 76: 0x5fd700, + 77: 0x5fd75f, + 78: 0x5fd787, + 79: 0x5fd7af, + 80: 0x5fd7d7, + 81: 0x5fd7ff, + 82: 0x5fff00, + 83: 0x5fff5f, + 84: 0x5fff87, + 85: 0x5fffaf, + 86: 0x5fffd7, + 87: 0x5fffff, + 88: 0x870000, + 89: 0x87005f, + 90: 0x870087, + 91: 0x8700af, + 92: 0x8700d7, + 93: 0x8700ff, + 94: 0x875f00, + 95: 0x875f5f, + 96: 0x875f87, + 97: 0x875faf, + 98: 0x875fd7, + 99: 0x875fff, + 100: 0x878700, + 101: 0x87875f, + 102: 0x878787, + 103: 0x8787af, + 104: 0x8787d7, + 105: 0x8787ff, + 106: 0x87af00, + 107: 0x87af5f, + 108: 0x87af87, + 109: 0x87afaf, + 110: 0x87afd7, + 111: 0x87afff, + 112: 0x87d700, + 113: 0x87d75f, + 114: 0x87d787, + 115: 0x87d7af, + 116: 0x87d7d7, + 117: 0x87d7ff, + 118: 0x87ff00, + 119: 0x87ff5f, + 120: 0x87ff87, + 121: 0x87ffaf, + 122: 0x87ffd7, + 123: 0x87ffff, + 124: 0xaf0000, + 125: 0xaf005f, + 126: 0xaf0087, + 127: 0xaf00af, + 128: 0xaf00d7, + 129: 0xaf00ff, + 130: 0xaf5f00, + 131: 0xaf5f5f, + 132: 0xaf5f87, + 133: 0xaf5faf, + 134: 0xaf5fd7, + 135: 0xaf5fff, + 136: 0xaf8700, + 137: 0xaf875f, + 138: 0xaf8787, + 139: 0xaf87af, + 140: 0xaf87d7, + 141: 0xaf87ff, + 142: 0xafaf00, + 143: 0xafaf5f, + 144: 0xafaf87, + 145: 0xafafaf, + 146: 0xafafd7, + 147: 0xafafff, + 148: 0xafd700, + 149: 0xafd75f, + 150: 0xafd787, + 151: 0xafd7af, + 152: 0xafd7d7, + 153: 0xafd7ff, + 154: 0xafff00, + 155: 0xafff5f, + 156: 0xafff87, + 157: 0xafffaf, + 158: 0xafffd7, + 159: 0xafffff, + 160: 0xd70000, + 161: 0xd7005f, + 162: 0xd70087, + 163: 0xd700af, + 164: 0xd700d7, + 165: 0xd700ff, + 166: 0xd75f00, + 167: 0xd75f5f, + 168: 0xd75f87, + 169: 0xd75faf, + 170: 0xd75fd7, + 171: 0xd75fff, + 172: 0xd78700, + 173: 0xd7875f, + 174: 0xd78787, + 175: 0xd787af, + 176: 0xd787d7, + 177: 0xd787ff, + 178: 0xd7af00, + 179: 0xd7af5f, + 180: 0xd7af87, + 181: 0xd7afaf, + 182: 0xd7afd7, + 183: 0xd7afff, + 184: 0xd7d700, + 185: 0xd7d75f, + 186: 0xd7d787, + 187: 0xd7d7af, + 188: 0xd7d7d7, + 189: 0xd7d7ff, + 190: 0xd7ff00, + 191: 0xd7ff5f, + 192: 0xd7ff87, + 193: 0xd7ffaf, + 194: 0xd7ffd7, + 195: 0xd7ffff, + 196: 0xff0000, + 197: 0xff005f, + 198: 0xff0087, + 199: 0xff00af, + 200: 0xff00d7, + 201: 0xff00ff, + 202: 0xff5f00, + 203: 0xff5f5f, + 204: 0xff5f87, + 205: 0xff5faf, + 206: 0xff5fd7, + 207: 0xff5fff, + 208: 0xff8700, + 209: 0xff875f, + 210: 0xff8787, + 211: 0xff87af, + 212: 0xff87d7, + 213: 0xff87ff, + 214: 0xffaf00, + 215: 0xffaf5f, + 216: 0xffaf87, + 217: 0xffafaf, + 218: 0xffafd7, + 219: 0xffafff, + 220: 0xffd700, + 221: 0xffd75f, + 222: 0xffd787, + 223: 0xffd7af, + 224: 0xffd7d7, + 225: 0xffd7ff, + 226: 0xffff00, + 227: 0xffff5f, + 228: 0xffff87, + 229: 0xffffaf, + 230: 0xffffd7, + 231: 0xffffff, + 232: 0x080808, + 233: 0x121212, + 234: 0x1c1c1c, + 235: 0x262626, + 236: 0x303030, + 237: 0x3a3a3a, + 238: 0x444444, + 239: 0x4e4e4e, + 240: 0x585858, + 241: 0x626262, + 242: 0x6c6c6c, + 243: 0x767676, + 244: 0x808080, + 245: 0x8a8a8a, + 246: 0x949494, + 247: 0x9e9e9e, + 248: 0xa8a8a8, + 249: 0xb2b2b2, + 250: 0xbcbcbc, + 251: 0xc6c6c6, + 252: 0xd0d0d0, + 253: 0xdadada, + 254: 0xe4e4e4, + 255: 0xeeeeee, +} + +// `\033]0;TITLESTR\007` +func doTitleSequence(er *bytes.Reader) error { + var c byte + var err error + + c, err = er.ReadByte() + if err != nil { + return err + } + if c != '0' && c != '2' { + return nil + } + c, err = er.ReadByte() + if err != nil { + return err + } + if c != ';' { + return nil + } + title := make([]byte, 0, 80) + for { + c, err = er.ReadByte() + if err != nil { + return err + } + if c == 0x07 || c == '\n' { + break + } + title = append(title, c) + } + if len(title) > 0 { + title8, err := syscall.UTF16PtrFromString(string(title)) + if err == nil { + procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) + } + } + return nil +} + +// returns Atoi(s) unless s == "" in which case it returns def +func atoiWithDefault(s string, def int) (int, error) { + if s == "" { + return def, nil + } + return strconv.Atoi(s) +} + +// Write writes data on console +func (w *Writer) Write(data []byte) (n int, err error) { + w.mutex.Lock() + defer w.mutex.Unlock() + var csbi consoleScreenBufferInfo + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) + + handle := w.handle + + var er *bytes.Reader + if w.rest.Len() > 0 { + var rest bytes.Buffer + w.rest.WriteTo(&rest) + w.rest.Reset() + rest.Write(data) + er = bytes.NewReader(rest.Bytes()) + } else { + er = bytes.NewReader(data) + } + var plaintext bytes.Buffer +loop: + for { + c1, err := er.ReadByte() + if err != nil { + plaintext.WriteTo(w.out) + break loop + } + if c1 != 0x1b { + plaintext.WriteByte(c1) + continue + } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } + c2, err := er.ReadByte() + if err != nil { + break loop + } + + switch c2 { + case '>': + continue + case ']': + w.rest.WriteByte(c1) + w.rest.WriteByte(c2) + er.WriteTo(&w.rest) + if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { + break loop + } + er = bytes.NewReader(w.rest.Bytes()[2:]) + err := doTitleSequence(er) + if err != nil { + break loop + } + w.rest.Reset() + continue + // https://github.com/mattn/go-colorable/issues/27 + case '7': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + w.oldpos = csbi.cursorPosition + continue + case '8': + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + continue + case 0x5b: + // execute part after switch + default: + continue + } + + w.rest.WriteByte(c1) + w.rest.WriteByte(c2) + er.WriteTo(&w.rest) + + var buf bytes.Buffer + var m byte + for i, c := range w.rest.Bytes()[2:] { + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + m = c + er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) + w.rest.Reset() + break + } + buf.Write([]byte(string(c))) + } + if m == 0 { + break loop + } + + switch m { + case 'A': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'B': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'C': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'D': + n, err = atoiWithDefault(buf.String(), 1) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x -= short(n) + if csbi.cursorPosition.x < 0 { + csbi.cursorPosition.x = 0 + } + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'E': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y += short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'F': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = 0 + csbi.cursorPosition.y -= short(n) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'G': + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + if n < 1 { + n = 1 + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + csbi.cursorPosition.x = short(n - 1) + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'H', 'f': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + if buf.Len() > 0 { + token := strings.Split(buf.String(), ";") + switch len(token) { + case 1: + n1, err := strconv.Atoi(token[0]) + if err != nil { + continue + } + csbi.cursorPosition.y = short(n1 - 1) + case 2: + n1, err := strconv.Atoi(token[0]) + if err != nil { + continue + } + n2, err := strconv.Atoi(token[1]) + if err != nil { + continue + } + csbi.cursorPosition.x = short(n2 - 1) + csbi.cursorPosition.y = short(n1 - 1) + } + } else { + csbi.cursorPosition.y = 0 + } + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + case 'J': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + var count, written dword + var cursor coord + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + case 1: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x) + case 2: + cursor = coord{x: csbi.window.left, y: csbi.window.top} + count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + } + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'K': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + var count, written dword + switch n { + case 0: + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x) + case 1: + cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x) + case 2: + cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + count = dword(csbi.size.x) + } + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'X': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + var written dword + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'm': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + attr := csbi.attributes + cs := buf.String() + if cs == "" { + procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) + continue + } + token := strings.Split(cs, ";") + for i := 0; i < len(token); i++ { + ns := token[i] + if n, err = strconv.Atoi(ns); err == nil { + switch { + case n == 0 || n == 100: + attr = w.oldattr + case n == 4: + attr |= commonLvbUnderscore + case (1 <= n && n <= 3) || n == 5: + attr |= foregroundIntensity + case n == 7 || n == 27: + attr = + (attr &^ (foregroundMask | backgroundMask)) | + ((attr & foregroundMask) << 4) | + ((attr & backgroundMask) >> 4) + case n == 22: + attr &^= foregroundIntensity + case n == 24: + attr &^= commonLvbUnderscore + case 30 <= n && n <= 37: + attr &= backgroundMask + if (n-30)&1 != 0 { + attr |= foregroundRed + } + if (n-30)&2 != 0 { + attr |= foregroundGreen + } + if (n-30)&4 != 0 { + attr |= foregroundBlue + } + case n == 38: // set foreground color. + if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256foreAttr == nil { + n256setup() + } + attr &= backgroundMask + attr |= n256foreAttr[n256%len(n256foreAttr)] + i += 2 + } + } else if len(token) == 5 && token[i+1] == "2" { + var r, g, b int + r, _ = strconv.Atoi(token[i+2]) + g, _ = strconv.Atoi(token[i+3]) + b, _ = strconv.Atoi(token[i+4]) + i += 4 + if r > 127 { + attr |= foregroundRed + } + if g > 127 { + attr |= foregroundGreen + } + if b > 127 { + attr |= foregroundBlue + } + } else { + attr = attr & (w.oldattr & backgroundMask) + } + case n == 39: // reset foreground color. + attr &= backgroundMask + attr |= w.oldattr & foregroundMask + case 40 <= n && n <= 47: + attr &= foregroundMask + if (n-40)&1 != 0 { + attr |= backgroundRed + } + if (n-40)&2 != 0 { + attr |= backgroundGreen + } + if (n-40)&4 != 0 { + attr |= backgroundBlue + } + case n == 48: // set background color. + if i < len(token)-2 && token[i+1] == "5" { + if n256, err := strconv.Atoi(token[i+2]); err == nil { + if n256backAttr == nil { + n256setup() + } + attr &= foregroundMask + attr |= n256backAttr[n256%len(n256backAttr)] + i += 2 + } + } else if len(token) == 5 && token[i+1] == "2" { + var r, g, b int + r, _ = strconv.Atoi(token[i+2]) + g, _ = strconv.Atoi(token[i+3]) + b, _ = strconv.Atoi(token[i+4]) + i += 4 + if r > 127 { + attr |= backgroundRed + } + if g > 127 { + attr |= backgroundGreen + } + if b > 127 { + attr |= backgroundBlue + } + } else { + attr = attr & (w.oldattr & foregroundMask) + } + case n == 49: // reset foreground color. + attr &= foregroundMask + attr |= w.oldattr & backgroundMask + case 90 <= n && n <= 97: + attr = (attr & backgroundMask) + attr |= foregroundIntensity + if (n-90)&1 != 0 { + attr |= foregroundRed + } + if (n-90)&2 != 0 { + attr |= foregroundGreen + } + if (n-90)&4 != 0 { + attr |= foregroundBlue + } + case 100 <= n && n <= 107: + attr = (attr & foregroundMask) + attr |= backgroundIntensity + if (n-100)&1 != 0 { + attr |= backgroundRed + } + if (n-100)&2 != 0 { + attr |= backgroundGreen + } + if (n-100)&4 != 0 { + attr |= backgroundBlue + } + } + procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) + } + } + case 'h': + var ci consoleCursorInfo + cs := buf.String() + if cs == "5>" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 0 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?25" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 1 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?1049" { + if w.althandle == 0 { + h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) + w.althandle = syscall.Handle(h) + if w.althandle != 0 { + handle = w.althandle + } + } + } + case 'l': + var ci consoleCursorInfo + cs := buf.String() + if cs == "5>" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 1 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?25" { + procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + ci.visible = 0 + procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + } else if cs == "?1049" { + if w.althandle != 0 { + syscall.CloseHandle(w.althandle) + w.althandle = 0 + handle = w.handle + } + } + case 's': + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + w.oldpos = csbi.cursorPosition + case 'u': + procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + } + } + + return len(data), nil +} + +type consoleColor struct { + rgb int + red bool + green bool + blue bool + intensity bool +} + +func (c consoleColor) foregroundAttr() (attr word) { + if c.red { + attr |= foregroundRed + } + if c.green { + attr |= foregroundGreen + } + if c.blue { + attr |= foregroundBlue + } + if c.intensity { + attr |= foregroundIntensity + } + return +} + +func (c consoleColor) backgroundAttr() (attr word) { + if c.red { + attr |= backgroundRed + } + if c.green { + attr |= backgroundGreen + } + if c.blue { + attr |= backgroundBlue + } + if c.intensity { + attr |= backgroundIntensity + } + return +} + +var color16 = []consoleColor{ + {0x000000, false, false, false, false}, + {0x000080, false, false, true, false}, + {0x008000, false, true, false, false}, + {0x008080, false, true, true, false}, + {0x800000, true, false, false, false}, + {0x800080, true, false, true, false}, + {0x808000, true, true, false, false}, + {0xc0c0c0, true, true, true, false}, + {0x808080, false, false, false, true}, + {0x0000ff, false, false, true, true}, + {0x00ff00, false, true, false, true}, + {0x00ffff, false, true, true, true}, + {0xff0000, true, false, false, true}, + {0xff00ff, true, false, true, true}, + {0xffff00, true, true, false, true}, + {0xffffff, true, true, true, true}, +} + +type hsv struct { + h, s, v float32 +} + +func (a hsv) dist(b hsv) float32 { + dh := a.h - b.h + switch { + case dh > 0.5: + dh = 1 - dh + case dh < -0.5: + dh = -1 - dh + } + ds := a.s - b.s + dv := a.v - b.v + return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) +} + +func toHSV(rgb int) hsv { + r, g, b := float32((rgb&0xFF0000)>>16)/256.0, + float32((rgb&0x00FF00)>>8)/256.0, + float32(rgb&0x0000FF)/256.0 + min, max := minmax3f(r, g, b) + h := max - min + if h > 0 { + if max == r { + h = (g - b) / h + if h < 0 { + h += 6 + } + } else if max == g { + h = 2 + (b-r)/h + } else { + h = 4 + (r-g)/h + } + } + h /= 6.0 + s := max - min + if max != 0 { + s /= max + } + v := max + return hsv{h: h, s: s, v: v} +} + +type hsvTable []hsv + +func toHSVTable(rgbTable []consoleColor) hsvTable { + t := make(hsvTable, len(rgbTable)) + for i, c := range rgbTable { + t[i] = toHSV(c.rgb) + } + return t +} + +func (t hsvTable) find(rgb int) consoleColor { + hsv := toHSV(rgb) + n := 7 + l := float32(5.0) + for i, p := range t { + d := hsv.dist(p) + if d < l { + l, n = d, i + } + } + return color16[n] +} + +func minmax3f(a, b, c float32) (min, max float32) { + if a < b { + if b < c { + return a, c + } else if a < c { + return a, b + } else { + return c, b + } + } else { + if a < c { + return b, c + } else if b < c { + return b, a + } else { + return c, a + } + } +} + +var n256foreAttr []word +var n256backAttr []word + +func n256setup() { + n256foreAttr = make([]word, 256) + n256backAttr = make([]word, 256) + t := toHSVTable(color16) + for i, rgb := range color256 { + c := t.find(rgb) + n256foreAttr[i] = c.foregroundAttr() + n256backAttr[i] = c.backgroundAttr() + } +} + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + var mode uint32 + h := os.Stdout.Fd() + if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { + if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { + if enabled != nil { + *enabled = true + } + return func() { + procSetConsoleMode.Call(h, uintptr(mode)) + } + } + } + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/go.test.sh b/vendor/github.com/mattn/go-colorable/go.test.sh new file mode 100644 index 000000000..012162b07 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/go.test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go new file mode 100644 index 000000000..05d6f74bf --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -0,0 +1,57 @@ +package colorable + +import ( + "bytes" + "io" +) + +// NonColorable holds writer but removes escape sequence. +type NonColorable struct { + out io.Writer +} + +// NewNonColorable returns new instance of Writer which removes escape sequence from Writer. +func NewNonColorable(w io.Writer) io.Writer { + return &NonColorable{out: w} +} + +// Write writes data on console +func (w *NonColorable) Write(data []byte) (n int, err error) { + er := bytes.NewReader(data) + var plaintext bytes.Buffer +loop: + for { + c1, err := er.ReadByte() + if err != nil { + plaintext.WriteTo(w.out) + break loop + } + if c1 != 0x1b { + plaintext.WriteByte(c1) + continue + } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } + c2, err := er.ReadByte() + if err != nil { + break loop + } + if c2 != 0x5b { + continue + } + + for { + c, err := er.ReadByte() + if err != nil { + break loop + } + if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { + break + } + } + } + + return len(data), nil +} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE new file mode 100644 index 000000000..65dc692b6 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) Yasuhiro MATSUMOTO + +MIT License (Expat) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md new file mode 100644 index 000000000..38418353e --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/README.md @@ -0,0 +1,50 @@ +# go-isatty + +[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) +[![Codecov](https://codecov.io/gh/mattn/go-isatty/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-isatty) +[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) +[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) + +isatty for golang + +## Usage + +```go +package main + +import ( + "fmt" + "github.com/mattn/go-isatty" + "os" +) + +func main() { + if isatty.IsTerminal(os.Stdout.Fd()) { + fmt.Println("Is Terminal") + } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { + fmt.Println("Is Cygwin/MSYS2 Terminal") + } else { + fmt.Println("Is Not Terminal") + } +} +``` + +## Installation + +``` +$ go get github.com/mattn/go-isatty +``` + +## License + +MIT + +## Author + +Yasuhiro Matsumoto (a.k.a mattn) + +## Thanks + +* k-takata: base idea for IsCygwinTerminal + + https://github.com/k-takata/go-iscygpty diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go new file mode 100644 index 000000000..17d4f90eb --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/doc.go @@ -0,0 +1,2 @@ +// Package isatty implements interface to isatty +package isatty diff --git a/vendor/github.com/mattn/go-isatty/go.test.sh b/vendor/github.com/mattn/go-isatty/go.test.sh new file mode 100644 index 000000000..012162b07 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/go.test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go new file mode 100644 index 000000000..d0ea68f40 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -0,0 +1,20 @@ +//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine && !tinygo +// +build darwin freebsd openbsd netbsd dragonfly hurd +// +build !appengine +// +build !tinygo + +package isatty + +import "golang.org/x/sys/unix" + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA) + return err == nil +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go new file mode 100644 index 000000000..7402e0618 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_others.go @@ -0,0 +1,17 @@ +//go:build (appengine || js || nacl || tinygo || wasm) && !windows +// +build appengine js nacl tinygo wasm +// +build !windows + +package isatty + +// IsTerminal returns true if the file descriptor is terminal which +// is always false on js and appengine classic which is a sandboxed PaaS. +func IsTerminal(fd uintptr) bool { + return false +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_plan9.go b/vendor/github.com/mattn/go-isatty/isatty_plan9.go new file mode 100644 index 000000000..bae7f9bb3 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_plan9.go @@ -0,0 +1,23 @@ +//go:build plan9 +// +build plan9 + +package isatty + +import ( + "syscall" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal(fd uintptr) bool { + path, err := syscall.Fd2path(int(fd)) + if err != nil { + return false + } + return path == "/dev/cons" || path == "/mnt/term/dev/cons" +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go new file mode 100644 index 000000000..0c3acf2dc --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_solaris.go @@ -0,0 +1,21 @@ +//go:build solaris && !appengine +// +build solaris,!appengine + +package isatty + +import ( + "golang.org/x/sys/unix" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +// see: https://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libc/port/gen/isatty.c +func IsTerminal(fd uintptr) bool { + _, err := unix.IoctlGetTermio(int(fd), unix.TCGETA) + return err == nil +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go new file mode 100644 index 000000000..0337d8cf6 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go @@ -0,0 +1,20 @@ +//go:build (linux || aix || zos) && !appengine && !tinygo +// +build linux aix zos +// +build !appengine +// +build !tinygo + +package isatty + +import "golang.org/x/sys/unix" + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + _, err := unix.IoctlGetTermios(int(fd), unix.TCGETS) + return err == nil +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go new file mode 100644 index 000000000..8e3c99171 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_windows.go @@ -0,0 +1,125 @@ +//go:build windows && !appengine +// +build windows,!appengine + +package isatty + +import ( + "errors" + "strings" + "syscall" + "unicode/utf16" + "unsafe" +) + +const ( + objectNameInfo uintptr = 1 + fileNameInfo = 2 + fileTypePipe = 3 +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + ntdll = syscall.NewLazyDLL("ntdll.dll") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") + procGetFileType = kernel32.NewProc("GetFileType") + procNtQueryObject = ntdll.NewProc("NtQueryObject") +) + +func init() { + // Check if GetFileInformationByHandleEx is available. + if procGetFileInformationByHandleEx.Find() != nil { + procGetFileInformationByHandleEx = nil + } +} + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} + +// Check pipe name is used for cygwin/msys2 pty. +// Cygwin/MSYS2 PTY has a name like: +// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master +func isCygwinPipeName(name string) bool { + token := strings.Split(name, "-") + if len(token) < 5 { + return false + } + + if token[0] != `\msys` && + token[0] != `\cygwin` && + token[0] != `\Device\NamedPipe\msys` && + token[0] != `\Device\NamedPipe\cygwin` { + return false + } + + if token[1] == "" { + return false + } + + if !strings.HasPrefix(token[2], "pty") { + return false + } + + if token[3] != `from` && token[3] != `to` { + return false + } + + if token[4] != "master" { + return false + } + + return true +} + +// getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler +// since GetFileInformationByHandleEx is not available under windows Vista and still some old fashion +// guys are using Windows XP, this is a workaround for those guys, it will also work on system from +// Windows vista to 10 +// see https://stackoverflow.com/a/18792477 for details +func getFileNameByHandle(fd uintptr) (string, error) { + if procNtQueryObject == nil { + return "", errors.New("ntdll.dll: NtQueryObject not supported") + } + + var buf [4 + syscall.MAX_PATH]uint16 + var result int + r, _, e := syscall.Syscall6(procNtQueryObject.Addr(), 5, + fd, objectNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(2*len(buf)), uintptr(unsafe.Pointer(&result)), 0) + if r != 0 { + return "", e + } + return string(utf16.Decode(buf[4 : 4+buf[0]/2])), nil +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. +func IsCygwinTerminal(fd uintptr) bool { + if procGetFileInformationByHandleEx == nil { + name, err := getFileNameByHandle(fd) + if err != nil { + return false + } + return isCygwinPipeName(name) + } + + // Cygwin/msys's pty is a pipe. + ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) + if ft != fileTypePipe || e != 0 { + return false + } + + var buf [2 + syscall.MAX_PATH]uint16 + r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), + 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), + uintptr(len(buf)*2), 0, 0) + if r == 0 || e != 0 { + return false + } + + l := *(*uint32)(unsafe.Pointer(&buf)) + return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) +} diff --git a/vendor/github.com/onsi/ginkgo/v2/.gitignore b/vendor/github.com/onsi/ginkgo/v2/.gitignore index 18793c248..6faaaf315 100644 --- a/vendor/github.com/onsi/ginkgo/v2/.gitignore +++ b/vendor/github.com/onsi/ginkgo/v2/.gitignore @@ -4,4 +4,5 @@ tmp/**/* *.coverprofile .vscode .idea/ -*.log \ No newline at end of file +*.log +*.test \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md b/vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md index fd6e070c1..663feb1ee 100644 --- a/vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md +++ b/vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md @@ -1,3 +1,81 @@ +## 2.23.3 + +### Fixes + +- allow `-` as a standalone argument [cfcc1a5] +- Bug Fix: Add GinkoTBWrapper.Chdir() and GinkoTBWrapper.Context() [feaf292] +- ignore exit code for symbol test on linux [88e2282] + +## 2.23.2 + +🎉🎉🎉 + +At long last, some long-standing performance gaps between `ginkgo` and `go test` have been resolved! + +Ginkgo operates by running `go test -c` to generate test binaries, and then running those binaries. It turns out that the compilation step of `go test -c` is slower than `go test`'s compilation step because `go test` strips out debug symbols (`ldflags=-w`) whereas `go test -c` does not. + +Ginkgo now passes the appropriate `ldflags` to `go test -c` when running specs to strip out symbols. This is only done when it is safe to do so and symbols are preferred when profiling is enabled and when `ginkgo build` is called explicitly. + +This, coupled, with the [instructions for disabling XProtect on MacOS](https://onsi.github.io/ginkgo/#if-you-are-running-on-macos) yields a much better performance experience with Ginkgo. + +## 2.23.1 + +## 🚨 For users on MacOS 🚨 + +A long-standing Ginkgo performance issue on MacOS seems to be due to mac's antimalware XProtect. You can follow the instructions [here](https://onsi.github.io/ginkgo/#if-you-are-running-on-macos) to disable it in your terminal. Doing so sped up Ginkgo's own test suite from 1m8s to 47s. + +### Fixes + +Ginkgo's CLI is now a bit clearer if you pass flags in incorrectly: + +- make it clearer that you need to pass a filename to the various profile flags, not an absolute directory [a0e52ff] +- emit an error and exit if the ginkgo invocation includes flags after positional arguments [b799d8d] + +This might cause existing CI builds to fail. If so then it's likely that your CI build was misconfigured and should be corrected. Open an issue if you need help. + +## 2.23.0 + +Ginkgo 2.23.0 adds a handful of methods to `GinkgoT()` to make it compatible with the `testing.TB` interface in Go 1.24. `GinkgoT().Context()`, in particular, is a useful shorthand for generating a new context that will clean itself up in a `DeferCleanup()`. This has subtle behavior differences from the golang implementation but should make sense in a Ginkgo... um... context. + +### Features +- bump to go 1.24.0 - support new testing.TB methods and add a test to cover testing.TB regressions [37a511b] + +### Fixes +- fix edge case where build -o is pointing at an explicit file, not a directory [7556a86] +- Fix binary paths when precompiling multiple suites. [4df06c6] + +### Maintenance +- Fix: Correct Markdown list rendering in MIGRATING_TO_V2.md [cbcf39a] +- docs: fix test workflow badge (#1512) [9b261ff] +- Bump golang.org/x/net in /integration/_fixtures/version_mismatch_fixture (#1516) [00f19c8] +- Bump golang.org/x/tools from 0.28.0 to 0.30.0 (#1515) [e98a4df] +- Bump activesupport from 6.0.6.1 to 6.1.7.5 in /docs (#1504) [60cc4e2] +- Bump github-pages from 231 to 232 in /docs (#1447) [fea6f2d] +- Bump rexml from 3.2.8 to 3.3.9 in /docs (#1497) [31d7813] +- Bump webrick from 1.8.1 to 1.9.1 in /docs (#1501) [fc3bbd6] +- Code linting (#1500) [aee0d56] +- change interface{} to any (#1502) [809a710] + +## 2.22.2 + +### Maintenance +- Bump github.com/onsi/gomega from 1.36.1 to 1.36.2 (#1499) [cc553ce] +- Bump golang.org/x/crypto (#1498) [2170370] +- Bump golang.org/x/net from 0.32.0 to 0.33.0 (#1496) [a96c44f] + +## 2.22.1 + +### Fixes +Fix CSV encoding +- Update tests [aab3da6] +- Properly encode CSV rows [c09df39] +- Add test case for proper csv escaping [96a80fc] +- Add meta-test [43dad69] + +### Maintenance +- ensure *.test files are gitignored so we don't accidentally commit compiled tests again [c88c634] +- remove golang.org/x/net/context in favour of stdlib context [4df44bf] + ## 2.22.0 ### Features @@ -610,7 +688,7 @@ Ginkgo also uses this progress reporting infrastructure under the hood when hand ### Features - `BeforeSuite`, `AfterSuite`, `SynchronizedBeforeSuite`, `SynchronizedAfterSuite`, and `ReportAfterSuite` now support (the relevant subset of) decorators. These can be passed in _after_ the callback functions that are usually passed into these nodes. - As a result the **signature of these methods has changed** and now includes a trailing `args ...interface{}`. For most users simply using the DSL, this change is transparent. However if you were assigning one of these functions to a custom variable (or passing it around) then your code may need to change to reflect the new signature. + As a result the **signature of these methods has changed** and now includes a trailing `args ...any`. For most users simply using the DSL, this change is transparent. However if you were assigning one of these functions to a custom variable (or passing it around) then your code may need to change to reflect the new signature. ### Maintenance - Modernize the invocation of Ginkgo in github actions [0ffde58] @@ -1022,7 +1100,7 @@ New Features: - `ginkgo -tags=TAG_LIST` passes a list of tags down to the `go build` command. - `ginkgo --failFast` aborts the test suite after the first failure. - `ginkgo generate file_1 file_2` can take multiple file arguments. -- Ginkgo now summarizes any spec failures that occurred at the end of the test run. +- Ginkgo now summarizes any spec failures that occurred at the end of the test run. - `ginkgo --randomizeSuites` will run tests *suites* in random order using the generated/passed-in seed. Improvements: @@ -1056,7 +1134,7 @@ Bug Fixes: Breaking changes: - `thirdparty/gomocktestreporter` is gone. Use `GinkgoT()` instead -- Modified the Reporter interface +- Modified the Reporter interface - `watch` is now a subcommand, not a flag. DSL changes: diff --git a/vendor/github.com/onsi/ginkgo/v2/README.md b/vendor/github.com/onsi/ginkgo/v2/README.md index cb23ffdf6..e3d0c13cc 100644 --- a/vendor/github.com/onsi/ginkgo/v2/README.md +++ b/vendor/github.com/onsi/ginkgo/v2/README.md @@ -1,6 +1,6 @@ ![Ginkgo](https://onsi.github.io/ginkgo/images/ginkgo.png) -[![test](https://github.com/onsi/ginkgo/workflows/test/badge.svg?branch=master)](https://github.com/onsi/ginkgo/actions?query=workflow%3Atest+branch%3Amaster) | [Ginkgo Docs](https://onsi.github.io/ginkgo/) +[![test](https://github.com/onsi/ginkgo/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/onsi/ginkgo/actions?query=workflow%3Atest+branch%3Amaster) | [Ginkgo Docs](https://onsi.github.io/ginkgo/) --- diff --git a/vendor/github.com/onsi/ginkgo/v2/core_dsl.go b/vendor/github.com/onsi/ginkgo/v2/core_dsl.go index a3e8237e9..d027bdff9 100644 --- a/vendor/github.com/onsi/ginkgo/v2/core_dsl.go +++ b/vendor/github.com/onsi/ginkgo/v2/core_dsl.go @@ -83,9 +83,9 @@ func exitIfErrors(errors []error) { type GinkgoWriterInterface interface { io.Writer - Print(a ...interface{}) - Printf(format string, a ...interface{}) - Println(a ...interface{}) + Print(a ...any) + Printf(format string, a ...any) + Println(a ...any) TeeTo(writer io.Writer) ClearTeeWriters() @@ -243,7 +243,7 @@ for more on how specs are parallelized in Ginkgo. You can also pass suite-level Label() decorators to RunSpecs. The passed-in labels will apply to all specs in the suite. */ -func RunSpecs(t GinkgoTestingT, description string, args ...interface{}) bool { +func RunSpecs(t GinkgoTestingT, description string, args ...any) bool { if suiteDidRun { exitIfErr(types.GinkgoErrors.RerunningSuite()) } @@ -316,7 +316,7 @@ func RunSpecs(t GinkgoTestingT, description string, args ...interface{}) bool { return passed } -func extractSuiteConfiguration(args []interface{}) Labels { +func extractSuiteConfiguration(args []any) Labels { suiteLabels := Labels{} configErrors := []error{} for _, arg := range args { @@ -491,14 +491,14 @@ to Describe the behavior of an object or function and, within that Describe, out You can learn more at https://onsi.github.io/ginkgo/#organizing-specs-with-container-nodes In addition, container nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference */ -func Describe(text string, args ...interface{}) bool { +func Describe(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } /* FDescribe focuses specs within the Describe block. */ -func FDescribe(text string, args ...interface{}) bool { +func FDescribe(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } @@ -506,7 +506,7 @@ func FDescribe(text string, args ...interface{}) bool { /* PDescribe marks specs within the Describe block as pending. */ -func PDescribe(text string, args ...interface{}) bool { +func PDescribe(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } @@ -522,18 +522,18 @@ var XDescribe = PDescribe var Context, FContext, PContext, XContext = Describe, FDescribe, PDescribe, XDescribe /* When is an alias for Describe - it generates the exact same kind of Container node */ -func When(text string, args ...interface{}) bool { +func When(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } /* When is an alias for Describe - it generates the exact same kind of Container node */ -func FWhen(text string, args ...interface{}) bool { +func FWhen(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } /* When is an alias for Describe - it generates the exact same kind of Container node */ -func PWhen(text string, args ...interface{}) bool { +func PWhen(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } @@ -550,14 +550,14 @@ You can pass It nodes bare functions (func() {}) or functions that receive a Spe You can learn more at https://onsi.github.io/ginkgo/#spec-subjects-it In addition, subject nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference */ -func It(text string, args ...interface{}) bool { +func It(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } /* FIt allows you to focus an individual It. */ -func FIt(text string, args ...interface{}) bool { +func FIt(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } @@ -565,7 +565,7 @@ func FIt(text string, args ...interface{}) bool { /* PIt allows you to mark an individual It as pending. */ -func PIt(text string, args ...interface{}) bool { +func PIt(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } @@ -611,8 +611,8 @@ BeforeSuite can take a func() body, or an interruptible func(SpecContext)/func(c You cannot nest any other Ginkgo nodes within a BeforeSuite node's closure. You can learn more here: https://onsi.github.io/ginkgo/#suite-setup-and-cleanup-beforesuite-and-aftersuite */ -func BeforeSuite(body interface{}, args ...interface{}) bool { - combinedArgs := []interface{}{body} +func BeforeSuite(body any, args ...any) bool { + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeSuite, "", combinedArgs...)) } @@ -630,8 +630,8 @@ AfterSuite can take a func() body, or an interruptible func(SpecContext)/func(co You cannot nest any other Ginkgo nodes within an AfterSuite node's closure. You can learn more here: https://onsi.github.io/ginkgo/#suite-setup-and-cleanup-beforesuite-and-aftersuite */ -func AfterSuite(body interface{}, args ...interface{}) bool { - combinedArgs := []interface{}{body} +func AfterSuite(body any, args ...any) bool { + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeAfterSuite, "", combinedArgs...)) } @@ -667,8 +667,8 @@ If either function receives a context.Context/SpecContext it is considered inter You cannot nest any other Ginkgo nodes within an SynchronizedBeforeSuite node's closure. You can learn more, and see some examples, here: https://onsi.github.io/ginkgo/#parallel-suite-setup-and-cleanup-synchronizedbeforesuite-and-synchronizedaftersuite */ -func SynchronizedBeforeSuite(process1Body interface{}, allProcessBody interface{}, args ...interface{}) bool { - combinedArgs := []interface{}{process1Body, allProcessBody} +func SynchronizedBeforeSuite(process1Body any, allProcessBody any, args ...any) bool { + combinedArgs := []any{process1Body, allProcessBody} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeSynchronizedBeforeSuite, "", combinedArgs...)) @@ -687,8 +687,8 @@ Note that you can also use DeferCleanup() in SynchronizedBeforeSuite to accompli You cannot nest any other Ginkgo nodes within an SynchronizedAfterSuite node's closure. You can learn more, and see some examples, here: https://onsi.github.io/ginkgo/#parallel-suite-setup-and-cleanup-synchronizedbeforesuite-and-synchronizedaftersuite */ -func SynchronizedAfterSuite(allProcessBody interface{}, process1Body interface{}, args ...interface{}) bool { - combinedArgs := []interface{}{allProcessBody, process1Body} +func SynchronizedAfterSuite(allProcessBody any, process1Body any, args ...any) bool { + combinedArgs := []any{allProcessBody, process1Body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeSynchronizedAfterSuite, "", combinedArgs...)) @@ -703,7 +703,7 @@ BeforeEach can take a func() body, or an interruptible func(SpecContext)/func(co You cannot nest any other Ginkgo nodes within a BeforeEach node's closure. You can learn more here: https://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach */ -func BeforeEach(args ...interface{}) bool { +func BeforeEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeEach, "", args...)) } @@ -716,7 +716,7 @@ JustBeforeEach can take a func() body, or an interruptible func(SpecContext)/fun You cannot nest any other Ginkgo nodes within a JustBeforeEach node's closure. You can learn more and see some examples here: https://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach */ -func JustBeforeEach(args ...interface{}) bool { +func JustBeforeEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeJustBeforeEach, "", args...)) } @@ -731,7 +731,7 @@ AfterEach can take a func() body, or an interruptible func(SpecContext)/func(con You cannot nest any other Ginkgo nodes within an AfterEach node's closure. You can learn more here: https://onsi.github.io/ginkgo/#spec-cleanup-aftereach-and-defercleanup */ -func AfterEach(args ...interface{}) bool { +func AfterEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeAfterEach, "", args...)) } @@ -743,7 +743,7 @@ JustAfterEach can take a func() body, or an interruptible func(SpecContext)/func You cannot nest any other Ginkgo nodes within a JustAfterEach node's closure. You can learn more and see some examples here: https://onsi.github.io/ginkgo/#separating-diagnostics-collection-and-teardown-justaftereach */ -func JustAfterEach(args ...interface{}) bool { +func JustAfterEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeJustAfterEach, "", args...)) } @@ -758,7 +758,7 @@ You cannot nest any other Ginkgo nodes within a BeforeAll node's closure. You can learn more about Ordered Containers at: https://onsi.github.io/ginkgo/#ordered-containers And you can learn more about BeforeAll at: https://onsi.github.io/ginkgo/#setup-in-ordered-containers-beforeall-and-afterall */ -func BeforeAll(args ...interface{}) bool { +func BeforeAll(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeAll, "", args...)) } @@ -775,7 +775,7 @@ You cannot nest any other Ginkgo nodes within an AfterAll node's closure. You can learn more about Ordered Containers at: https://onsi.github.io/ginkgo/#ordered-containers And you can learn more about AfterAll at: https://onsi.github.io/ginkgo/#setup-in-ordered-containers-beforeall-and-afterall */ -func AfterAll(args ...interface{}) bool { +func AfterAll(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeAfterAll, "", args...)) } @@ -818,7 +818,7 @@ When DeferCleanup is called in BeforeSuite, SynchronizedBeforeSuite, AfterSuite, Note that DeferCleanup does not represent a node but rather dynamically generates the appropriate type of cleanup node based on the context in which it is called. As such you must call DeferCleanup within a Setup or Subject node, and not within a Container node. You can learn more about DeferCleanup here: https://onsi.github.io/ginkgo/#cleaning-up-our-cleanup-code-defercleanup */ -func DeferCleanup(args ...interface{}) { +func DeferCleanup(args ...any) { fail := func(message string, cl types.CodeLocation) { global.Failer.Fail(message, cl) } diff --git a/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go b/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go index f912bbec6..fd45b8bea 100644 --- a/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go +++ b/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go @@ -118,9 +118,9 @@ Use Gomega's gmeasure package instead. You can learn more here: https://onsi.github.io/ginkgo/#benchmarking-code */ type Benchmarker interface { - Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) - RecordValue(name string, value float64, info ...interface{}) - RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) + Time(name string, body func(), info ...any) (elapsedTime time.Duration) + RecordValue(name string, value float64, info ...any) + RecordValueWithPrecision(name string, value float64, units string, precision int, info ...any) } /* @@ -129,7 +129,7 @@ Deprecated: Measure() has been removed from Ginkgo 2.0 Use Gomega's gmeasure package instead. You can learn more here: https://onsi.github.io/ginkgo/#benchmarking-code */ -func Measure(_ ...interface{}) bool { +func Measure(_ ...any) bool { deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), types.NewCodeLocation(1)) return true } diff --git a/vendor/github.com/onsi/ginkgo/v2/formatter/formatter.go b/vendor/github.com/onsi/ginkgo/v2/formatter/formatter.go index 4d5749114..f61356db1 100644 --- a/vendor/github.com/onsi/ginkgo/v2/formatter/formatter.go +++ b/vendor/github.com/onsi/ginkgo/v2/formatter/formatter.go @@ -24,15 +24,15 @@ const ( var SingletonFormatter = New(ColorModeTerminal) -func F(format string, args ...interface{}) string { +func F(format string, args ...any) string { return SingletonFormatter.F(format, args...) } -func Fi(indentation uint, format string, args ...interface{}) string { +func Fi(indentation uint, format string, args ...any) string { return SingletonFormatter.Fi(indentation, format, args...) } -func Fiw(indentation uint, maxWidth uint, format string, args ...interface{}) string { +func Fiw(indentation uint, maxWidth uint, format string, args ...any) string { return SingletonFormatter.Fiw(indentation, maxWidth, format, args...) } @@ -115,15 +115,15 @@ func New(colorMode ColorMode) Formatter { return f } -func (f Formatter) F(format string, args ...interface{}) string { +func (f Formatter) F(format string, args ...any) string { return f.Fi(0, format, args...) } -func (f Formatter) Fi(indentation uint, format string, args ...interface{}) string { +func (f Formatter) Fi(indentation uint, format string, args ...any) string { return f.Fiw(indentation, 0, format, args...) } -func (f Formatter) Fiw(indentation uint, maxWidth uint, format string, args ...interface{}) string { +func (f Formatter) Fiw(indentation uint, maxWidth uint, format string, args ...any) string { out := f.style(format) if len(args) > 0 { out = fmt.Sprintf(out, args...) diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/build/build_command.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/build/build_command.go index fd1726084..2b36b2feb 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/build/build_command.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/build/build_command.go @@ -44,7 +44,7 @@ func buildSpecs(args []string, cliConfig types.CLIConfig, goFlagsConfig types.Go internal.VerifyCLIAndFrameworkVersion(suites) opc := internal.NewOrderedParallelCompiler(cliConfig.ComputedNumCompilers()) - opc.StartCompiling(suites, goFlagsConfig) + opc.StartCompiling(suites, goFlagsConfig, true) for { suiteIdx, suite := opc.Next() @@ -55,18 +55,22 @@ func buildSpecs(args []string, cliConfig types.CLIConfig, goFlagsConfig types.Go if suite.State.Is(internal.TestSuiteStateFailedToCompile) { fmt.Println(suite.CompilationError.Error()) } else { - if len(goFlagsConfig.O) == 0 { - goFlagsConfig.O = path.Join(suite.Path, suite.PackageName+".test") - } else { + var testBinPath string + if len(goFlagsConfig.O) != 0 { stat, err := os.Stat(goFlagsConfig.O) if err != nil { panic(err) } if stat.IsDir() { - goFlagsConfig.O += "/" + suite.PackageName + ".test" + testBinPath = goFlagsConfig.O + "/" + suite.PackageName + ".test" + } else { + testBinPath = goFlagsConfig.O } } - fmt.Printf("Compiled %s\n", goFlagsConfig.O) + if len(testBinPath) == 0 { + testBinPath = path.Join(suite.Path, suite.PackageName+".test") + } + fmt.Printf("Compiled %s\n", testBinPath) } } diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/abort.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/abort.go index 2efd28608..f0e7331f7 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/abort.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/abort.go @@ -12,7 +12,7 @@ func Abort(details AbortDetails) { panic(details) } -func AbortGracefullyWith(format string, args ...interface{}) { +func AbortGracefullyWith(format string, args ...any) { Abort(AbortDetails{ ExitCode: 0, Error: fmt.Errorf(format, args...), @@ -20,7 +20,7 @@ func AbortGracefullyWith(format string, args ...interface{}) { }) } -func AbortWith(format string, args ...interface{}) { +func AbortWith(format string, args ...any) { Abort(AbortDetails{ ExitCode: 1, Error: fmt.Errorf(format, args...), @@ -28,7 +28,7 @@ func AbortWith(format string, args ...interface{}) { }) } -func AbortWithUsage(format string, args ...interface{}) { +func AbortWithUsage(format string, args ...any) { Abort(AbortDetails{ ExitCode: 1, Error: fmt.Errorf(format, args...), diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/command.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/command.go index 12e0e5659..79b83a3af 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/command.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/command.go @@ -24,7 +24,11 @@ func (c Command) Run(args []string, additionalArgs []string) { if err != nil { AbortWithUsage(err.Error()) } - + for _, arg := range args { + if len(arg) > 1 && strings.HasPrefix(arg, "-") { + AbortWith(types.GinkgoErrors.FlagAfterPositionalParameter().Error()) + } + } c.Command(args, additionalArgs) } diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/program.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/program.go index 88dd8d6b0..c3f6d3a11 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/program.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/command/program.go @@ -68,7 +68,6 @@ func (p Program) RunAndExit(osArgs []string) { fmt.Fprintln(p.ErrWriter, deprecationTracker.DeprecationsReport()) } p.Exiter(exitCode) - return }() args, additionalArgs := []string{}, []string{} @@ -157,7 +156,6 @@ func (p Program) handleHelpRequestsAndExit(writer io.Writer, args []string) { p.EmitUsage(writer) Abort(AbortDetails{ExitCode: 1}) } - return } func (p Program) EmitUsage(writer io.Writer) { diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/compile.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/compile.go index 48827cc5e..7bbe6be0f 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/compile.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/compile.go @@ -11,7 +11,7 @@ import ( "github.com/onsi/ginkgo/v2/types" ) -func CompileSuite(suite TestSuite, goFlagsConfig types.GoFlagsConfig) TestSuite { +func CompileSuite(suite TestSuite, goFlagsConfig types.GoFlagsConfig, preserveSymbols bool) TestSuite { if suite.PathToCompiledTest != "" { return suite } @@ -46,7 +46,7 @@ func CompileSuite(suite TestSuite, goFlagsConfig types.GoFlagsConfig) TestSuite suite.CompilationError = fmt.Errorf("Failed to get relative path from package to the current working directory:\n%s", err.Error()) return suite } - args, err := types.GenerateGoTestCompileArgs(goFlagsConfig, "./", pathToInvocationPath) + args, err := types.GenerateGoTestCompileArgs(goFlagsConfig, "./", pathToInvocationPath, preserveSymbols) if err != nil { suite.State = TestSuiteStateFailedToCompile suite.CompilationError = fmt.Errorf("Failed to generate go test compile flags:\n%s", err.Error()) @@ -120,7 +120,7 @@ func NewOrderedParallelCompiler(numCompilers int) *OrderedParallelCompiler { } } -func (opc *OrderedParallelCompiler) StartCompiling(suites TestSuites, goFlagsConfig types.GoFlagsConfig) { +func (opc *OrderedParallelCompiler) StartCompiling(suites TestSuites, goFlagsConfig types.GoFlagsConfig, preserveSymbols bool) { opc.stopped = false opc.idx = 0 opc.numSuites = len(suites) @@ -135,7 +135,7 @@ func (opc *OrderedParallelCompiler) StartCompiling(suites TestSuites, goFlagsCon stopped := opc.stopped opc.mutex.Unlock() if !stopped { - suite = CompileSuite(suite, goFlagsConfig) + suite = CompileSuite(suite, goFlagsConfig, preserveSymbols) } c <- suite } diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/gocovmerge.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/gocovmerge.go index 3c5079ff4..87cfa1119 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/gocovmerge.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/internal/gocovmerge.go @@ -89,7 +89,7 @@ func mergeProfileBlock(p *cover.Profile, pb cover.ProfileBlock, startIndex int) } i := 0 - if sortFunc(i) != true { + if !sortFunc(i) { i = sort.Search(len(p.Blocks)-startIndex, sortFunc) } diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/outline.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/outline.go index c2327cda8..e99d557d1 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/outline.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/outline.go @@ -1,10 +1,13 @@ package outline import ( + "bytes" + "encoding/csv" "encoding/json" "fmt" "go/ast" "go/token" + "strconv" "strings" "golang.org/x/tools/go/ast/inspector" @@ -84,9 +87,11 @@ func (o *outline) String() string { // StringIndent returns a CSV-formated outline, but every line is indented by // one 'width' of spaces for every level of nesting. func (o *outline) StringIndent(width int) string { - var b strings.Builder + var b bytes.Buffer b.WriteString("Name,Text,Start,End,Spec,Focused,Pending,Labels\n") + csvWriter := csv.NewWriter(&b) + currentIndent := 0 pre := func(n *ginkgoNode) { b.WriteString(fmt.Sprintf("%*s", currentIndent, "")) @@ -96,8 +101,22 @@ func (o *outline) StringIndent(width int) string { } else { labels = strings.Join(n.Labels, ", ") } - //enclosing labels in a double quoted comma separate listed so that when inmported into a CSV app the Labels column has comma separate strings - b.WriteString(fmt.Sprintf("%s,%s,%d,%d,%t,%t,%t,\"%s\"\n", n.Name, n.Text, n.Start, n.End, n.Spec, n.Focused, n.Pending, labels)) + + row := []string{ + n.Name, + n.Text, + strconv.Itoa(n.Start), + strconv.Itoa(n.End), + strconv.FormatBool(n.Spec), + strconv.FormatBool(n.Focused), + strconv.FormatBool(n.Pending), + labels, + } + csvWriter.Write(row) + + // Ensure we write to `b' before the next `b.WriteString()', which might be adding indentation + csvWriter.Flush() + currentIndent += width } post := func(n *ginkgoNode) { @@ -106,5 +125,6 @@ func (o *outline) StringIndent(width int) string { for _, n := range o.Nodes { n.Walk(pre, post) } + return b.String() } diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/run/run_command.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/run/run_command.go index aaed4d570..03875b979 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/run/run_command.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/run/run_command.go @@ -107,7 +107,7 @@ OUTER_LOOP: } opc := internal.NewOrderedParallelCompiler(r.cliConfig.ComputedNumCompilers()) - opc.StartCompiling(suites, r.goFlagsConfig) + opc.StartCompiling(suites, r.goFlagsConfig, false) SUITE_LOOP: for { @@ -142,7 +142,7 @@ OUTER_LOOP: } if !endTime.IsZero() { - r.suiteConfig.Timeout = endTime.Sub(time.Now()) + r.suiteConfig.Timeout = time.Until(endTime) if r.suiteConfig.Timeout <= 0 { suites[suiteIdx].State = internal.TestSuiteStateFailedDueToTimeout opc.StopAndDrain() diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/watch/watch_command.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/watch/watch_command.go index bde4193ce..fe1ca3051 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/watch/watch_command.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/watch/watch_command.go @@ -153,7 +153,7 @@ func (w *SpecWatcher) WatchSpecs(args []string, additionalArgs []string) { } func (w *SpecWatcher) compileAndRun(suite internal.TestSuite, additionalArgs []string) internal.TestSuite { - suite = internal.CompileSuite(suite, w.goFlagsConfig) + suite = internal.CompileSuite(suite, w.goFlagsConfig, false) if suite.State.Is(internal.TestSuiteStateFailedToCompile) { fmt.Println(suite.CompilationError.Error()) return suite diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go index 02c6739e5..993279de2 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go @@ -1,6 +1,7 @@ package ginkgo import ( + "context" "testing" "github.com/onsi/ginkgo/v2/internal/testingtproxy" @@ -48,6 +49,8 @@ The portion of the interface returned by GinkgoT() that maps onto methods in the */ type GinkgoTInterface interface { Cleanup(func()) + Chdir(dir string) + Context() context.Context Setenv(kev, value string) Error(args ...any) Errorf(format string, args ...any) @@ -127,6 +130,12 @@ type GinkgoTBWrapper struct { func (g *GinkgoTBWrapper) Cleanup(f func()) { g.GinkgoT.Cleanup(f) } +func (g *GinkgoTBWrapper) Chdir(dir string) { + g.GinkgoT.Chdir(dir) +} +func (g *GinkgoTBWrapper) Context() context.Context { + return g.GinkgoT.Context() +} func (g *GinkgoTBWrapper) Error(args ...any) { g.GinkgoT.Error(args...) } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/failer.go b/vendor/github.com/onsi/ginkgo/v2/internal/failer.go index e9bd9565f..8c5de9c16 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/failer.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/failer.go @@ -32,7 +32,7 @@ func (f *Failer) GetFailure() types.Failure { return f.failure } -func (f *Failer) Panic(location types.CodeLocation, forwardedPanic interface{}) { +func (f *Failer) Panic(location types.CodeLocation, forwardedPanic any) { f.lock.Lock() defer f.lock.Unlock() diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/interrupt_handler/interrupt_handler.go b/vendor/github.com/onsi/ginkgo/v2/internal/interrupt_handler/interrupt_handler.go index 8ed86111f..79bfa87db 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/interrupt_handler/interrupt_handler.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/interrupt_handler/interrupt_handler.go @@ -40,7 +40,7 @@ func (ic InterruptCause) String() string { } type InterruptStatus struct { - Channel chan interface{} + Channel chan any Level InterruptLevel Cause InterruptCause } @@ -62,14 +62,14 @@ type InterruptHandlerInterface interface { } type InterruptHandler struct { - c chan interface{} + c chan any lock *sync.Mutex level InterruptLevel cause InterruptCause client parallel_support.Client - stop chan interface{} + stop chan any signals []os.Signal - requestAbortCheck chan interface{} + requestAbortCheck chan any } func NewInterruptHandler(client parallel_support.Client, signals ...os.Signal) *InterruptHandler { @@ -77,10 +77,10 @@ func NewInterruptHandler(client parallel_support.Client, signals ...os.Signal) * signals = []os.Signal{os.Interrupt, syscall.SIGTERM} } handler := &InterruptHandler{ - c: make(chan interface{}), + c: make(chan any), lock: &sync.Mutex{}, - stop: make(chan interface{}), - requestAbortCheck: make(chan interface{}), + stop: make(chan any), + requestAbortCheck: make(chan any), client: client, signals: signals, } @@ -98,9 +98,9 @@ func (handler *InterruptHandler) registerForInterrupts() { signal.Notify(signalChannel, handler.signals...) // cross-process abort handling - var abortChannel chan interface{} + var abortChannel chan any if handler.client != nil { - abortChannel = make(chan interface{}) + abortChannel = make(chan any) go func() { pollTicker := time.NewTicker(ABORT_POLLING_INTERVAL) for { @@ -125,7 +125,7 @@ func (handler *InterruptHandler) registerForInterrupts() { }() } - go func(abortChannel chan interface{}) { + go func(abortChannel chan any) { var interruptCause InterruptCause for { select { @@ -151,7 +151,7 @@ func (handler *InterruptHandler) registerForInterrupts() { } if handler.level != oldLevel { close(handler.c) - handler.c = make(chan interface{}) + handler.c = make(chan any) } handler.lock.Unlock() } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/node.go b/vendor/github.com/onsi/ginkgo/v2/internal/node.go index 0686f7410..8096950b6 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/node.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/node.go @@ -84,7 +84,7 @@ const SuppressProgressReporting = suppressProgressReporting(true) type FlakeAttempts uint type MustPassRepeatedly uint type Offset uint -type Done chan<- interface{} // Deprecated Done Channel for asynchronous testing +type Done chan<- any // Deprecated Done Channel for asynchronous testing type Labels []string type PollProgressInterval time.Duration type PollProgressAfter time.Duration @@ -110,9 +110,9 @@ func UnionOfLabels(labels ...Labels) Labels { return out } -func PartitionDecorations(args ...interface{}) ([]interface{}, []interface{}) { - decorations := []interface{}{} - remainingArgs := []interface{}{} +func PartitionDecorations(args ...any) ([]any, []any) { + decorations := []any{} + remainingArgs := []any{} for _, arg := range args { if isDecoration(arg) { decorations = append(decorations, arg) @@ -123,7 +123,7 @@ func PartitionDecorations(args ...interface{}) ([]interface{}, []interface{}) { return decorations, remainingArgs } -func isDecoration(arg interface{}) bool { +func isDecoration(arg any) bool { switch t := reflect.TypeOf(arg); { case t == nil: return false @@ -168,7 +168,7 @@ func isDecoration(arg interface{}) bool { } } -func isSliceOfDecorations(slice interface{}) bool { +func isSliceOfDecorations(slice any) bool { vSlice := reflect.ValueOf(slice) if vSlice.Len() == 0 { return false @@ -184,7 +184,7 @@ func isSliceOfDecorations(slice interface{}) bool { var contextType = reflect.TypeOf(new(context.Context)).Elem() var specContextType = reflect.TypeOf(new(SpecContext)).Elem() -func NewNode(deprecationTracker *types.DeprecationTracker, nodeType types.NodeType, text string, args ...interface{}) (Node, []error) { +func NewNode(deprecationTracker *types.DeprecationTracker, nodeType types.NodeType, text string, args ...any) (Node, []error) { baseOffset := 2 node := Node{ ID: UniqueNodeID(), @@ -207,7 +207,7 @@ func NewNode(deprecationTracker *types.DeprecationTracker, nodeType types.NodeTy args = unrollInterfaceSlice(args) - remainingArgs := []interface{}{} + remainingArgs := []any{} // First get the CodeLocation up-to-date for _, arg := range args { switch v := arg.(type) { @@ -223,7 +223,7 @@ func NewNode(deprecationTracker *types.DeprecationTracker, nodeType types.NodeTy labelsSeen := map[string]bool{} trackedFunctionError := false args = remainingArgs - remainingArgs = []interface{}{} + remainingArgs = []any{} // now process the rest of the args for _, arg := range args { switch t := reflect.TypeOf(arg); { @@ -451,7 +451,7 @@ func NewNode(deprecationTracker *types.DeprecationTracker, nodeType types.NodeTy var doneType = reflect.TypeOf(make(Done)) -func extractBodyFunction(deprecationTracker *types.DeprecationTracker, cl types.CodeLocation, arg interface{}) (func(SpecContext), bool) { +func extractBodyFunction(deprecationTracker *types.DeprecationTracker, cl types.CodeLocation, arg any) (func(SpecContext), bool) { t := reflect.TypeOf(arg) if t.NumOut() > 0 || t.NumIn() > 1 { return nil, false @@ -477,7 +477,7 @@ func extractBodyFunction(deprecationTracker *types.DeprecationTracker, cl types. var byteType = reflect.TypeOf([]byte{}) -func extractSynchronizedBeforeSuiteProc1Body(arg interface{}) (func(SpecContext) []byte, bool) { +func extractSynchronizedBeforeSuiteProc1Body(arg any) (func(SpecContext) []byte, bool) { t := reflect.TypeOf(arg) v := reflect.ValueOf(arg) @@ -505,7 +505,7 @@ func extractSynchronizedBeforeSuiteProc1Body(arg interface{}) (func(SpecContext) }, hasContext } -func extractSynchronizedBeforeSuiteAllProcsBody(arg interface{}) (func(SpecContext, []byte), bool) { +func extractSynchronizedBeforeSuiteAllProcsBody(arg any) (func(SpecContext, []byte), bool) { t := reflect.TypeOf(arg) v := reflect.ValueOf(arg) hasContext, hasByte := false, false @@ -536,11 +536,11 @@ func extractSynchronizedBeforeSuiteAllProcsBody(arg interface{}) (func(SpecConte var errInterface = reflect.TypeOf((*error)(nil)).Elem() -func NewCleanupNode(deprecationTracker *types.DeprecationTracker, fail func(string, types.CodeLocation), args ...interface{}) (Node, []error) { +func NewCleanupNode(deprecationTracker *types.DeprecationTracker, fail func(string, types.CodeLocation), args ...any) (Node, []error) { decorations, remainingArgs := PartitionDecorations(args...) baseOffset := 2 cl := types.NewCodeLocation(baseOffset) - finalArgs := []interface{}{} + finalArgs := []any{} for _, arg := range decorations { switch t := reflect.TypeOf(arg); { case t == reflect.TypeOf(Offset(0)): @@ -920,12 +920,12 @@ func (n Nodes) GetMaxMustPassRepeatedly() int { return maxMustPassRepeatedly } -func unrollInterfaceSlice(args interface{}) []interface{} { +func unrollInterfaceSlice(args any) []any { v := reflect.ValueOf(args) if v.Kind() != reflect.Slice { - return []interface{}{args} + return []any{args} } - out := []interface{}{} + out := []any{} for i := 0; i < v.Len(); i++ { el := reflect.ValueOf(v.Index(i).Interface()) if el.Kind() == reflect.Slice && el.Type() != reflect.TypeOf(Labels{}) { diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor.go b/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor.go index 4a1c09461..5598f15cb 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor.go @@ -69,7 +69,7 @@ type pipePair struct { writer *os.File } -func startPipeFactory(pipeChannel chan pipePair, shutdown chan interface{}) { +func startPipeFactory(pipeChannel chan pipePair, shutdown chan any) { for { //make the next pipe... pair := pipePair{} @@ -101,8 +101,8 @@ type genericOutputInterceptor struct { stderrClone *os.File pipe pipePair - shutdown chan interface{} - emergencyBailout chan interface{} + shutdown chan any + emergencyBailout chan any pipeChannel chan pipePair interceptedContent chan string @@ -139,7 +139,7 @@ func (interceptor *genericOutputInterceptor) ResumeIntercepting() { interceptor.intercepting = true if interceptor.stdoutClone == nil { interceptor.stdoutClone, interceptor.stderrClone = interceptor.implementation.CreateStdoutStderrClones() - interceptor.shutdown = make(chan interface{}) + interceptor.shutdown = make(chan any) go startPipeFactory(interceptor.pipeChannel, interceptor.shutdown) } @@ -147,13 +147,13 @@ func (interceptor *genericOutputInterceptor) ResumeIntercepting() { // we get the pipe from our pipe factory. it runs in the background so we can request the next pipe while the spec being intercepted is running interceptor.pipe = <-interceptor.pipeChannel - interceptor.emergencyBailout = make(chan interface{}) + interceptor.emergencyBailout = make(chan any) //Spin up a goroutine to copy data from the pipe into a buffer, this is how we capture any output the user is emitting go func() { buffer := &bytes.Buffer{} destination := io.MultiWriter(buffer, interceptor.forwardTo) - copyFinished := make(chan interface{}) + copyFinished := make(chan any) reader := interceptor.pipe.reader go func() { io.Copy(destination, reader) @@ -224,7 +224,7 @@ func NewOSGlobalReassigningOutputInterceptor() OutputInterceptor { return &genericOutputInterceptor{ interceptedContent: make(chan string), pipeChannel: make(chan pipePair), - shutdown: make(chan interface{}), + shutdown: make(chan any), implementation: &osGlobalReassigningOutputInterceptorImpl{}, } } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor_unix.go b/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor_unix.go index 8a237f446..e0f1431d5 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor_unix.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/output_interceptor_unix.go @@ -13,7 +13,7 @@ func NewOutputInterceptor() OutputInterceptor { return &genericOutputInterceptor{ interceptedContent: make(chan string), pipeChannel: make(chan pipePair), - shutdown: make(chan interface{}), + shutdown: make(chan any), implementation: &dupSyscallOutputInterceptorImpl{}, } } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/client_server.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/client_server.go index b3cd64292..4234d802c 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/client_server.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/client_server.go @@ -30,7 +30,7 @@ type Server interface { Close() Address() string RegisterAlive(node int, alive func() bool) - GetSuiteDone() chan interface{} + GetSuiteDone() chan any GetOutputDestination() io.Writer SetOutputDestination(io.Writer) } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_client.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_client.go index 6547c7a66..4aa10ae4f 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_client.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_client.go @@ -34,7 +34,7 @@ func (client *httpClient) Close() error { return nil } -func (client *httpClient) post(path string, data interface{}) error { +func (client *httpClient) post(path string, data any) error { var body io.Reader if data != nil { encoded, err := json.Marshal(data) @@ -54,7 +54,7 @@ func (client *httpClient) post(path string, data interface{}) error { return nil } -func (client *httpClient) poll(path string, data interface{}) error { +func (client *httpClient) poll(path string, data any) error { for { resp, err := http.Get(client.serverHost + path) if err != nil { @@ -153,10 +153,7 @@ func (client *httpClient) PostAbort() error { func (client *httpClient) ShouldAbort() bool { err := client.poll("/abort", nil) - if err == ErrorGone { - return true - } - return false + return err == ErrorGone } func (client *httpClient) Write(p []byte) (int, error) { diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_server.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_server.go index d2c71ab1b..8a1b7a5bb 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_server.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/http_server.go @@ -75,7 +75,7 @@ func (server *httpServer) Address() string { return "http://" + server.listener.Addr().String() } -func (server *httpServer) GetSuiteDone() chan interface{} { +func (server *httpServer) GetSuiteDone() chan any { return server.handler.done } @@ -96,7 +96,7 @@ func (server *httpServer) RegisterAlive(node int, alive func() bool) { // // The server will forward all received messages to Ginkgo reporters registered with `RegisterReporters` -func (server *httpServer) decode(writer http.ResponseWriter, request *http.Request, object interface{}) bool { +func (server *httpServer) decode(writer http.ResponseWriter, request *http.Request, object any) bool { defer request.Body.Close() if json.NewDecoder(request.Body).Decode(object) != nil { writer.WriteHeader(http.StatusBadRequest) diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_client.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_client.go index 59e8e6fd0..bb4675a02 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_client.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_client.go @@ -35,7 +35,7 @@ func (client *rpcClient) Close() error { return client.client.Close() } -func (client *rpcClient) poll(method string, data interface{}) error { +func (client *rpcClient) poll(method string, data any) error { for { err := client.client.Call(method, voidSender, data) if err == nil { diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_server.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_server.go index 2620fd562..1574f99ac 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_server.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/rpc_server.go @@ -25,7 +25,7 @@ type RPCServer struct { handler *ServerHandler } -//Create a new server, automatically selecting a port +// Create a new server, automatically selecting a port func newRPCServer(parallelTotal int, reporter reporters.Reporter) (*RPCServer, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -37,7 +37,7 @@ func newRPCServer(parallelTotal int, reporter reporters.Reporter) (*RPCServer, e }, nil } -//Start the server. You don't need to `go s.Start()`, just `s.Start()` +// Start the server. You don't need to `go s.Start()`, just `s.Start()` func (server *RPCServer) Start() { rpcServer := rpc.NewServer() rpcServer.RegisterName("Server", server.handler) //register the handler's methods as the server @@ -48,17 +48,17 @@ func (server *RPCServer) Start() { go httpServer.Serve(server.listener) } -//Stop the server +// Stop the server func (server *RPCServer) Close() { server.listener.Close() } -//The address the server can be reached it. Pass this into the `ForwardingReporter`. +// The address the server can be reached it. Pass this into the `ForwardingReporter`. func (server *RPCServer) Address() string { return server.listener.Addr().String() } -func (server *RPCServer) GetSuiteDone() chan interface{} { +func (server *RPCServer) GetSuiteDone() chan any { return server.handler.done } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/server_handler.go b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/server_handler.go index a6d98793e..ab9e11372 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/server_handler.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/parallel_support/server_handler.go @@ -18,7 +18,7 @@ var voidSender Void // It handles all the business logic to avoid duplication between the two servers type ServerHandler struct { - done chan interface{} + done chan any outputDestination io.Writer reporter reporters.Reporter alives []func() bool @@ -46,7 +46,7 @@ func newServerHandler(parallelTotal int, reporter reporters.Reporter) *ServerHan parallelTotal: parallelTotal, outputDestination: os.Stdout, - done: make(chan interface{}), + done: make(chan any), } } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/report_entry.go b/vendor/github.com/onsi/ginkgo/v2/internal/report_entry.go index cc351a39b..9c18dc8e5 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/report_entry.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/report_entry.go @@ -8,7 +8,7 @@ import ( type ReportEntry = types.ReportEntry -func NewReportEntry(name string, cl types.CodeLocation, args ...interface{}) (ReportEntry, error) { +func NewReportEntry(name string, cl types.CodeLocation, args ...any) (ReportEntry, error) { out := ReportEntry{ Visibility: types.ReportEntryVisibilityAlways, Name: name, diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/suite.go b/vendor/github.com/onsi/ginkgo/v2/internal/suite.go index a3c9e6bf1..3edf50776 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/suite.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/suite.go @@ -1,6 +1,7 @@ package internal import ( + "context" "fmt" "sync" "time" @@ -9,7 +10,6 @@ import ( "github.com/onsi/ginkgo/v2/internal/parallel_support" "github.com/onsi/ginkgo/v2/reporters" "github.com/onsi/ginkgo/v2/types" - "golang.org/x/net/context" ) type Phase uint @@ -20,7 +20,7 @@ const ( PhaseRun ) -var PROGRESS_REPORTER_DEADLING = 5 * time.Second +const ProgressReporterDeadline = 5 * time.Second type Suite struct { tree *TreeNode @@ -370,7 +370,7 @@ func (suite *Suite) generateProgressReport(fullReport bool) types.ProgressReport suite.selectiveLock.Lock() defer suite.selectiveLock.Unlock() - deadline, cancel := context.WithTimeout(context.Background(), PROGRESS_REPORTER_DEADLING) + deadline, cancel := context.WithTimeout(context.Background(), ProgressReporterDeadline) defer cancel() var additionalReports []string if suite.currentSpecContext != nil { diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/testingtproxy/testing_t_proxy.go b/vendor/github.com/onsi/ginkgo/v2/internal/testingtproxy/testing_t_proxy.go index 73e265565..b4ecc7cb8 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/testingtproxy/testing_t_proxy.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/testingtproxy/testing_t_proxy.go @@ -1,6 +1,7 @@ package testingtproxy import ( + "context" "fmt" "io" "os" @@ -19,9 +20,9 @@ type addReportEntryFunc func(names string, args ...any) type ginkgoWriterInterface interface { io.Writer - Print(a ...interface{}) - Printf(format string, a ...interface{}) - Println(a ...interface{}) + Print(a ...any) + Printf(format string, a ...any) + Println(a ...any) } type ginkgoRecoverFunc func() type attachProgressReporterFunc func(func() string) func() @@ -80,11 +81,31 @@ func (t *ginkgoTestingTProxy) Setenv(key, value string) { } } -func (t *ginkgoTestingTProxy) Error(args ...interface{}) { +func (t *ginkgoTestingTProxy) Chdir(dir string) { + currentDir, err := os.Getwd() + if err != nil { + t.fail(fmt.Sprintf("Failed to get current directory: %v", err), 1) + } + + t.cleanup(os.Chdir, currentDir, internal.Offset(1)) + + err = os.Chdir(dir) + if err != nil { + t.fail(fmt.Sprintf("Failed to change directory: %v", err), 1) + } +} + +func (t *ginkgoTestingTProxy) Context() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + t.cleanup(cancel, internal.Offset(1)) + return ctx +} + +func (t *ginkgoTestingTProxy) Error(args ...any) { t.fail(fmt.Sprintln(args...), t.offset) } -func (t *ginkgoTestingTProxy) Errorf(format string, args ...interface{}) { +func (t *ginkgoTestingTProxy) Errorf(format string, args ...any) { t.fail(fmt.Sprintf(format, args...), t.offset) } @@ -100,11 +121,11 @@ func (t *ginkgoTestingTProxy) Failed() bool { return t.report().Failed() } -func (t *ginkgoTestingTProxy) Fatal(args ...interface{}) { +func (t *ginkgoTestingTProxy) Fatal(args ...any) { t.fail(fmt.Sprintln(args...), t.offset) } -func (t *ginkgoTestingTProxy) Fatalf(format string, args ...interface{}) { +func (t *ginkgoTestingTProxy) Fatalf(format string, args ...any) { t.fail(fmt.Sprintf(format, args...), t.offset) } @@ -112,11 +133,11 @@ func (t *ginkgoTestingTProxy) Helper() { types.MarkAsHelper(1) } -func (t *ginkgoTestingTProxy) Log(args ...interface{}) { +func (t *ginkgoTestingTProxy) Log(args ...any) { fmt.Fprintln(t.writer, args...) } -func (t *ginkgoTestingTProxy) Logf(format string, args ...interface{}) { +func (t *ginkgoTestingTProxy) Logf(format string, args ...any) { t.Log(fmt.Sprintf(format, args...)) } @@ -128,7 +149,7 @@ func (t *ginkgoTestingTProxy) Parallel() { // No-op } -func (t *ginkgoTestingTProxy) Skip(args ...interface{}) { +func (t *ginkgoTestingTProxy) Skip(args ...any) { t.skip(fmt.Sprintln(args...), t.offset) } @@ -136,7 +157,7 @@ func (t *ginkgoTestingTProxy) SkipNow() { t.skip("skip", t.offset) } -func (t *ginkgoTestingTProxy) Skipf(format string, args ...interface{}) { +func (t *ginkgoTestingTProxy) Skipf(format string, args ...any) { t.skip(fmt.Sprintf(format, args...), t.offset) } diff --git a/vendor/github.com/onsi/ginkgo/v2/internal/writer.go b/vendor/github.com/onsi/ginkgo/v2/internal/writer.go index aab42d5fb..1c4e0534e 100644 --- a/vendor/github.com/onsi/ginkgo/v2/internal/writer.go +++ b/vendor/github.com/onsi/ginkgo/v2/internal/writer.go @@ -121,15 +121,15 @@ func (w *Writer) ClearTeeWriters() { w.teeWriters = []io.Writer{} } -func (w *Writer) Print(a ...interface{}) { +func (w *Writer) Print(a ...any) { fmt.Fprint(w, a...) } -func (w *Writer) Printf(format string, a ...interface{}) { +func (w *Writer) Printf(format string, a ...any) { fmt.Fprintf(w, format, a...) } -func (w *Writer) Println(a ...interface{}) { +func (w *Writer) Println(a ...any) { fmt.Fprintln(w, a...) } diff --git a/vendor/github.com/onsi/ginkgo/v2/reporters/default_reporter.go b/vendor/github.com/onsi/ginkgo/v2/reporters/default_reporter.go index 480730486..74ad0768b 100644 --- a/vendor/github.com/onsi/ginkgo/v2/reporters/default_reporter.go +++ b/vendor/github.com/onsi/ginkgo/v2/reporters/default_reporter.go @@ -685,11 +685,11 @@ func (r *DefaultReporter) _emit(s string, block bool, isDelimiter bool) { } /* Rendering text */ -func (r *DefaultReporter) f(format string, args ...interface{}) string { +func (r *DefaultReporter) f(format string, args ...any) string { return r.formatter.F(format, args...) } -func (r *DefaultReporter) fi(indentation uint, format string, args ...interface{}) string { +func (r *DefaultReporter) fi(indentation uint, format string, args ...any) string { return r.formatter.Fi(indentation, format, args...) } diff --git a/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go b/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go index aa1a35176..5bf2e62e9 100644 --- a/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go +++ b/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go @@ -60,7 +60,7 @@ AddReportEntry() must be called within a Subject or Setup node - not in a Contai You can learn more about Report Entries here: https://onsi.github.io/ginkgo/#attaching-data-to-reports */ -func AddReportEntry(name string, args ...interface{}) { +func AddReportEntry(name string, args ...any) { cl := types.NewCodeLocation(1) reportEntry, err := internal.NewReportEntry(name, cl, args...) if err != nil { @@ -89,7 +89,7 @@ You can learn more about ReportBeforeEach here: https://onsi.github.io/ginkgo/#g You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportBeforeEach(body any, args ...any) bool { - combinedArgs := []interface{}{body} + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportBeforeEach, "", combinedArgs...)) @@ -113,7 +113,7 @@ You can learn more about ReportAfterEach here: https://onsi.github.io/ginkgo/#ge You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportAfterEach(body any, args ...any) bool { - combinedArgs := []interface{}{body} + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportAfterEach, "", combinedArgs...)) @@ -143,7 +143,7 @@ You can learn more about Ginkgo's reporting infrastructure, including generating You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportBeforeSuite(body any, args ...any) bool { - combinedArgs := []interface{}{body} + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportBeforeSuite, "", combinedArgs...)) } @@ -174,8 +174,8 @@ You can learn more about Ginkgo's reporting infrastructure, including generating You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ -func ReportAfterSuite(text string, body any, args ...interface{}) bool { - combinedArgs := []interface{}{body} +func ReportAfterSuite(text string, body any, args ...any) bool { + combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportAfterSuite, text, combinedArgs...)) } diff --git a/vendor/github.com/onsi/ginkgo/v2/table_dsl.go b/vendor/github.com/onsi/ginkgo/v2/table_dsl.go index 9074a57ac..b9e0ca9ef 100644 --- a/vendor/github.com/onsi/ginkgo/v2/table_dsl.go +++ b/vendor/github.com/onsi/ginkgo/v2/table_dsl.go @@ -23,7 +23,7 @@ You can learn more about generating EntryDescriptions here: https://onsi.github. */ type EntryDescription string -func (ed EntryDescription) render(args ...interface{}) string { +func (ed EntryDescription) render(args ...any) string { return fmt.Sprintf(string(ed), args...) } @@ -44,7 +44,7 @@ For example: You can learn more about DescribeTable here: https://onsi.github.io/ginkgo/#table-specs And can explore some Table patterns here: https://onsi.github.io/ginkgo/#table-specs-patterns */ -func DescribeTable(description string, args ...interface{}) bool { +func DescribeTable(description string, args ...any) bool { GinkgoHelper() generateTable(description, false, args...) return true @@ -53,7 +53,7 @@ func DescribeTable(description string, args ...interface{}) bool { /* You can focus a table with `FDescribeTable`. This is equivalent to `FDescribe`. */ -func FDescribeTable(description string, args ...interface{}) bool { +func FDescribeTable(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Focus) generateTable(description, false, args...) @@ -63,7 +63,7 @@ func FDescribeTable(description string, args ...interface{}) bool { /* You can mark a table as pending with `PDescribeTable`. This is equivalent to `PDescribe`. */ -func PDescribeTable(description string, args ...interface{}) bool { +func PDescribeTable(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Pending) generateTable(description, false, args...) @@ -109,7 +109,7 @@ Note that you **must** place define an It inside the body function. You can learn more about DescribeTableSubtree here: https://onsi.github.io/ginkgo/#table-specs And can explore some Table patterns here: https://onsi.github.io/ginkgo/#table-specs-patterns */ -func DescribeTableSubtree(description string, args ...interface{}) bool { +func DescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() generateTable(description, true, args...) return true @@ -118,7 +118,7 @@ func DescribeTableSubtree(description string, args ...interface{}) bool { /* You can focus a table with `FDescribeTableSubtree`. This is equivalent to `FDescribe`. */ -func FDescribeTableSubtree(description string, args ...interface{}) bool { +func FDescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Focus) generateTable(description, true, args...) @@ -128,7 +128,7 @@ func FDescribeTableSubtree(description string, args ...interface{}) bool { /* You can mark a table as pending with `PDescribeTableSubtree`. This is equivalent to `PDescribe`. */ -func PDescribeTableSubtree(description string, args ...interface{}) bool { +func PDescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Pending) generateTable(description, true, args...) @@ -144,9 +144,9 @@ var XDescribeTableSubtree = PDescribeTableSubtree TableEntry represents an entry in a table test. You generally use the `Entry` constructor. */ type TableEntry struct { - description interface{} - decorations []interface{} - parameters []interface{} + description any + decorations []any + parameters []any codeLocation types.CodeLocation } @@ -162,7 +162,7 @@ If you want to generate interruptible specs simply write a Table function that a You can learn more about Entry here: https://onsi.github.io/ginkgo/#table-specs */ -func Entry(description interface{}, args ...interface{}) TableEntry { +func Entry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) return TableEntry{description: description, decorations: decorations, parameters: parameters, codeLocation: types.NewCodeLocation(0)} @@ -171,7 +171,7 @@ func Entry(description interface{}, args ...interface{}) TableEntry { /* You can focus a particular entry with FEntry. This is equivalent to FIt. */ -func FEntry(description interface{}, args ...interface{}) TableEntry { +func FEntry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) decorations = append(decorations, internal.Focus) @@ -181,7 +181,7 @@ func FEntry(description interface{}, args ...interface{}) TableEntry { /* You can mark a particular entry as pending with PEntry. This is equivalent to PIt. */ -func PEntry(description interface{}, args ...interface{}) TableEntry { +func PEntry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) decorations = append(decorations, internal.Pending) @@ -196,17 +196,17 @@ var XEntry = PEntry var contextType = reflect.TypeOf(new(context.Context)).Elem() var specContextType = reflect.TypeOf(new(SpecContext)).Elem() -func generateTable(description string, isSubtree bool, args ...interface{}) { +func generateTable(description string, isSubtree bool, args ...any) { GinkgoHelper() cl := types.NewCodeLocation(0) - containerNodeArgs := []interface{}{cl} + containerNodeArgs := []any{cl} entries := []TableEntry{} - var internalBody interface{} + var internalBody any var internalBodyType reflect.Type - var tableLevelEntryDescription interface{} - tableLevelEntryDescription = func(args ...interface{}) string { + var tableLevelEntryDescription any + tableLevelEntryDescription = func(args ...any) string { out := []string{} for _, arg := range args { out = append(out, fmt.Sprint(arg)) @@ -265,7 +265,7 @@ func generateTable(description string, isSubtree bool, args ...interface{}) { err = types.GinkgoErrors.InvalidEntryDescription(entry.codeLocation) } - internalNodeArgs := []interface{}{entry.codeLocation} + internalNodeArgs := []any{entry.codeLocation} internalNodeArgs = append(internalNodeArgs, entry.decorations...) hasContext := false @@ -290,7 +290,7 @@ func generateTable(description string, isSubtree bool, args ...interface{}) { if err != nil { panic(err) } - invokeFunction(internalBody, append([]interface{}{c}, entry.parameters...)) + invokeFunction(internalBody, append([]any{c}, entry.parameters...)) }) if isSubtree { exitIfErr(types.GinkgoErrors.ContextsCannotBeUsedInSubtreeTables(cl)) @@ -316,7 +316,7 @@ func generateTable(description string, isSubtree bool, args ...interface{}) { pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, description, containerNodeArgs...)) } -func invokeFunction(function interface{}, parameters []interface{}) []reflect.Value { +func invokeFunction(function any, parameters []any) []reflect.Value { inValues := make([]reflect.Value, len(parameters)) funcType := reflect.TypeOf(function) @@ -339,7 +339,7 @@ func invokeFunction(function interface{}, parameters []interface{}) []reflect.Va return reflect.ValueOf(function).Call(inValues) } -func validateParameters(function interface{}, parameters []interface{}, kind string, cl types.CodeLocation, hasContext bool) error { +func validateParameters(function any, parameters []any, kind string, cl types.CodeLocation, hasContext bool) error { funcType := reflect.TypeOf(function) limit := funcType.NumIn() offset := 0 @@ -377,7 +377,7 @@ func validateParameters(function interface{}, parameters []interface{}, kind str return nil } -func computeValue(parameter interface{}, t reflect.Type) reflect.Value { +func computeValue(parameter any, t reflect.Type) reflect.Value { if parameter == nil { return reflect.Zero(t) } else { diff --git a/vendor/github.com/onsi/ginkgo/v2/types/config.go b/vendor/github.com/onsi/ginkgo/v2/types/config.go index 8c0dfab8c..ca837b055 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/config.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/config.go @@ -231,6 +231,10 @@ func (g GoFlagsConfig) BinaryMustBePreserved() bool { return g.BlockProfile != "" || g.CPUProfile != "" || g.MemProfile != "" || g.MutexProfile != "" } +func (g GoFlagsConfig) NeedsSymbols() bool { + return g.BinaryMustBePreserved() +} + // Configuration that were deprecated in 2.0 type deprecatedConfig struct { DebugParallel bool @@ -257,8 +261,12 @@ var FlagSections = GinkgoFlagSections{ {Key: "filter", Style: "{{cyan}}", Heading: "Filtering Tests"}, {Key: "failure", Style: "{{red}}", Heading: "Failure Handling"}, {Key: "output", Style: "{{magenta}}", Heading: "Controlling Output Formatting"}, - {Key: "code-and-coverage-analysis", Style: "{{orange}}", Heading: "Code and Coverage Analysis"}, - {Key: "performance-analysis", Style: "{{coral}}", Heading: "Performance Analysis"}, + {Key: "code-and-coverage-analysis", Style: "{{orange}}", Heading: "Code and Coverage Analysis", + Description: "When generating a cover files, please pass a filename {{bold}}not{{/}} a path. To specify a different directory use {{magenta}}--output-dir{{/}}.", + }, + {Key: "performance-analysis", Style: "{{coral}}", Heading: "Performance Analysis", + Description: "When generating profile files, please pass filenames {{bold}}not{{/}} a path. Ginkgo will generate a profile file with the given name in the package's directory. To specify a different directory use {{magenta}}--output-dir{{/}}.", + }, {Key: "debug", Style: "{{blue}}", Heading: "Debugging Tests", Description: "In addition to these flags, Ginkgo supports a few debugging environment variables. To change the parallel server protocol set {{blue}}GINKGO_PARALLEL_PROTOCOL{{/}} to {{bold}}HTTP{{/}}. To avoid pruning callstacks set {{blue}}GINKGO_PRUNE_STACK{{/}} to {{bold}}FALSE{{/}}."}, {Key: "watch", Style: "{{light-yellow}}", Heading: "Controlling Ginkgo Watch"}, @@ -365,7 +373,7 @@ var ReporterConfigFlags = GinkgoFlags{ func BuildTestSuiteFlagSet(suiteConfig *SuiteConfig, reporterConfig *ReporterConfig) (GinkgoFlagSet, error) { flags := SuiteConfigFlags.CopyAppend(ParallelConfigFlags...).CopyAppend(ReporterConfigFlags...) flags = flags.WithPrefix("ginkgo") - bindings := map[string]interface{}{ + bindings := map[string]any{ "S": suiteConfig, "R": reporterConfig, "D": &deprecatedConfig{}, @@ -572,7 +580,7 @@ var GoBuildFlags = GinkgoFlags{ // GoRunFlags provides flags for the Ginkgo CLI run, and watch commands that capture go's run-time flags. These are passed to the compiled test binary by the ginkgo CLI var GoRunFlags = GinkgoFlags{ {KeyPath: "Go.CoverProfile", Name: "coverprofile", UsageArgument: "file", SectionKey: "code-and-coverage-analysis", - Usage: `Write a coverage profile to the file after all tests have passed. Sets -cover.`}, + Usage: `Write a coverage profile to the file after all tests have passed. Sets -cover. Must be passed a filename, not a path. Use output-dir to control the location of the output.`}, {KeyPath: "Go.BlockProfile", Name: "blockprofile", UsageArgument: "file", SectionKey: "performance-analysis", Usage: `Write a goroutine blocking profile to the specified file when all tests are complete. Preserves test binary.`}, {KeyPath: "Go.BlockProfileRate", Name: "blockprofilerate", UsageArgument: "rate", SectionKey: "performance-analysis", @@ -600,6 +608,22 @@ func VetAndInitializeCLIAndGoConfig(cliConfig CLIConfig, goFlagsConfig GoFlagsCo errors = append(errors, GinkgoErrors.BothRepeatAndUntilItFails()) } + if strings.ContainsRune(goFlagsConfig.CoverProfile, os.PathSeparator) { + errors = append(errors, GinkgoErrors.ExpectFilenameNotPath("--coverprofile", goFlagsConfig.CoverProfile)) + } + if strings.ContainsRune(goFlagsConfig.CPUProfile, os.PathSeparator) { + errors = append(errors, GinkgoErrors.ExpectFilenameNotPath("--cpuprofile", goFlagsConfig.CPUProfile)) + } + if strings.ContainsRune(goFlagsConfig.MemProfile, os.PathSeparator) { + errors = append(errors, GinkgoErrors.ExpectFilenameNotPath("--memprofile", goFlagsConfig.MemProfile)) + } + if strings.ContainsRune(goFlagsConfig.BlockProfile, os.PathSeparator) { + errors = append(errors, GinkgoErrors.ExpectFilenameNotPath("--blockprofile", goFlagsConfig.BlockProfile)) + } + if strings.ContainsRune(goFlagsConfig.MutexProfile, os.PathSeparator) { + errors = append(errors, GinkgoErrors.ExpectFilenameNotPath("--mutexprofile", goFlagsConfig.MutexProfile)) + } + //initialize the output directory if cliConfig.OutputDir != "" { err := os.MkdirAll(cliConfig.OutputDir, 0777) @@ -620,7 +644,7 @@ func VetAndInitializeCLIAndGoConfig(cliConfig CLIConfig, goFlagsConfig GoFlagsCo } // GenerateGoTestCompileArgs is used by the Ginkgo CLI to generate command line arguments to pass to the go test -c command when compiling the test -func GenerateGoTestCompileArgs(goFlagsConfig GoFlagsConfig, packageToBuild string, pathToInvocationPath string) ([]string, error) { +func GenerateGoTestCompileArgs(goFlagsConfig GoFlagsConfig, packageToBuild string, pathToInvocationPath string, preserveSymbols bool) ([]string, error) { // if the user has set the CoverProfile run-time flag make sure to set the build-time cover flag to make sure // the built test binary can generate a coverprofile if goFlagsConfig.CoverProfile != "" { @@ -643,10 +667,14 @@ func GenerateGoTestCompileArgs(goFlagsConfig GoFlagsConfig, packageToBuild strin goFlagsConfig.CoverPkg = strings.Join(adjustedCoverPkgs, ",") } + if !goFlagsConfig.NeedsSymbols() && goFlagsConfig.LDFlags == "" && !preserveSymbols { + goFlagsConfig.LDFlags = "-w -s" + } + args := []string{"test", "-c", packageToBuild} goArgs, err := GenerateFlagArgs( GoBuildFlags, - map[string]interface{}{ + map[string]any{ "Go": &goFlagsConfig, }, ) @@ -665,7 +693,7 @@ func GenerateGinkgoTestRunArgs(suiteConfig SuiteConfig, reporterConfig ReporterC flags = flags.CopyAppend(ParallelConfigFlags.WithPrefix("ginkgo")...) flags = flags.CopyAppend(ReporterConfigFlags.WithPrefix("ginkgo")...) flags = flags.CopyAppend(GoRunFlags.WithPrefix("test")...) - bindings := map[string]interface{}{ + bindings := map[string]any{ "S": &suiteConfig, "R": &reporterConfig, "Go": &goFlagsConfig, @@ -677,7 +705,7 @@ func GenerateGinkgoTestRunArgs(suiteConfig SuiteConfig, reporterConfig ReporterC // GenerateGoTestRunArgs is used by the Ginkgo CLI to generate command line arguments to pass to the compiled non-Ginkgo test binary func GenerateGoTestRunArgs(goFlagsConfig GoFlagsConfig) ([]string, error) { flags := GoRunFlags.WithPrefix("test") - bindings := map[string]interface{}{ + bindings := map[string]any{ "Go": &goFlagsConfig, } @@ -699,7 +727,7 @@ func BuildRunCommandFlagSet(suiteConfig *SuiteConfig, reporterConfig *ReporterCo flags = flags.CopyAppend(GoBuildFlags...) flags = flags.CopyAppend(GoRunFlags...) - bindings := map[string]interface{}{ + bindings := map[string]any{ "S": suiteConfig, "R": reporterConfig, "C": cliConfig, @@ -720,7 +748,7 @@ func BuildWatchCommandFlagSet(suiteConfig *SuiteConfig, reporterConfig *Reporter flags = flags.CopyAppend(GoBuildFlags...) flags = flags.CopyAppend(GoRunFlags...) - bindings := map[string]interface{}{ + bindings := map[string]any{ "S": suiteConfig, "R": reporterConfig, "C": cliConfig, @@ -736,7 +764,7 @@ func BuildBuildCommandFlagSet(cliConfig *CLIConfig, goFlagsConfig *GoFlagsConfig flags := GinkgoCLISharedFlags flags = flags.CopyAppend(GoBuildFlags...) - bindings := map[string]interface{}{ + bindings := map[string]any{ "C": cliConfig, "Go": goFlagsConfig, "D": &deprecatedConfig{}, @@ -760,7 +788,7 @@ func BuildBuildCommandFlagSet(cliConfig *CLIConfig, goFlagsConfig *GoFlagsConfig func BuildLabelsCommandFlagSet(cliConfig *CLIConfig) (GinkgoFlagSet, error) { flags := GinkgoCLISharedFlags.SubsetWithNames("r", "skip-package") - bindings := map[string]interface{}{ + bindings := map[string]any{ "C": cliConfig, } diff --git a/vendor/github.com/onsi/ginkgo/v2/types/deprecated_types.go b/vendor/github.com/onsi/ginkgo/v2/types/deprecated_types.go index 17922304b..518989a84 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/deprecated_types.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/deprecated_types.go @@ -113,7 +113,7 @@ type DeprecatedSpecFailure struct { type DeprecatedSpecMeasurement struct { Name string - Info interface{} + Info any Order int Results []float64 diff --git a/vendor/github.com/onsi/ginkgo/v2/types/errors.go b/vendor/github.com/onsi/ginkgo/v2/types/errors.go index 6bb72d00c..c3f562f77 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/errors.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/errors.go @@ -88,7 +88,7 @@ body of a {{bold}}Describe{{/}}, {{bold}}Context{{/}}, or {{bold}}When{{/}}.`, n } } -func (g ginkgoErrors) CaughtPanicDuringABuildPhase(caughtPanic interface{}, cl CodeLocation) error { +func (g ginkgoErrors) CaughtPanicDuringABuildPhase(caughtPanic any, cl CodeLocation) error { return GinkgoError{ Heading: "Assertion or Panic detected during tree construction", Message: formatter.F( @@ -189,7 +189,7 @@ func (g ginkgoErrors) InvalidDeclarationOfFlakeAttemptsAndMustPassRepeatedly(cl } } -func (g ginkgoErrors) UnknownDecorator(cl CodeLocation, nodeType NodeType, decorator interface{}) error { +func (g ginkgoErrors) UnknownDecorator(cl CodeLocation, nodeType NodeType, decorator any) error { return GinkgoError{ Heading: "Unknown Decorator", Message: formatter.F(`[%s] node was passed an unknown decorator: '%#v'`, nodeType, decorator), @@ -345,7 +345,7 @@ func (g ginkgoErrors) PushingCleanupInCleanupNode(cl CodeLocation) error { } /* ReportEntry errors */ -func (g ginkgoErrors) TooManyReportEntryValues(cl CodeLocation, arg interface{}) error { +func (g ginkgoErrors) TooManyReportEntryValues(cl CodeLocation, arg any) error { return GinkgoError{ Heading: "Too Many ReportEntry Values", Message: formatter.F(`{{bold}}AddGinkgoReport{{/}} can only be given one value. Got unexpected value: %#v`, arg), @@ -539,7 +539,7 @@ func (g ginkgoErrors) SynchronizedBeforeSuiteDisappearedOnProc1() error { /* Configuration errors */ -func (g ginkgoErrors) UnknownTypePassedToRunSpecs(value interface{}) error { +func (g ginkgoErrors) UnknownTypePassedToRunSpecs(value any) error { return GinkgoError{ Heading: "Unknown Type passed to RunSpecs", Message: fmt.Sprintf("RunSpecs() accepts labels, and configuration of type types.SuiteConfig and/or types.ReporterConfig.\n You passed in: %v", value), @@ -629,6 +629,20 @@ func (g ginkgoErrors) BothRepeatAndUntilItFails() error { } } +func (g ginkgoErrors) ExpectFilenameNotPath(flag string, path string) error { + return GinkgoError{ + Heading: fmt.Sprintf("%s expects a filename but was given a path: %s", flag, path), + Message: fmt.Sprintf("%s takes a filename, not a path. Use --output-dir to specify a directory to collect all test outputs.", flag), + } +} + +func (g ginkgoErrors) FlagAfterPositionalParameter() error { + return GinkgoError{ + Heading: "Malformed arguments - detected a flag after the package liste", + Message: "Make sure all flags appear {{bold}}after{{/}} the Ginkgo subcommand and {{bold}}before{{/}} your list of packages (or './...').\n{{gray}}e.g. 'ginkgo run -p my_package' is valid but `ginkgo -p run my_package` is not.\n{{gray}}e.g. 'ginkgo -p -vet ./...' is valid but 'ginkgo -p ./... -vet' is not{{/}}", + } +} + /* Stack-Trace parsing errors */ func (g ginkgoErrors) FailedToParseStackTrace(message string) error { diff --git a/vendor/github.com/onsi/ginkgo/v2/types/flags.go b/vendor/github.com/onsi/ginkgo/v2/types/flags.go index de69f3022..8409653f9 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/flags.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/flags.go @@ -92,7 +92,7 @@ func (gfs GinkgoFlagSections) Lookup(key string) (GinkgoFlagSection, bool) { type GinkgoFlagSet struct { flags GinkgoFlags - bindings interface{} + bindings any sections GinkgoFlagSections extraGoFlagsSection GinkgoFlagSection @@ -101,7 +101,7 @@ type GinkgoFlagSet struct { } // Call NewGinkgoFlagSet to create GinkgoFlagSet that creates and binds to it's own *flag.FlagSet -func NewGinkgoFlagSet(flags GinkgoFlags, bindings interface{}, sections GinkgoFlagSections) (GinkgoFlagSet, error) { +func NewGinkgoFlagSet(flags GinkgoFlags, bindings any, sections GinkgoFlagSections) (GinkgoFlagSet, error) { return bindFlagSet(GinkgoFlagSet{ flags: flags, bindings: bindings, @@ -110,7 +110,7 @@ func NewGinkgoFlagSet(flags GinkgoFlags, bindings interface{}, sections GinkgoFl } // Call NewGinkgoFlagSet to create GinkgoFlagSet that extends an existing *flag.FlagSet -func NewAttachedGinkgoFlagSet(flagSet *flag.FlagSet, flags GinkgoFlags, bindings interface{}, sections GinkgoFlagSections, extraGoFlagsSection GinkgoFlagSection) (GinkgoFlagSet, error) { +func NewAttachedGinkgoFlagSet(flagSet *flag.FlagSet, flags GinkgoFlags, bindings any, sections GinkgoFlagSections, extraGoFlagsSection GinkgoFlagSection) (GinkgoFlagSet, error) { return bindFlagSet(GinkgoFlagSet{ flags: flags, bindings: bindings, @@ -335,7 +335,7 @@ func (f GinkgoFlagSet) substituteUsage() { fmt.Fprintln(f.flagSet.Output(), f.Usage()) } -func valueAtKeyPath(root interface{}, keyPath string) (reflect.Value, bool) { +func valueAtKeyPath(root any, keyPath string) (reflect.Value, bool) { if len(keyPath) == 0 { return reflect.Value{}, false } @@ -433,7 +433,7 @@ func (ssv stringSliceVar) Set(s string) error { } // given a set of GinkgoFlags and bindings, generate flag arguments suitable to be passed to an application with that set of flags configured. -func GenerateFlagArgs(flags GinkgoFlags, bindings interface{}) ([]string, error) { +func GenerateFlagArgs(flags GinkgoFlags, bindings any) ([]string, error) { result := []string{} for _, flag := range flags { name := flag.ExportAs diff --git a/vendor/github.com/onsi/ginkgo/v2/types/label_filter.go b/vendor/github.com/onsi/ginkgo/v2/types/label_filter.go index 7fdc8aa23..40a909b6d 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/label_filter.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/label_filter.go @@ -343,7 +343,7 @@ func tokenize(input string) func() (*treeNode, error) { consumeUntil := func(cutset string) (string, int) { j := i for ; j < len(runes); j++ { - if strings.IndexRune(cutset, runes[j]) >= 0 { + if strings.ContainsRune(cutset, runes[j]) { break } } diff --git a/vendor/github.com/onsi/ginkgo/v2/types/report_entry.go b/vendor/github.com/onsi/ginkgo/v2/types/report_entry.go index 7b1524b52..63f7a9f6d 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/report_entry.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/report_entry.go @@ -9,18 +9,18 @@ import ( // ReportEntryValue wraps a report entry's value ensuring it can be encoded and decoded safely into reports // and across the network connection when running in parallel type ReportEntryValue struct { - raw interface{} //unexported to prevent gob from freaking out about unregistered structs + raw any //unexported to prevent gob from freaking out about unregistered structs AsJSON string Representation string } -func WrapEntryValue(value interface{}) ReportEntryValue { +func WrapEntryValue(value any) ReportEntryValue { return ReportEntryValue{ raw: value, } } -func (rev ReportEntryValue) GetRawValue() interface{} { +func (rev ReportEntryValue) GetRawValue() any { return rev.raw } @@ -118,7 +118,7 @@ func (entry ReportEntry) StringRepresentation() string { // If used from a rehydrated JSON file _or_ in a ReportAfterSuite when running in parallel this will be // a JSON-decoded {}interface. If you want to reconstitute your original object you can decode the entry.Value.AsJSON // field yourself. -func (entry ReportEntry) GetRawValue() interface{} { +func (entry ReportEntry) GetRawValue() any { return entry.Value.GetRawValue() } diff --git a/vendor/github.com/onsi/ginkgo/v2/types/version.go b/vendor/github.com/onsi/ginkgo/v2/types/version.go index 0b51c0b56..cfbba0d90 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/version.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/version.go @@ -1,3 +1,3 @@ package types -const VERSION = "2.22.0" +const VERSION = "2.23.3" diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md index 79c3f6199..890d89222 100644 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ b/vendor/github.com/onsi/gomega/CHANGELOG.md @@ -1,3 +1,32 @@ +## 1.37.0 + +### Features +- add To/ToNot/NotTo aliases for AsyncAssertion [5666f98] + +## 1.36.3 + +### Maintenance + +- bump all the things [adb8b49] +- chore: replace `interface{}` with `any` [7613216] +- Bump google.golang.org/protobuf from 1.36.1 to 1.36.5 (#822) [9fe5259] +- remove spurious "toolchain" from go.mod (#819) [a0e85b9] +- Bump golang.org/x/net from 0.33.0 to 0.35.0 (#823) [604a8b1] +- Bump activesupport from 6.0.6.1 to 6.1.7.5 in /docs (#772) [36fbc84] +- Bump github-pages from 231 to 232 in /docs (#778) [ced70d7] +- Bump rexml from 3.2.6 to 3.3.9 in /docs (#788) [c8b4a07] +- Bump github.com/onsi/ginkgo/v2 from 2.22.1 to 2.22.2 (#812) [06431b9] +- Bump webrick from 1.8.1 to 1.9.1 in /docs (#800) [b55a92d] +- Fix typos (#813) [a1d518b] + +## 1.36.2 + +### Maintenance +- Bump google.golang.org/protobuf from 1.35.1 to 1.36.1 (#810) [9a7609d] +- Bump golang.org/x/net from 0.30.0 to 0.33.0 (#807) [b6cb028] +- Bump github.com/onsi/ginkgo/v2 from 2.20.1 to 2.22.1 (#808) [5756529] +- Bump nokogiri from 1.16.3 to 1.16.5 in /docs (#757) [dabc12e] + ## 1.36.1 ### Fixes @@ -314,7 +343,7 @@ Require Go 1.22+ ### Features -Introducting [gcustom](https://onsi.github.io/gomega/#gcustom-a-convenient-mechanism-for-buildling-custom-matchers) - a convenient mechanism for building custom matchers. +Introducing [gcustom](https://onsi.github.io/gomega/#gcustom-a-convenient-mechanism-for-buildling-custom-matchers) - a convenient mechanism for building custom matchers. This is an RC release for `gcustom`. The external API may be tweaked in response to feedback however it is expected to remain mostly stable. @@ -453,7 +482,7 @@ These improvements are all documented in [Gomega's docs](https://onsi.github.io/ - Fix max number of samples in experiments on non-64-bit systems. (#528) [1c84497] - Remove dependency on ginkgo v1.16.4 (#530) [4dea8d5] - Fix for Go 1.18 (#532) [56d2a29] -- Document precendence of timeouts (#533) [b607941] +- Document precedence of timeouts (#533) [b607941] ## 1.18.1 @@ -470,7 +499,7 @@ These improvements are all documented in [Gomega's docs](https://onsi.github.io/ ## Fixes - Gomega now uses ioutil for Go 1.15 and lower (#492) - official support is only for the most recent two major versions of Go but this will unblock users who need to stay on older unsupported versions of Go. [c29c1c0] -## Maintenace +## Maintenance - Remove Travis workflow (#491) [72e6040] - Upgrade to Ginkgo 2.0.0 GA [f383637] - chore: fix description of HaveField matcher (#487) [2b4b2c0] @@ -718,7 +747,7 @@ Improvements: - Added `BeSent` which attempts to send a value down a channel and fails if the attempt blocks. Can be paired with `Eventually` to safely send a value down a channel with a timeout. - `Ω`, `Expect`, `Eventually`, and `Consistently` now immediately `panic` if there is no registered fail handler. This is always a mistake that can hide failing tests. -- `Receive()` no longer errors when passed a closed channel, it's perfectly fine to attempt to read from a closed channel so Ω(c).Should(Receive()) always fails and Ω(c).ShoudlNot(Receive()) always passes with a closed channel. +- `Receive()` no longer errors when passed a closed channel, it's perfectly fine to attempt to read from a closed channel so Ω(c).Should(Receive()) always fails and Ω(c).ShouldNot(Receive()) always passes with a closed channel. - Added `HavePrefix` and `HaveSuffix` matchers. - `ghttp` can now handle concurrent requests. - Added `Succeed` which allows one to write `Ω(MyFunction()).Should(Succeed())`. @@ -728,7 +757,7 @@ Improvements: - `ghttp` servers can take an `io.Writer`. `ghttp` will write a line to the writer when each request arrives. - Added `WithTransform` matcher to allow munging input data before feeding into the relevant matcher - Added boolean `And`, `Or`, and `Not` matchers to allow creating composite matchers -- Added `gbytes.TimeoutCloser`, `gbytes.TimeoutReader`, and `gbytes.TimeoutWriter` - these are convenience wrappers that timeout if the underlying Closer/Reader/Writer does not return within the alloted time. +- Added `gbytes.TimeoutCloser`, `gbytes.TimeoutReader`, and `gbytes.TimeoutWriter` - these are convenience wrappers that timeout if the underlying Closer/Reader/Writer does not return within the allotted time. - Added `gbytes.BufferReader` - this constructs a `gbytes.Buffer` that asynchronously reads the passed-in `io.Reader` into its buffer. Bug Fixes: @@ -773,7 +802,7 @@ New Matchers: Updated Matchers: -- `Receive` matcher can take a matcher as an argument and passes only if the channel under test receives an objet that satisfies the passed-in matcher. +- `Receive` matcher can take a matcher as an argument and passes only if the channel under test receives an object that satisfies the passed-in matcher. - Matchers that implement `MatchMayChangeInTheFuture(actual interface{}) bool` can inform `Eventually` and/or `Consistently` when a match has no chance of changing status in the future. For example, `Receive` returns `false` when a channel is closed. Misc: diff --git a/vendor/github.com/onsi/gomega/format/format.go b/vendor/github.com/onsi/gomega/format/format.go index 6c1680638..96f04b210 100644 --- a/vendor/github.com/onsi/gomega/format/format.go +++ b/vendor/github.com/onsi/gomega/format/format.go @@ -57,7 +57,7 @@ var Indent = " " var longFormThreshold = 20 -// GomegaStringer allows for custom formating of objects for gomega. +// GomegaStringer allows for custom formatting of objects for gomega. type GomegaStringer interface { // GomegaString will be used to custom format an object. // It does not follow UseStringerRepresentation value and will always be called regardless. @@ -73,7 +73,7 @@ If the CustomFormatter does not want to handle the object it should return ("", Strings returned by CustomFormatters are not truncated */ -type CustomFormatter func(value interface{}) (string, bool) +type CustomFormatter func(value any) (string, bool) type CustomFormatterKey uint var customFormatterKey CustomFormatterKey = 1 @@ -125,7 +125,7 @@ If expected is omitted, then the message looks like: */ -func Message(actual interface{}, message string, expected ...interface{}) string { +func Message(actual any, message string, expected ...any) string { if len(expected) == 0 { return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) } @@ -255,7 +255,7 @@ recursing into the object. Set PrintContextObjects to true to print the content of objects implementing context.Context */ -func Object(object interface{}, indentation uint) string { +func Object(object any, indentation uint) string { indent := strings.Repeat(Indent, int(indentation)) value := reflect.ValueOf(object) commonRepresentation := "" @@ -392,7 +392,7 @@ func formatValue(value reflect.Value, indentation uint) string { } } -func formatString(object interface{}, indentation uint) string { +func formatString(object any, indentation uint) string { if indentation == 1 { s := fmt.Sprintf("%s", object) components := strings.Split(s, "\n") diff --git a/vendor/github.com/onsi/gomega/gcustom/make_matcher.go b/vendor/github.com/onsi/gomega/gcustom/make_matcher.go index 5372fa441..ca556ceb0 100644 --- a/vendor/github.com/onsi/gomega/gcustom/make_matcher.go +++ b/vendor/github.com/onsi/gomega/gcustom/make_matcher.go @@ -12,7 +12,7 @@ import ( "github.com/onsi/gomega/format" ) -var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() +var interfaceType = reflect.TypeOf((*any)(nil)).Elem() var errInterface = reflect.TypeOf((*error)(nil)).Elem() var defaultTemplate = template.Must(ParseTemplate("{{if .Failure}}Custom matcher failed for:{{else}}Custom matcher succeeded (but was expected to fail) for:{{end}}\n{{.FormattedActual}}")) @@ -191,7 +191,7 @@ func (c CustomGomegaMatcher) WithTemplate(templ string, data ...any) CustomGomeg /* WithPrecompiledTemplate returns a CustomGomegaMatcher configured to use the passed-in template. The template should be precompiled with gcustom.ParseTemplate(). -As with WithTemplate() you can provide a single pice of additional data as an optional argument. This is accessed in the template via {{.Data}} +As with WithTemplate() you can provide a single piece of additional data as an optional argument. This is accessed in the template via {{.Data}} */ func (c CustomGomegaMatcher) WithPrecompiledTemplate(templ *template.Template, data ...any) CustomGomegaMatcher { c.templateMessage = templ diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go index c6ac499f7..a491a64be 100644 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ b/vendor/github.com/onsi/gomega/gomega_dsl.go @@ -22,7 +22,7 @@ import ( "github.com/onsi/gomega/types" ) -const GOMEGA_VERSION = "1.36.1" +const GOMEGA_VERSION = "1.37.0" const nilGomegaPanic = `You are trying to make an assertion, but haven't registered Gomega's fail handler. If you're using Ginkgo then you probably forgot to put your assertion in an It(). @@ -191,7 +191,7 @@ func ensureDefaultGomegaIsConfigured() { // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Ω and Expect are identical -func Ω(actual interface{}, extra ...interface{}) Assertion { +func Ω(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Ω(actual, extra...) } @@ -217,7 +217,7 @@ func Ω(actual interface{}, extra ...interface{}) Assertion { // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Expect and Ω are identical -func Expect(actual interface{}, extra ...interface{}) Assertion { +func Expect(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Expect(actual, extra...) } @@ -233,7 +233,7 @@ func Expect(actual interface{}, extra ...interface{}) Assertion { // This is most useful in helper functions that make assertions. If you want Gomega's // error message to refer to the calling line in the test (as opposed to the line in the helper function) // set the first argument of `ExpectWithOffset` appropriately. -func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion { +func ExpectWithOffset(offset int, actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.ExpectWithOffset(offset, actual, extra...) } @@ -319,19 +319,19 @@ you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) -Either way the context pasesd to Eventually is also passed to the underlying function. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. +Either way the context passed to Eventually is also passed to the underlying function. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. By default, when a context is passed to Eventually *without* an explicit timeout, Gomega will rely solely on the context's cancellation to determine when to stop polling. If you want to specify a timeout in addition to the context you can do so using the .WithTimeout() method. For example: Eventually(client.FetchCount).WithContext(ctx).WithTimeout(10*time.Second).Should(BeNumerically(">=", 17)) -now either the context cacnellation or the timeout will cause Eventually to stop polling. +now either the context cancellation or the timeout will cause Eventually to stop polling. If, instead, you would like to opt out of this behavior and have Gomega's default timeouts govern Eventuallys that take a context you can call: EnforceDefaultTimeoutsWhenUsingContexts() -in the DSL (or on a Gomega instance). Now all calls to Eventually that take a context will fail if eitehr the context is cancelled or the default timeout elapses. +in the DSL (or on a Gomega instance). Now all calls to Eventually that take a context will fail if either the context is cancelled or the default timeout elapses. **Category 3: Making assertions _in_ the function passed into Eventually** @@ -390,7 +390,7 @@ is equivalent to Eventually(...).WithTimeout(10*time.Second).WithPolling(2*time.Second).WithContext(ctx).Should(...) */ -func Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func Eventually(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Eventually(actualOrCtx, args...) } @@ -404,7 +404,7 @@ func Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { // `EventuallyWithOffset` specifying a timeout interval (and an optional polling interval) are // the same as `Eventually(...).WithOffset(...).WithTimeout` or // `Eventually(...).WithOffset(...).WithTimeout(...).WithPolling`. -func EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.EventuallyWithOffset(offset, actualOrCtx, args...) } @@ -424,7 +424,7 @@ Consistently is useful in cases where you want to assert that something *does no This will block for 200 milliseconds and repeatedly check the channel and ensure nothing has been received. */ -func Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func Consistently(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Consistently(actualOrCtx, args...) } @@ -435,13 +435,13 @@ func Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion { // // `ConsistentlyWithOffset` is the same as `Consistently(...).WithOffset` and // optional `WithTimeout` and `WithPolling`. -func ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion { +func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.ConsistentlyWithOffset(offset, actualOrCtx, args...) } /* -StopTrying can be used to signal to Eventually and Consistentlythat they should abort and stop trying. This always results in a failure of the assertion - and the failure message is the content of the StopTrying signal. +StopTrying can be used to signal to Eventually and Consistently that they should abort and stop trying. This always results in a failure of the assertion - and the failure message is the content of the StopTrying signal. You can send the StopTrying signal by either returning StopTrying("message") as an error from your passed-in function _or_ by calling StopTrying("message").Now() to trigger a panic and end execution. diff --git a/vendor/github.com/onsi/gomega/internal/assertion.go b/vendor/github.com/onsi/gomega/internal/assertion.go index 08356a610..cc846e7ce 100644 --- a/vendor/github.com/onsi/gomega/internal/assertion.go +++ b/vendor/github.com/onsi/gomega/internal/assertion.go @@ -9,19 +9,19 @@ import ( ) type Assertion struct { - actuals []interface{} // actual value plus all extra values - actualIndex int // value to pass to the matcher - vet vetinari // the vet to call before calling Gomega matcher + actuals []any // actual value plus all extra values + actualIndex int // value to pass to the matcher + vet vetinari // the vet to call before calling Gomega matcher offset int g *Gomega } // ...obligatory discworld reference, as "vetineer" doesn't sound ... quite right. -type vetinari func(assertion *Assertion, optionalDescription ...interface{}) bool +type vetinari func(assertion *Assertion, optionalDescription ...any) bool -func NewAssertion(actualInput interface{}, g *Gomega, offset int, extra ...interface{}) *Assertion { +func NewAssertion(actualInput any, g *Gomega, offset int, extra ...any) *Assertion { return &Assertion{ - actuals: append([]interface{}{actualInput}, extra...), + actuals: append([]any{actualInput}, extra...), actualIndex: 0, vet: (*Assertion).vetActuals, offset: offset, @@ -44,37 +44,37 @@ func (assertion *Assertion) Error() types.Assertion { } } -func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } -func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } -func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } -func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) string { +func (assertion *Assertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" @@ -86,7 +86,7 @@ func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } -func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { +func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { actualInput := assertion.actuals[assertion.actualIndex] matches, err := matcher.Match(actualInput) assertion.g.THelper() @@ -113,7 +113,7 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool // vetActuals vets the actual values, with the (optional) exception of a // specific value, such as the first value in case non-error assertions, or the // last value in case of Error()-based assertions. -func (assertion *Assertion) vetActuals(optionalDescription ...interface{}) bool { +func (assertion *Assertion) vetActuals(optionalDescription ...any) bool { success, message := vetActuals(assertion.actuals, assertion.actualIndex) if success { return true @@ -129,7 +129,7 @@ func (assertion *Assertion) vetActuals(optionalDescription ...interface{}) bool // the final error value is non-zero. Otherwise, it doesn't vet the actual // values, as these are allowed to take on any values unless there is a non-zero // error value. -func (assertion *Assertion) vetError(optionalDescription ...interface{}) bool { +func (assertion *Assertion) vetError(optionalDescription ...any) bool { if err := assertion.actuals[assertion.actualIndex]; err != nil { // Go error result idiom: all other actual values must be zero values. return assertion.vetActuals(optionalDescription...) @@ -139,7 +139,7 @@ func (assertion *Assertion) vetError(optionalDescription ...interface{}) bool { // vetActuals vets a slice of actual values, optionally skipping a particular // value slice element, such as the first or last value slice element. -func vetActuals(actuals []interface{}, skipIndex int) (bool, string) { +func vetActuals(actuals []any, skipIndex int) (bool, string) { for i, actual := range actuals { if i == skipIndex { continue diff --git a/vendor/github.com/onsi/gomega/internal/async_assertion.go b/vendor/github.com/onsi/gomega/internal/async_assertion.go index 8b4cd1f5b..a3a646e4a 100644 --- a/vendor/github.com/onsi/gomega/internal/async_assertion.go +++ b/vendor/github.com/onsi/gomega/internal/async_assertion.go @@ -69,8 +69,8 @@ type AsyncAssertion struct { asyncType AsyncAssertionType actualIsFunc bool - actual interface{} - argsToForward []interface{} + actual any + argsToForward []any timeoutInterval time.Duration pollingInterval time.Duration @@ -80,7 +80,7 @@ type AsyncAssertion struct { g *Gomega } -func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput interface{}, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, mustPassRepeatedly int, ctx context.Context, offset int) *AsyncAssertion { +func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput any, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, mustPassRepeatedly int, ctx context.Context, offset int) *AsyncAssertion { out := &AsyncAssertion{ asyncType: asyncType, timeoutInterval: timeoutInterval, @@ -129,7 +129,7 @@ func (assertion *AsyncAssertion) WithContext(ctx context.Context) types.AsyncAss return assertion } -func (assertion *AsyncAssertion) WithArguments(argsToForward ...interface{}) types.AsyncAssertion { +func (assertion *AsyncAssertion) WithArguments(argsToForward ...any) types.AsyncAssertion { assertion.argsToForward = argsToForward return assertion } @@ -139,19 +139,31 @@ func (assertion *AsyncAssertion) MustPassRepeatedly(count int) types.AsyncAssert return assertion } -func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, true, optionalDescription...) } -func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { + return assertion.Should(matcher, optionalDescription...) +} + +func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, false, optionalDescription...) } -func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interface{}) string { +func (assertion *AsyncAssertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { + return assertion.ShouldNot(matcher, optionalDescription...) +} + +func (assertion *AsyncAssertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { + return assertion.ShouldNot(matcher, optionalDescription...) +} + +func (assertion *AsyncAssertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" @@ -163,7 +175,7 @@ func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interfa return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } -func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (interface{}, error) { +func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (any, error) { if len(values) == 0 { return nil, &asyncPolledActualError{ message: fmt.Sprintf("The function passed to %s did not return any values", assertion.asyncType), @@ -224,7 +236,7 @@ func (assertion *AsyncAssertion) argumentMismatchError(t reflect.Type, numProvid if numProvided == 1 { have = "has" } - return fmt.Errorf(`The function passed to %s has signature %s takes %d arguments but %d %s been provided. Please use %s().WithArguments() to pass the corect set of arguments. + return fmt.Errorf(`The function passed to %s has signature %s takes %d arguments but %d %s been provided. Please use %s().WithArguments() to pass the correct set of arguments. You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, t, t.NumIn(), numProvided, have, assertion.asyncType) @@ -237,9 +249,9 @@ You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, reason) } -func (assertion *AsyncAssertion) buildActualPoller() (func() (interface{}, error), error) { +func (assertion *AsyncAssertion) buildActualPoller() (func() (any, error), error) { if !assertion.actualIsFunc { - return func() (interface{}, error) { return assertion.actual, nil }, nil + return func() (any, error) { return assertion.actual, nil }, nil } actualValue := reflect.ValueOf(assertion.actual) actualType := reflect.TypeOf(assertion.actual) @@ -301,7 +313,7 @@ func (assertion *AsyncAssertion) buildActualPoller() (func() (interface{}, error return nil, assertion.invalidMustPassRepeatedlyError("parameter can't be < 1") } - return func() (actual interface{}, err error) { + return func() (actual any, err error) { var values []reflect.Value assertionFailure = nil defer func() { @@ -354,14 +366,14 @@ func (assertion *AsyncAssertion) afterPolling() <-chan time.Time { } } -func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value interface{}) bool { +func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value any) bool { if assertion.actualIsFunc || types.MatchMayChangeInTheFuture(matcher, value) { return false } return true } -func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value interface{}) (matches bool, err error) { +func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value any) (matches bool, err error) { defer func() { if e := recover(); e != nil { if _, isAsyncError := AsPollingSignalError(e); isAsyncError { @@ -377,13 +389,13 @@ func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value return } -func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { +func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { timer := time.Now() timeout := assertion.afterTimeout() lock := sync.Mutex{} var matches, hasLastValidActual bool - var actual, lastValidActual interface{} + var actual, lastValidActual any var actualErr, matcherErr error var oracleMatcherSaysStop bool diff --git a/vendor/github.com/onsi/gomega/internal/duration_bundle.go b/vendor/github.com/onsi/gomega/internal/duration_bundle.go index 2e026c336..1019deb88 100644 --- a/vendor/github.com/onsi/gomega/internal/duration_bundle.go +++ b/vendor/github.com/onsi/gomega/internal/duration_bundle.go @@ -49,7 +49,7 @@ func durationFromEnv(key string, defaultDuration time.Duration) time.Duration { return duration } -func toDuration(input interface{}) (time.Duration, error) { +func toDuration(input any) (time.Duration, error) { duration, ok := input.(time.Duration) if ok { return duration, nil diff --git a/vendor/github.com/onsi/gomega/internal/gomega.go b/vendor/github.com/onsi/gomega/internal/gomega.go index c6e2fcc0e..66dfe7d04 100644 --- a/vendor/github.com/onsi/gomega/internal/gomega.go +++ b/vendor/github.com/onsi/gomega/internal/gomega.go @@ -40,45 +40,45 @@ func (g *Gomega) ConfigureWithT(t types.GomegaTestingT) *Gomega { return g } -func (g *Gomega) Ω(actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) Ω(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } -func (g *Gomega) Expect(actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) Expect(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } -func (g *Gomega) ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) types.Assertion { +func (g *Gomega) ExpectWithOffset(offset int, actual any, extra ...any) types.Assertion { return NewAssertion(actual, g, offset, extra...) } -func (g *Gomega) Eventually(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) Eventually(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, 0, actualOrCtx, args...) } -func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, offset, actualOrCtx, args...) } -func (g *Gomega) Consistently(actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) Consistently(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, 0, actualOrCtx, args...) } -func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, offset, actualOrCtx, args...) } -func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx interface{}, args ...interface{}) types.AsyncAssertion { +func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx any, args ...any) types.AsyncAssertion { baseOffset := 3 timeoutInterval := -time.Duration(1) pollingInterval := -time.Duration(1) - intervals := []interface{}{} + intervals := []any{} var ctx context.Context actual := actualOrCtx startingIndex := 0 if _, isCtx := actualOrCtx.(context.Context); isCtx && len(args) > 0 { - // the first argument is a context, we should accept it as the context _only if_ it is **not** the only argumnent **and** the second argument is not a parseable duration + // the first argument is a context, we should accept it as the context _only if_ it is **not** the only argument **and** the second argument is not a parseable duration // this is due to an unfortunate ambiguity in early version of Gomega in which multi-type durations are allowed after the actual if _, err := toDuration(args[0]); err != nil { ctx = actualOrCtx.(context.Context) diff --git a/vendor/github.com/onsi/gomega/internal/polling_signal_error.go b/vendor/github.com/onsi/gomega/internal/polling_signal_error.go index 3a4f7ddd9..450c40333 100644 --- a/vendor/github.com/onsi/gomega/internal/polling_signal_error.go +++ b/vendor/github.com/onsi/gomega/internal/polling_signal_error.go @@ -100,7 +100,7 @@ func (s *PollingSignalErrorImpl) TryAgainDuration() time.Duration { return s.duration } -func AsPollingSignalError(actual interface{}) (*PollingSignalErrorImpl, bool) { +func AsPollingSignalError(actual any) (*PollingSignalErrorImpl, bool) { if actual == nil { return nil, false } diff --git a/vendor/github.com/onsi/gomega/internal/vetoptdesc.go b/vendor/github.com/onsi/gomega/internal/vetoptdesc.go index f29587641..b748de41f 100644 --- a/vendor/github.com/onsi/gomega/internal/vetoptdesc.go +++ b/vendor/github.com/onsi/gomega/internal/vetoptdesc.go @@ -10,7 +10,7 @@ import ( // Gomega matcher at the beginning it panics. This allows for rendering Gomega // matchers as part of an optional Description, as long as they're not in the // first slot. -func vetOptionalDescription(assertion string, optionalDescription ...interface{}) { +func vetOptionalDescription(assertion string, optionalDescription ...any) { if len(optionalDescription) == 0 { return } diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go index 7ef27dc9c..10b6693fd 100644 --- a/vendor/github.com/onsi/gomega/matchers.go +++ b/vendor/github.com/onsi/gomega/matchers.go @@ -12,7 +12,7 @@ import ( // Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about // types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. -func Equal(expected interface{}) types.GomegaMatcher { +func Equal(expected any) types.GomegaMatcher { return &matchers.EqualMatcher{ Expected: expected, } @@ -22,7 +22,7 @@ func Equal(expected interface{}) types.GomegaMatcher { // This is done by converting actual to have the type of expected before // attempting equality with reflect.DeepEqual. // It is an error for actual and expected to be nil. Use BeNil() instead. -func BeEquivalentTo(expected interface{}) types.GomegaMatcher { +func BeEquivalentTo(expected any) types.GomegaMatcher { return &matchers.BeEquivalentToMatcher{ Expected: expected, } @@ -31,7 +31,7 @@ func BeEquivalentTo(expected interface{}) types.GomegaMatcher { // BeComparableTo uses gocmp.Equal from github.com/google/go-cmp (instead of reflect.DeepEqual) to perform a deep comparison. // You can pass cmp.Option as options. // It is an error for actual and expected to be nil. Use BeNil() instead. -func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatcher { +func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { return &matchers.BeComparableToMatcher{ Expected: expected, Options: opts, @@ -41,7 +41,7 @@ func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatche // BeIdenticalTo uses the == operator to compare actual with expected. // BeIdenticalTo is strict about types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. -func BeIdenticalTo(expected interface{}) types.GomegaMatcher { +func BeIdenticalTo(expected any) types.GomegaMatcher { return &matchers.BeIdenticalToMatcher{ Expected: expected, } @@ -139,7 +139,7 @@ func Succeed() types.GomegaMatcher { // Error interface // // The optional second argument is a description of the error function, if used. This is required when passing a function but is ignored in all other cases. -func MatchError(expected interface{}, functionErrorDescription ...any) types.GomegaMatcher { +func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { return &matchers.MatchErrorMatcher{ Expected: expected, FuncErrDescription: functionErrorDescription, @@ -202,11 +202,11 @@ func BeClosed() types.GomegaMatcher { // Expect(myThing.IsValid()).Should(BeTrue()) // // Finally, if you want to match the received object as well as get the actual received value into a variable, so you can reason further about the value received, -// you can pass a pointer to a variable of the approriate type first, and second a matcher: +// you can pass a pointer to a variable of the appropriate type first, and second a matcher: // // var myThing thing // Eventually(thingChan).Should(Receive(&myThing, ContainSubstring("bar"))) -func Receive(args ...interface{}) types.GomegaMatcher { +func Receive(args ...any) types.GomegaMatcher { return &matchers.ReceiveMatcher{ Args: args, } @@ -224,7 +224,7 @@ func Receive(args ...interface{}) types.GomegaMatcher { // // Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). // Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. -func BeSent(arg interface{}) types.GomegaMatcher { +func BeSent(arg any) types.GomegaMatcher { return &matchers.BeSentMatcher{ Arg: arg, } @@ -233,7 +233,7 @@ func BeSent(arg interface{}) types.GomegaMatcher { // MatchRegexp succeeds if actual is a string or stringer that matches the // passed-in regexp. Optional arguments can be provided to construct a regexp // via fmt.Sprintf(). -func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { +func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { return &matchers.MatchRegexpMatcher{ Regexp: regexp, Args: args, @@ -243,7 +243,7 @@ func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { // ContainSubstring succeeds if actual is a string or stringer that contains the // passed-in substring. Optional arguments can be provided to construct the substring // via fmt.Sprintf(). -func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { +func ContainSubstring(substr string, args ...any) types.GomegaMatcher { return &matchers.ContainSubstringMatcher{ Substr: substr, Args: args, @@ -253,7 +253,7 @@ func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { // HavePrefix succeeds if actual is a string or stringer that contains the // passed-in string as a prefix. Optional arguments can be provided to construct // via fmt.Sprintf(). -func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { +func HavePrefix(prefix string, args ...any) types.GomegaMatcher { return &matchers.HavePrefixMatcher{ Prefix: prefix, Args: args, @@ -263,7 +263,7 @@ func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { // HaveSuffix succeeds if actual is a string or stringer that contains the // passed-in string as a suffix. Optional arguments can be provided to construct // via fmt.Sprintf(). -func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { +func HaveSuffix(suffix string, args ...any) types.GomegaMatcher { return &matchers.HaveSuffixMatcher{ Suffix: suffix, Args: args, @@ -273,7 +273,7 @@ func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { // MatchJSON succeeds if actual is a string or stringer of JSON that matches // the expected JSON. The JSONs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchJSON(json interface{}) types.GomegaMatcher { +func MatchJSON(json any) types.GomegaMatcher { return &matchers.MatchJSONMatcher{ JSONToMatch: json, } @@ -282,7 +282,7 @@ func MatchJSON(json interface{}) types.GomegaMatcher { // MatchXML succeeds if actual is a string or stringer of XML that matches // the expected XML. The XMLs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like whitespaces shouldn't matter. -func MatchXML(xml interface{}) types.GomegaMatcher { +func MatchXML(xml any) types.GomegaMatcher { return &matchers.MatchXMLMatcher{ XMLToMatch: xml, } @@ -291,7 +291,7 @@ func MatchXML(xml interface{}) types.GomegaMatcher { // MatchYAML succeeds if actual is a string or stringer of YAML that matches // the expected YAML. The YAML's are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchYAML(yaml interface{}) types.GomegaMatcher { +func MatchYAML(yaml any) types.GomegaMatcher { return &matchers.MatchYAMLMatcher{ YAMLToMatch: yaml, } @@ -338,7 +338,7 @@ func BeZero() types.GomegaMatcher { // // var findings []string // Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings))) -func ContainElement(element interface{}, result ...interface{}) types.GomegaMatcher { +func ContainElement(element any, result ...any) types.GomegaMatcher { return &matchers.ContainElementMatcher{ Element: element, Result: result, @@ -358,7 +358,7 @@ func ContainElement(element interface{}, result ...interface{}) types.GomegaMatc // Expect(2).Should(BeElementOf(1, 2)) // // Actual must be typed. -func BeElementOf(elements ...interface{}) types.GomegaMatcher { +func BeElementOf(elements ...any) types.GomegaMatcher { return &matchers.BeElementOfMatcher{ Elements: elements, } @@ -368,7 +368,7 @@ func BeElementOf(elements ...interface{}) types.GomegaMatcher { // BeKeyOf() always uses Equal() to perform the match between actual and the map keys. // // Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false})) -func BeKeyOf(element interface{}) types.GomegaMatcher { +func BeKeyOf(element any) types.GomegaMatcher { return &matchers.BeKeyOfMatcher{ Map: element, } @@ -388,14 +388,14 @@ func BeKeyOf(element interface{}) types.GomegaMatcher { // // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) // -// Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule. -func ConsistOf(elements ...interface{}) types.GomegaMatcher { +// Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []any are different types - hence the need for this special rule. +func ConsistOf(elements ...any) types.GomegaMatcher { return &matchers.ConsistOfMatcher{ Elements: elements, } } -// HaveExactElements succeeds if actual contains elements that precisely match the elemets passed into the matcher. The ordering of the elements does matter. +// HaveExactElements succeeds if actual contains elements that precisely match the elements passed into the matcher. The ordering of the elements does matter. // By default HaveExactElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: // // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements("Foo", "FooBar")) @@ -403,7 +403,7 @@ func ConsistOf(elements ...interface{}) types.GomegaMatcher { // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements(ContainSubstring("Foo"), ContainSubstring("Foo"))) // // Actual must be an array or slice. -func HaveExactElements(elements ...interface{}) types.GomegaMatcher { +func HaveExactElements(elements ...any) types.GomegaMatcher { return &matchers.HaveExactElementsMatcher{ Elements: elements, } @@ -417,7 +417,7 @@ func HaveExactElements(elements ...interface{}) types.GomegaMatcher { // // Actual must be an array, slice or map. // For maps, ContainElements searches through the map's values. -func ContainElements(elements ...interface{}) types.GomegaMatcher { +func ContainElements(elements ...any) types.GomegaMatcher { return &matchers.ContainElementsMatcher{ Elements: elements, } @@ -432,7 +432,7 @@ func ContainElements(elements ...interface{}) types.GomegaMatcher { // // Actual must be an array, slice or map. // For maps, HaveEach searches through the map's values. -func HaveEach(element interface{}) types.GomegaMatcher { +func HaveEach(element any) types.GomegaMatcher { return &matchers.HaveEachMatcher{ Element: element, } @@ -443,7 +443,7 @@ func HaveEach(element interface{}) types.GomegaMatcher { // matcher can be passed in instead: // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) -func HaveKey(key interface{}) types.GomegaMatcher { +func HaveKey(key any) types.GomegaMatcher { return &matchers.HaveKeyMatcher{ Key: key, } @@ -455,7 +455,7 @@ func HaveKey(key interface{}) types.GomegaMatcher { // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) -func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { +func HaveKeyWithValue(key any, value any) types.GomegaMatcher { return &matchers.HaveKeyWithValueMatcher{ Key: key, Value: value, @@ -483,7 +483,7 @@ func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { // Expect(book).To(HaveField("Title", ContainSubstring("Les")) // Expect(book).To(HaveField("Author.FirstName", Equal("Victor")) // Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900)) -func HaveField(field string, expected interface{}) types.GomegaMatcher { +func HaveField(field string, expected any) types.GomegaMatcher { return &matchers.HaveFieldMatcher{ Field: field, Expected: expected, @@ -535,7 +535,7 @@ func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { // Expect(1.0).Should(BeNumerically(">=", 1.0)) // Expect(1.0).Should(BeNumerically("<", 3)) // Expect(1.0).Should(BeNumerically("<=", 1.0)) -func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher { +func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { return &matchers.BeNumericallyMatcher{ Comparator: comparator, CompareTo: compareTo, @@ -562,7 +562,7 @@ func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Dura // Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type // Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type // Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) -func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher { +func BeAssignableToTypeOf(expected any) types.GomegaMatcher { return &matchers.AssignableToTypeOfMatcher{ Expected: expected, } @@ -581,7 +581,7 @@ func Panic() types.GomegaMatcher { // matcher can be passed in instead: // // Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`))) -func PanicWith(expected interface{}) types.GomegaMatcher { +func PanicWith(expected any) types.GomegaMatcher { return &matchers.PanicMatcher{Expected: expected} } @@ -610,7 +610,7 @@ func BeADirectory() types.GomegaMatcher { // Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200 // Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found" // Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent)) // asserts that resp.StatusCode == 200 || resp.StatusCode == 204 -func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher { +func HaveHTTPStatus(expected ...any) types.GomegaMatcher { return &matchers.HaveHTTPStatusMatcher{Expected: expected} } @@ -618,7 +618,7 @@ func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher { // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be a string header name, followed by a header value which // can be a string, or another matcher. -func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatcher { +func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher { return &matchers.HaveHTTPHeaderWithValueMatcher{ Header: header, Value: value, @@ -628,7 +628,7 @@ func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatch // HaveHTTPBody matches if the body matches. // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be either a string, []byte, or other matcher -func HaveHTTPBody(expected interface{}) types.GomegaMatcher { +func HaveHTTPBody(expected any) types.GomegaMatcher { return &matchers.HaveHTTPBodyMatcher{Expected: expected} } @@ -687,15 +687,15 @@ func Not(matcher types.GomegaMatcher) types.GomegaMatcher { // Expect(1).To(WithTransform(failingplus1, Equal(2))) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher { +func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { return matchers.NewWithTransformMatcher(transform, matcher) } // Satisfy matches the actual value against the `predicate` function. -// The given predicate must be a function of one paramter that returns bool. +// The given predicate must be a function of one parameter that returns bool. // // var isEven = func(i int) bool { return i%2 == 0 } // Expect(2).To(Satisfy(isEven)) -func Satisfy(predicate interface{}) types.GomegaMatcher { +func Satisfy(predicate any) types.GomegaMatcher { return matchers.NewSatisfyMatcher(predicate) } diff --git a/vendor/github.com/onsi/gomega/matchers/and.go b/vendor/github.com/onsi/gomega/matchers/and.go index 6bd826adc..db48e90b3 100644 --- a/vendor/github.com/onsi/gomega/matchers/and.go +++ b/vendor/github.com/onsi/gomega/matchers/and.go @@ -14,7 +14,7 @@ type AndMatcher struct { firstFailedMatcher types.GomegaMatcher } -func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { +func (m *AndMatcher) Match(actual any) (success bool, err error) { m.firstFailedMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) @@ -26,16 +26,16 @@ func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { return true, nil } -func (m *AndMatcher) FailureMessage(actual interface{}) (message string) { +func (m *AndMatcher) FailureMessage(actual any) (message string) { return m.firstFailedMatcher.FailureMessage(actual) } -func (m *AndMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *AndMatcher) NegatedFailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To not satisfy all of these matchers: %s", m.Matchers)) } -func (m *AndMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *AndMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go index be4839520..a100e5c07 100644 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go @@ -10,10 +10,10 @@ import ( ) type AssignableToTypeOfMatcher struct { - Expected interface{} + Expected any } -func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *AssignableToTypeOfMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } else if matcher.Expected == nil { @@ -28,10 +28,10 @@ func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success boo return actualType.AssignableTo(expectedType), nil } -func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual interface{}) string { +func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) } -func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual interface{}) string { +func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go b/vendor/github.com/onsi/gomega/matchers/be_a_directory.go index 93d4497c7..1d8236048 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go +++ b/vendor/github.com/onsi/gomega/matchers/be_a_directory.go @@ -24,11 +24,11 @@ func (t notADirectoryError) Error() string { } type BeADirectoryMatcher struct { - expected interface{} + expected any err error } -func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeADirectoryMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeADirectoryMatcher matcher expects a file path") @@ -47,10 +47,10 @@ func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err return true, nil } -func (matcher *BeADirectoryMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeADirectoryMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a directory: %s", matcher.err)) } -func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a directory") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go index 8fefc4deb..3e53d6285 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go +++ b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go @@ -24,11 +24,11 @@ func (t notARegularFileError) Error() string { } type BeARegularFileMatcher struct { - expected interface{} + expected any err error } -func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeARegularFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeARegularFileMatcher matcher expects a file path") @@ -47,10 +47,10 @@ func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, e return true, nil } -func (matcher *BeARegularFileMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeARegularFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a regular file: %s", matcher.err)) } -func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a regular file") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go index e2bdd2811..04f156db3 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go +++ b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go @@ -10,10 +10,10 @@ import ( ) type BeAnExistingFileMatcher struct { - expected interface{} + expected any } -func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeAnExistingFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeAnExistingFileMatcher matcher expects a file path") @@ -31,10 +31,10 @@ func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, return true, nil } -func (matcher *BeAnExistingFileMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeAnExistingFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to exist") } -func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to exist") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go index f13c24490..4319dde45 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go @@ -12,7 +12,7 @@ import ( type BeClosedMatcher struct { } -func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeClosedMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeClosed matcher expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -39,10 +39,10 @@ func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err err return closed, nil } -func (matcher *BeClosedMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeClosedMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be closed") } -func (matcher *BeClosedMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeClosedMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to be open") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go index 4e3897858..532fc3744 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go @@ -9,11 +9,11 @@ import ( ) type BeComparableToMatcher struct { - Expected interface{} + Expected any Options cmp.Options } -func (matcher *BeComparableToMatcher) Match(actual interface{}) (success bool, matchErr error) { +func (matcher *BeComparableToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -40,10 +40,10 @@ func (matcher *BeComparableToMatcher) Match(actual interface{}) (success bool, m return cmp.Equal(actual, matcher.Expected, matcher.Options...), nil } -func (matcher *BeComparableToMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeComparableToMatcher) FailureMessage(actual any) (message string) { return fmt.Sprint("Expected object to be comparable, diff: ", cmp.Diff(actual, matcher.Expected, matcher.Options...)) } -func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be comparable to", matcher.Expected) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go index 9ee75a5d5..406fe5484 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go @@ -10,10 +10,10 @@ import ( ) type BeElementOfMatcher struct { - Elements []interface{} + Elements []any } -func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeElementOfMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual) == nil { return false, fmt.Errorf("BeElement matcher expects actual to be typed") } @@ -34,10 +34,10 @@ func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err return false, lastError } -func (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeElementOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be an element of", presentable(matcher.Elements)) } -func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be an element of", presentable(matcher.Elements)) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go index bd7f0b96e..e9e0644f3 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go @@ -13,7 +13,7 @@ import ( type BeEmptyMatcher struct { } -func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeEmptyMatcher) Match(actual any) (success bool, err error) { // short-circuit the iterator case, as we only need to see the first // element, if any. if miter.IsIter(actual) { @@ -34,10 +34,10 @@ func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err erro return length == 0, nil } -func (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeEmptyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be empty") } -func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be empty") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go index 263627f40..37b3080ba 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go @@ -10,10 +10,10 @@ import ( ) type BeEquivalentToMatcher struct { - Expected interface{} + Expected any } -func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeEquivalentToMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Both actual and expected must not be nil.") } @@ -27,10 +27,10 @@ func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, e return reflect.DeepEqual(convertedActual, matcher.Expected), nil } -func (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeEquivalentToMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be equivalent to", matcher.Expected) } -func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be equivalent to", matcher.Expected) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go index 8ee2b1c51..55e869515 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go @@ -12,7 +12,7 @@ type BeFalseMatcher struct { Reason string } -func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeFalseMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } @@ -20,7 +20,7 @@ func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err erro return actual == false, nil } -func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeFalseMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be false") } else { @@ -28,7 +28,7 @@ func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message strin } } -func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeFalseMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be false") } else { diff --git a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go b/vendor/github.com/onsi/gomega/matchers/be_identical_to.go index 631ce11e3..579aa41b3 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go +++ b/vendor/github.com/onsi/gomega/matchers/be_identical_to.go @@ -10,10 +10,10 @@ import ( ) type BeIdenticalToMatcher struct { - Expected interface{} + Expected any } -func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, matchErr error) { +func (matcher *BeIdenticalToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -30,10 +30,10 @@ func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, ma return actual == matcher.Expected, nil } -func (matcher *BeIdenticalToMatcher) FailureMessage(actual interface{}) string { +func (matcher *BeIdenticalToMatcher) FailureMessage(actual any) string { return format.Message(actual, "to be identical to", matcher.Expected) } -func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual interface{}) string { +func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, "not to be identical to", matcher.Expected) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go index 449a291ef..3fff3df78 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go @@ -8,10 +8,10 @@ import ( ) type BeKeyOfMatcher struct { - Map interface{} + Map any } -func (matcher *BeKeyOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeKeyOfMatcher) Match(actual any) (success bool, err error) { if !isMap(matcher.Map) { return false, fmt.Errorf("BeKeyOf matcher needs expected to be a map type") } @@ -36,10 +36,10 @@ func (matcher *BeKeyOfMatcher) Match(actual interface{}) (success bool, err erro return false, lastError } -func (matcher *BeKeyOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeKeyOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be a key of", presentable(valuesOf(matcher.Map))) } -func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be a key of", presentable(valuesOf(matcher.Map))) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go index 551d99d74..cab37f4f9 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go @@ -7,14 +7,14 @@ import "github.com/onsi/gomega/format" type BeNilMatcher struct { } -func (matcher *BeNilMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeNilMatcher) Match(actual any) (success bool, err error) { return isNil(actual), nil } -func (matcher *BeNilMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeNilMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be nil") } -func (matcher *BeNilMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeNilMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be nil") } diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go index 100735de3..7e6ce154e 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go @@ -11,18 +11,18 @@ import ( type BeNumericallyMatcher struct { Comparator string - CompareTo []interface{} + CompareTo []any } -func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeNumericallyMatcher) FailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, false) } -func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, true) } -func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, negated bool) (message string) { +func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual any, negated bool) (message string) { if len(matcher.CompareTo) == 1 { message = fmt.Sprintf("to be %s", matcher.Comparator) } else { @@ -34,7 +34,7 @@ func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, ne return format.Message(actual, message, matcher.CompareTo[0]) } -func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeNumericallyMatcher) Match(actual any) (success bool, err error) { if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { return false, fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go index cf582a3fc..14ffbf6c4 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go @@ -10,11 +10,11 @@ import ( ) type BeSentMatcher struct { - Arg interface{} + Arg any channelClosed bool } -func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeSentMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeSent expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -56,15 +56,15 @@ func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error return didSend, nil } -func (matcher *BeSentMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeSentMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to send:", matcher.Arg) } -func (matcher *BeSentMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeSentMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to send:", matcher.Arg) } -func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go index dec4db024..edb647c6f 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go @@ -15,17 +15,17 @@ type BeTemporallyMatcher struct { Threshold []time.Duration } -func (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeTemporallyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo) } -func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo) } -func (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) { +func (matcher *BeTemporallyMatcher) Match(actual any) (bool, error) { // predicate to test for time.Time type - isTime := func(t interface{}) bool { + isTime := func(t any) bool { _, ok := t.(time.Time) return ok } diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go index 3576aac88..a010bec5a 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go @@ -12,7 +12,7 @@ type BeTrueMatcher struct { Reason string } -func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeTrueMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } @@ -20,7 +20,7 @@ func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error return actual.(bool), nil } -func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeTrueMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be true") } else { @@ -28,7 +28,7 @@ func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string } } -func (matcher *BeTrueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeTrueMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be true") } else { diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go index 26196f168..f5f5d7f7d 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go @@ -9,7 +9,7 @@ import ( type BeZeroMatcher struct { } -func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *BeZeroMatcher) Match(actual any) (success bool, err error) { if actual == nil { return true, nil } @@ -19,10 +19,10 @@ func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error } -func (matcher *BeZeroMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *BeZeroMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be zero-valued") } -func (matcher *BeZeroMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *BeZeroMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be zero-valued") } diff --git a/vendor/github.com/onsi/gomega/matchers/consist_of.go b/vendor/github.com/onsi/gomega/matchers/consist_of.go index a11188182..05c751b66 100644 --- a/vendor/github.com/onsi/gomega/matchers/consist_of.go +++ b/vendor/github.com/onsi/gomega/matchers/consist_of.go @@ -12,12 +12,12 @@ import ( ) type ConsistOfMatcher struct { - Elements []interface{} - missingElements []interface{} - extraElements []interface{} + Elements []any + missingElements []any + extraElements []any } -func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ConsistOfMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } @@ -35,19 +35,19 @@ func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err er return true, nil } - var missingMatchers []interface{} + var missingMatchers []any matcher.extraElements, missingMatchers = bipartiteGraph.FreeLeftRight(edges) matcher.missingElements = equalMatchersToElements(missingMatchers) return false, nil } -func neighbours(value, matcher interface{}) (bool, error) { +func neighbours(value, matcher any) (bool, error) { match, err := matcher.(omegaMatcher).Match(value) return match && err == nil, nil } -func equalMatchersToElements(matchers []interface{}) (elements []interface{}) { +func equalMatchersToElements(matchers []any) (elements []any) { for _, matcher := range matchers { if equalMatcher, ok := matcher.(*EqualMatcher); ok { elements = append(elements, equalMatcher.Expected) @@ -60,7 +60,7 @@ func equalMatchersToElements(matchers []interface{}) (elements []interface{}) { return } -func flatten(elems []interface{}) []interface{} { +func flatten(elems []any) []any { if len(elems) != 1 || !(isArrayOrSlice(elems[0]) || (miter.IsIter(elems[0]) && !miter.IsSeq2(elems[0]))) { @@ -77,14 +77,14 @@ func flatten(elems []interface{}) []interface{} { } value := reflect.ValueOf(elems[0]) - flattened := make([]interface{}, value.Len()) + flattened := make([]any, value.Len()) for i := 0; i < value.Len(); i++ { flattened[i] = value.Index(i).Interface() } return flattened } -func matchers(expectedElems []interface{}) (matchers []interface{}) { +func matchers(expectedElems []any) (matchers []any) { for _, e := range flatten(expectedElems) { if e == nil { matchers = append(matchers, &BeNilMatcher{}) @@ -97,11 +97,11 @@ func matchers(expectedElems []interface{}) (matchers []interface{}) { return } -func presentable(elems []interface{}) interface{} { +func presentable(elems []any) any { elems = flatten(elems) if len(elems) == 0 { - return []interface{}{} + return []any{} } sv := reflect.ValueOf(elems) @@ -125,9 +125,9 @@ func presentable(elems []interface{}) interface{} { return ss.Interface() } -func valuesOf(actual interface{}) []interface{} { +func valuesOf(actual any) []any { value := reflect.ValueOf(actual) - values := []interface{}{} + values := []any{} if miter.IsIter(actual) { if miter.IsSeq2(actual) { miter.IterateKV(actual, func(k, v reflect.Value) bool { @@ -154,7 +154,7 @@ func valuesOf(actual interface{}) []interface{} { return values } -func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ConsistOfMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to consist of", presentable(matcher.Elements)) message = appendMissingElements(message, matcher.missingElements) if len(matcher.extraElements) > 0 { @@ -164,7 +164,7 @@ func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message str return } -func appendMissingElements(message string, missingElements []interface{}) string { +func appendMissingElements(message string, missingElements []any) string { if len(missingElements) == 0 { return message } @@ -172,6 +172,6 @@ func appendMissingElements(message string, missingElements []interface{}) string format.Object(presentable(missingElements), 1)) } -func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to consist of", presentable(matcher.Elements)) } diff --git a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go index 830239c7b..8337a5261 100644 --- a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go @@ -12,11 +12,11 @@ import ( ) type ContainElementMatcher struct { - Element interface{} - Result []interface{} + Element any + Result []any } -func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainElementMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElement matcher expects an array/slice/map/iterator. Got:\n%s", format.Object(actual, 1)) } @@ -132,14 +132,14 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e var lastError error if !miter.IsIter(actual) { - var valueAt func(int) interface{} + var valueAt func(int) any var foundAt func(int) // We're dealing with an array/slice/map, so in all cases we can iterate // over the elements in actual using indices (that can be considered // keys in case of maps). if isMap(actual) { keys := value.MapKeys() - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } if result.Kind() != reflect.Invalid { @@ -150,7 +150,7 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e } } } else { - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.Index(i).Interface() } if result.Kind() != reflect.Invalid { @@ -251,7 +251,7 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e } // pick up any findings the test is interested in as it specified a non-nil - // result reference. However, the expection always is that there are at + // result reference. However, the expectation always is that there are at // least one or multiple findings. So, if a result is expected, but we had // no findings, then this is an error. findings := getFindings() @@ -284,10 +284,10 @@ func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, e return true, nil } -func (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } -func (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) } diff --git a/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go index d9fcb8b80..ce3041892 100644 --- a/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go @@ -9,11 +9,11 @@ import ( ) type ContainElementsMatcher struct { - Elements []interface{} - missingElements []interface{} + Elements []any + missingElements []any } -func (matcher *ContainElementsMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainElementsMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElements matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } @@ -35,11 +35,11 @@ func (matcher *ContainElementsMatcher) Match(actual interface{}) (success bool, return false, nil } -func (matcher *ContainElementsMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to contain elements", presentable(matcher.Elements)) return appendMissingElements(message, matcher.missingElements) } -func (matcher *ContainElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) } diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go index e725f8c27..d9980ee26 100644 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go @@ -11,10 +11,10 @@ import ( type ContainSubstringMatcher struct { Substr string - Args []interface{} + Args []any } -func (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ContainSubstringMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("ContainSubstring matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -31,10 +31,10 @@ func (matcher *ContainSubstringMatcher) stringToMatch() string { return stringToMatch } -func (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ContainSubstringMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain substring", matcher.stringToMatch()) } -func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain substring", matcher.stringToMatch()) } diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go index befb7bdfd..4ad166157 100644 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go @@ -9,10 +9,10 @@ import ( ) type EqualMatcher struct { - Expected interface{} + Expected any } -func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *EqualMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } @@ -27,7 +27,7 @@ func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) return reflect.DeepEqual(actual, matcher.Expected), nil } -func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *EqualMatcher) FailureMessage(actual any) (message string) { actualString, actualOK := actual.(string) expectedString, expectedOK := matcher.Expected.(string) if actualOK && expectedOK { @@ -37,6 +37,6 @@ func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) return format.Message(actual, "to equal", matcher.Expected) } -func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *EqualMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to equal", matcher.Expected) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go index 9856752f1..a4fcfc425 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go @@ -12,7 +12,7 @@ type HaveCapMatcher struct { Count int } -func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveCapMatcher) Match(actual any) (success bool, err error) { length, ok := capOf(actual) if !ok { return false, fmt.Errorf("HaveCap matcher expects a array/channel/slice. Got:\n%s", format.Object(actual, 1)) @@ -21,10 +21,10 @@ func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err erro return length == matcher.Count, nil } -func (matcher *HaveCapMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveCapMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have capacity %d", format.Object(actual, 1), matcher.Count) } -func (matcher *HaveCapMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveCapMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have capacity %d", format.Object(actual, 1), matcher.Count) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go index 4111f2b86..4c45063bd 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go @@ -9,10 +9,10 @@ import ( ) type HaveEachMatcher struct { - Element interface{} + Element any } -func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveEachMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("HaveEach matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) @@ -61,14 +61,14 @@ func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err err format.Object(actual, 1)) } - var valueAt func(int) interface{} + var valueAt func(int) any if isMap(actual) { keys := value.MapKeys() - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } } else { - valueAt = func(i int) interface{} { + valueAt = func(i int) any { return value.Index(i).Interface() } } @@ -89,11 +89,11 @@ func (matcher *HaveEachMatcher) Match(actual interface{}) (success bool, err err } // FailureMessage returns a suitable failure message. -func (matcher *HaveEachMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveEachMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } // NegatedFailureMessage returns a suitable negated failure message. -func (matcher *HaveEachMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveEachMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go b/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go index 23799f1c6..8b2d297c5 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go +++ b/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go @@ -14,13 +14,13 @@ type mismatchFailure struct { } type HaveExactElementsMatcher struct { - Elements []interface{} + Elements []any mismatchFailures []mismatchFailure missingIndex int extraIndex int } -func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveExactElementsMatcher) Match(actual any) (success bool, err error) { matcher.resetState() if isMap(actual) || miter.IsSeq2(actual) { @@ -108,7 +108,7 @@ func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool return success, nil } -func (matcher *HaveExactElementsMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveExactElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to have exact elements with", presentable(matcher.Elements)) if matcher.missingIndex > 0 { message = fmt.Sprintf("%s\nthe missing elements start from index %d", message, matcher.missingIndex) @@ -125,7 +125,7 @@ func (matcher *HaveExactElementsMatcher) FailureMessage(actual interface{}) (mes return } -func (matcher *HaveExactElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveExactElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go index b57018745..a5a028e9a 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go @@ -11,7 +11,7 @@ type HaveExistingFieldMatcher struct { Field string } -func (matcher *HaveExistingFieldMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveExistingFieldMatcher) Match(actual any) (success bool, err error) { // we don't care about the field's actual value, just about any error in // trying to find the field (or method). _, err = extractField(actual, matcher.Field, "HaveExistingField") @@ -27,10 +27,10 @@ func (matcher *HaveExistingFieldMatcher) Match(actual interface{}) (success bool return false, err } -func (matcher *HaveExistingFieldMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveExistingFieldMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have field '%s'", format.Object(actual, 1), matcher.Field) } -func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have field '%s'", format.Object(actual, 1), matcher.Field) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_field.go b/vendor/github.com/onsi/gomega/matchers/have_field.go index 293457e85..d9fbeaf75 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_field.go +++ b/vendor/github.com/onsi/gomega/matchers/have_field.go @@ -17,7 +17,7 @@ func (e missingFieldError) Error() string { return string(e) } -func extractField(actual interface{}, field string, matchername string) (any, error) { +func extractField(actual any, field string, matchername string) (any, error) { fields := strings.SplitN(field, ".", 2) actualValue := reflect.ValueOf(actual) @@ -68,7 +68,7 @@ func extractField(actual interface{}, field string, matchername string) (any, er type HaveFieldMatcher struct { Field string - Expected interface{} + Expected any } func (matcher *HaveFieldMatcher) expectedMatcher() omegaMatcher { @@ -80,7 +80,7 @@ func (matcher *HaveFieldMatcher) expectedMatcher() omegaMatcher { return expectedMatcher } -func (matcher *HaveFieldMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveFieldMatcher) Match(actual any) (success bool, err error) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { return false, err @@ -89,7 +89,7 @@ func (matcher *HaveFieldMatcher) Match(actual interface{}) (success bool, err er return matcher.expectedMatcher().Match(extractedField) } -func (matcher *HaveFieldMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveFieldMatcher) FailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen @@ -101,7 +101,7 @@ func (matcher *HaveFieldMatcher) FailureMessage(actual interface{}) (message str return message } -func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen diff --git a/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go index d14d9e5fc..2d561b9a2 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go @@ -11,12 +11,12 @@ import ( ) type HaveHTTPBodyMatcher struct { - Expected interface{} - cachedResponse interface{} + Expected any + cachedResponse any cachedBody []byte } -func (matcher *HaveHTTPBodyMatcher) Match(actual interface{}) (bool, error) { +func (matcher *HaveHTTPBodyMatcher) Match(actual any) (bool, error) { body, err := matcher.body(actual) if err != nil { return false, err @@ -34,7 +34,7 @@ func (matcher *HaveHTTPBodyMatcher) Match(actual interface{}) (bool, error) { } } -func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) @@ -52,7 +52,7 @@ func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual interface{}) (message } } -func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) @@ -73,7 +73,7 @@ func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual interface{}) (m // body returns the body. It is cached because once we read it in Match() // the Reader is closed and it is not readable again in FailureMessage() // or NegatedFailureMessage() -func (matcher *HaveHTTPBodyMatcher) body(actual interface{}) ([]byte, error) { +func (matcher *HaveHTTPBodyMatcher) body(actual any) ([]byte, error) { if matcher.cachedResponse == actual && matcher.cachedBody != nil { return matcher.cachedBody, nil } diff --git a/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go index c256f452e..756722659 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go @@ -11,10 +11,10 @@ import ( type HaveHTTPHeaderWithValueMatcher struct { Header string - Value interface{} + Value any } -func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual any) (success bool, err error) { headerValue, err := matcher.extractHeader(actual) if err != nil { return false, err @@ -28,7 +28,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual interface{}) (succes return headerMatcher.Match(headerValue) } -func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual interface{}) string { +func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual any) string { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() @@ -43,7 +43,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual interface{} return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff) } -func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual any) (message string) { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() @@ -69,7 +69,7 @@ func (matcher *HaveHTTPHeaderWithValueMatcher) getSubMatcher() (types.GomegaMatc } } -func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual interface{}) (string, error) { +func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual any) (string, error) { switch r := actual.(type) { case *http.Response: return r.Header.Get(matcher.Header), nil diff --git a/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go index 0f66e46ec..8b25b3a9f 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go @@ -12,10 +12,10 @@ import ( ) type HaveHTTPStatusMatcher struct { - Expected []interface{} + Expected []any } -func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveHTTPStatusMatcher) Match(actual any) (success bool, err error) { var resp *http.Response switch a := actual.(type) { case *http.Response: @@ -48,11 +48,11 @@ func (matcher *HaveHTTPStatusMatcher) Match(actual interface{}) (success bool, e return false, nil } -func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "to have HTTP status", matcher.expectedString()) } -func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "not to have HTTP status", matcher.expectedString()) } @@ -64,7 +64,7 @@ func (matcher *HaveHTTPStatusMatcher) expectedString() string { return strings.Join(lines, "\n") } -func formatHttpResponse(input interface{}) string { +func formatHttpResponse(input any) string { var resp *http.Response switch r := input.(type) { case *http.Response: diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go index b62ee93cb..9e16dcf5d 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go @@ -11,10 +11,10 @@ import ( ) type HaveKeyMatcher struct { - Key interface{} + Key any } -func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveKeyMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKey matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } @@ -52,7 +52,7 @@ func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err erro return false, nil } -func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyMatcher) FailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "to have key matching", matcher.Key) @@ -61,7 +61,7 @@ func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message strin } } -func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "not to have key matching", matcher.Key) diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go index 3d608f63e..1c53f1e56 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go @@ -11,11 +11,11 @@ import ( ) type HaveKeyWithValueMatcher struct { - Key interface{} - Value interface{} + Key any + Value any } -func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveKeyWithValueMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKeyWithValue matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } @@ -70,7 +70,7 @@ func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, return false, nil } -func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual any) (message string) { str := "to have {key: value}" if _, ok := matcher.Key.(omegaMatcher); ok { str += " matching" @@ -78,12 +78,12 @@ func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (mess str += " matching" } - expect := make(map[interface{}]interface{}, 1) + expect := make(map[any]any, 1) expect[matcher.Key] = matcher.Value return format.Message(actual, str, expect) } -func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual any) (message string) { kStr := "not to have key" if _, ok := matcher.Key.(omegaMatcher); ok { kStr = "not to have key matching" diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go index ca25713fe..c334d4c0a 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go @@ -10,7 +10,7 @@ type HaveLenMatcher struct { Count int } -func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveLenMatcher) Match(actual any) (success bool, err error) { length, ok := lengthOf(actual) if !ok { return false, fmt.Errorf("HaveLen matcher expects a string/array/map/channel/slice/iterator. Got:\n%s", format.Object(actual, 1)) @@ -19,10 +19,10 @@ func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err erro return length == matcher.Count, nil } -func (matcher *HaveLenMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveLenMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have length %d", format.Object(actual, 1), matcher.Count) } -func (matcher *HaveLenMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveLenMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have length %d", format.Object(actual, 1), matcher.Count) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go index 22a1b6730..a240f1a1c 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go @@ -11,7 +11,7 @@ import ( type HaveOccurredMatcher struct { } -func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveOccurredMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return false, nil @@ -26,10 +26,10 @@ func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err return !isNil(actual), nil } -func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveOccurredMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1)) } -func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Unexpected error:\n%s\n%s", format.Object(actual, 1), "occurred") } diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go index 1d8e80270..7987d41f7 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go @@ -8,10 +8,10 @@ import ( type HavePrefixMatcher struct { Prefix string - Args []interface{} + Args []any } -func (matcher *HavePrefixMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HavePrefixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HavePrefix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -27,10 +27,10 @@ func (matcher *HavePrefixMatcher) prefix() string { return matcher.Prefix } -func (matcher *HavePrefixMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HavePrefixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have prefix", matcher.prefix()) } -func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have prefix", matcher.prefix()) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go index 40a3526eb..2aa4ceacb 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go @@ -8,10 +8,10 @@ import ( type HaveSuffixMatcher struct { Suffix string - Args []interface{} + Args []any } -func (matcher *HaveSuffixMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *HaveSuffixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HaveSuffix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) @@ -27,10 +27,10 @@ func (matcher *HaveSuffixMatcher) suffix() string { return matcher.Suffix } -func (matcher *HaveSuffixMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *HaveSuffixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have suffix", matcher.suffix()) } -func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have suffix", matcher.suffix()) } diff --git a/vendor/github.com/onsi/gomega/matchers/have_value.go b/vendor/github.com/onsi/gomega/matchers/have_value.go index f67252835..4c39e0db0 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_value.go +++ b/vendor/github.com/onsi/gomega/matchers/have_value.go @@ -12,10 +12,10 @@ const maxIndirections = 31 type HaveValueMatcher struct { Matcher types.GomegaMatcher // the matcher to apply to the "resolved" actual value. - resolvedActual interface{} // the ("resolved") value. + resolvedActual any // the ("resolved") value. } -func (m *HaveValueMatcher) Match(actual interface{}) (bool, error) { +func (m *HaveValueMatcher) Match(actual any) (bool, error) { val := reflect.ValueOf(actual) for allowedIndirs := maxIndirections; allowedIndirs > 0; allowedIndirs-- { // return an error if value isn't valid. Please note that we cannot @@ -45,10 +45,10 @@ func (m *HaveValueMatcher) Match(actual interface{}) (bool, error) { return false, errors.New(format.Message(actual, "too many indirections")) } -func (m *HaveValueMatcher) FailureMessage(_ interface{}) (message string) { +func (m *HaveValueMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.resolvedActual) } -func (m *HaveValueMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (m *HaveValueMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.resolvedActual) } diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go index c539dd389..f9d313772 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go @@ -71,14 +71,14 @@ func (matcher *MatchErrorMatcher) Match(actual any) (success bool, err error) { format.Object(expected, 1)) } -func (matcher *MatchErrorMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchErrorMatcher) FailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("to match error function %s", matcher.FuncErrDescription[0])) } return format.Message(actual, "to match error", matcher.Expected) } -func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("not to match error function %s", matcher.FuncErrDescription[0])) } diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go index f962f139f..331f289ab 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go @@ -9,18 +9,18 @@ import ( ) type MatchJSONMatcher struct { - JSONToMatch interface{} - firstFailurePath []interface{} + JSONToMatch any + firstFailurePath []any } -func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchJSONMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.prettyPrint(actual) if err != nil { return false, err } - var aval interface{} - var eval interface{} + var aval any + var eval any // this is guarded by prettyPrint json.Unmarshal([]byte(actualString), &aval) @@ -30,17 +30,17 @@ func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err er return equal, nil } -func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchJSONMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchJSONMatcher) prettyPrint(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go index adac5db6b..779be683e 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go @@ -9,10 +9,10 @@ import ( type MatchRegexpMatcher struct { Regexp string - Args []interface{} + Args []any } -func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchRegexpMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) @@ -26,11 +26,11 @@ func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err return match, nil } -func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchRegexpMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to match regular expression", matcher.regexp()) } -func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match regular expression", matcher.regexp()) } diff --git a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go index 5c815f5af..f7dcaf6fd 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go @@ -15,10 +15,10 @@ import ( ) type MatchXMLMatcher struct { - XMLToMatch interface{} + XMLToMatch any } -func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchXMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.formattedPrint(actual) if err != nil { return false, err @@ -37,17 +37,17 @@ func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err err return reflect.DeepEqual(aval, eval), nil } -func (matcher *MatchXMLMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchXMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString) } -func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString) } -func (matcher *MatchXMLMatcher) formattedPrint(actual interface{}) (actualString, expectedString string, err error) { +func (matcher *MatchXMLMatcher) formattedPrint(actual any) (actualString, expectedString string, err error) { var ok bool actualString, ok = toString(actual) if !ok { diff --git a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go index 2cb6b47db..95057c26c 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go @@ -9,18 +9,18 @@ import ( ) type MatchYAMLMatcher struct { - YAMLToMatch interface{} - firstFailurePath []interface{} + YAMLToMatch any + firstFailurePath []any } -func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchYAMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.toStrings(actual) if err != nil { return false, err } - var aval interface{} - var eval interface{} + var aval any + var eval any if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) @@ -34,23 +34,23 @@ func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err er return equal, nil } -func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *MatchYAMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath) } -func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, expectedString, err := matcher.toStrings(actual) return normalise(actualString), normalise(expectedString), err } func normalise(input string) string { - var val interface{} + var val any err := yaml.Unmarshal([]byte(input), &val) if err != nil { panic(err) // unreachable since Match already calls Unmarshal @@ -62,7 +62,7 @@ func normalise(input string) string { return strings.TrimSpace(string(output)) } -func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { +func (matcher *MatchYAMLMatcher) toStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) diff --git a/vendor/github.com/onsi/gomega/matchers/not.go b/vendor/github.com/onsi/gomega/matchers/not.go index 78b71910d..c598b7899 100644 --- a/vendor/github.com/onsi/gomega/matchers/not.go +++ b/vendor/github.com/onsi/gomega/matchers/not.go @@ -8,7 +8,7 @@ type NotMatcher struct { Matcher types.GomegaMatcher } -func (m *NotMatcher) Match(actual interface{}) (bool, error) { +func (m *NotMatcher) Match(actual any) (bool, error) { success, err := m.Matcher.Match(actual) if err != nil { return false, err @@ -16,14 +16,14 @@ func (m *NotMatcher) Match(actual interface{}) (bool, error) { return !success, nil } -func (m *NotMatcher) FailureMessage(actual interface{}) (message string) { +func (m *NotMatcher) FailureMessage(actual any) (message string) { return m.Matcher.NegatedFailureMessage(actual) // works beautifully } -func (m *NotMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *NotMatcher) NegatedFailureMessage(actual any) (message string) { return m.Matcher.FailureMessage(actual) // works beautifully } -func (m *NotMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *NotMatcher) MatchMayChangeInTheFuture(actual any) bool { return types.MatchMayChangeInTheFuture(m.Matcher, actual) // just return m.Matcher's value } diff --git a/vendor/github.com/onsi/gomega/matchers/or.go b/vendor/github.com/onsi/gomega/matchers/or.go index 841ae26ab..6578404b0 100644 --- a/vendor/github.com/onsi/gomega/matchers/or.go +++ b/vendor/github.com/onsi/gomega/matchers/or.go @@ -14,7 +14,7 @@ type OrMatcher struct { firstSuccessfulMatcher types.GomegaMatcher } -func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { +func (m *OrMatcher) Match(actual any) (success bool, err error) { m.firstSuccessfulMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) @@ -29,16 +29,16 @@ func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { return false, nil } -func (m *OrMatcher) FailureMessage(actual interface{}) (message string) { +func (m *OrMatcher) FailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To satisfy at least one of these matchers: %s", m.Matchers)) } -func (m *OrMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *OrMatcher) NegatedFailureMessage(actual any) (message string) { return m.firstSuccessfulMatcher.NegatedFailureMessage(actual) } -func (m *OrMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (m *OrMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C diff --git a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go b/vendor/github.com/onsi/gomega/matchers/panic_matcher.go index adc8cee63..8be5a7ccf 100644 --- a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/panic_matcher.go @@ -8,11 +8,11 @@ import ( ) type PanicMatcher struct { - Expected interface{} - object interface{} + Expected any + object any } -func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *PanicMatcher) Match(actual any) (success bool, err error) { if actual == nil { return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") } @@ -52,7 +52,7 @@ func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) return } -func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *PanicMatcher) FailureMessage(actual any) (message string) { if matcher.Expected == nil { // We wanted any panic to occur, but none did. return format.Message(actual, "to panic") @@ -91,7 +91,7 @@ func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) } } -func (matcher *PanicMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *PanicMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Expected == nil { // We didn't want any panic to occur, but one did. return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1))) diff --git a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go b/vendor/github.com/onsi/gomega/matchers/receive_matcher.go index 948164eaf..1d9f61d63 100644 --- a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/receive_matcher.go @@ -11,12 +11,12 @@ import ( ) type ReceiveMatcher struct { - Args []interface{} + Args []any receivedValue reflect.Value channelClosed bool } -func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ReceiveMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("ReceiveMatcher expects a channel. Got:\n%s", format.Object(actual, 1)) } @@ -30,7 +30,7 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro var subMatcher omegaMatcher var hasSubMatcher bool - var resultReference interface{} + var resultReference any // Valid arg formats are as follows, always with optional POINTER before // optional MATCHER: @@ -115,8 +115,8 @@ func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err erro return false, nil } -func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message string) { - var matcherArg interface{} +func (matcher *ReceiveMatcher) FailureMessage(actual any) (message string) { + var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } @@ -136,8 +136,8 @@ func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message strin return format.Message(actual, "to receive something."+closedAddendum) } -func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (message string) { - var matcherArg interface{} +func (matcher *ReceiveMatcher) NegatedFailureMessage(actual any) (message string) { + var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } @@ -157,7 +157,7 @@ func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (messag return format.Message(actual, "not to receive anything."+closedAddendum) } -func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } diff --git a/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go b/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go index ec68fe8b6..2adc4825a 100644 --- a/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go @@ -8,13 +8,13 @@ import ( ) type SatisfyMatcher struct { - Predicate interface{} + Predicate any // cached type predicateArgType reflect.Type } -func NewSatisfyMatcher(predicate interface{}) *SatisfyMatcher { +func NewSatisfyMatcher(predicate any) *SatisfyMatcher { if predicate == nil { panic("predicate cannot be nil") } @@ -35,7 +35,7 @@ func NewSatisfyMatcher(predicate interface{}) *SatisfyMatcher { } } -func (m *SatisfyMatcher) Match(actual interface{}) (success bool, err error) { +func (m *SatisfyMatcher) Match(actual any) (success bool, err error) { // prepare a parameter to pass to the predicate var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.predicateArgType) { @@ -57,10 +57,10 @@ func (m *SatisfyMatcher) Match(actual interface{}) (success bool, err error) { return result[0].Bool(), nil } -func (m *SatisfyMatcher) FailureMessage(actual interface{}) (message string) { +func (m *SatisfyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to satisfy predicate", m.Predicate) } -func (m *SatisfyMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (m *SatisfyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to not satisfy predicate", m.Predicate) } diff --git a/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go b/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go index 1369c1e87..30dd58f4a 100644 --- a/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go +++ b/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go @@ -8,7 +8,7 @@ import ( "strings" ) -func formattedMessage(comparisonMessage string, failurePath []interface{}) string { +func formattedMessage(comparisonMessage string, failurePath []any) string { var diffMessage string if len(failurePath) == 0 { diffMessage = "" @@ -18,7 +18,7 @@ func formattedMessage(comparisonMessage string, failurePath []interface{}) strin return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) } -func formattedFailurePath(failurePath []interface{}) string { +func formattedFailurePath(failurePath []any) string { formattedPaths := []string{} for i := len(failurePath) - 1; i >= 0; i-- { switch p := failurePath[i].(type) { @@ -34,33 +34,33 @@ func formattedFailurePath(failurePath []interface{}) string { return strings.Join(formattedPaths, "") } -func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { - var errorPath []interface{} +func deepEqual(a any, b any) (bool, []any) { + var errorPath []any if reflect.TypeOf(a) != reflect.TypeOf(b) { return false, errorPath } switch a.(type) { - case []interface{}: - if len(a.([]interface{})) != len(b.([]interface{})) { + case []any: + if len(a.([]any)) != len(b.([]any)) { return false, errorPath } - for i, v := range a.([]interface{}) { - elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) + for i, v := range a.([]any) { + elementEqual, keyPath := deepEqual(v, b.([]any)[i]) if !elementEqual { return false, append(keyPath, i) } } return true, errorPath - case map[interface{}]interface{}: - if len(a.(map[interface{}]interface{})) != len(b.(map[interface{}]interface{})) { + case map[any]any: + if len(a.(map[any]any)) != len(b.(map[any]any)) { return false, errorPath } - for k, v1 := range a.(map[interface{}]interface{}) { - v2, ok := b.(map[interface{}]interface{})[k] + for k, v1 := range a.(map[any]any) { + v2, ok := b.(map[any]any)[k] if !ok { return false, errorPath } @@ -71,13 +71,13 @@ func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { } return true, errorPath - case map[string]interface{}: - if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { + case map[string]any: + if len(a.(map[string]any)) != len(b.(map[string]any)) { return false, errorPath } - for k, v1 := range a.(map[string]interface{}) { - v2, ok := b.(map[string]interface{})[k] + for k, v1 := range a.(map[string]any) { + v2, ok := b.(map[string]any)[k] if !ok { return false, errorPath } diff --git a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go b/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go index 327350f7b..f0b2c4aa6 100644 --- a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go @@ -14,7 +14,7 @@ type formattedGomegaError interface { type SucceedMatcher struct { } -func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *SucceedMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return true, nil @@ -29,7 +29,7 @@ func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err erro return isNil(actual), nil } -func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *SucceedMatcher) FailureMessage(actual any) (message string) { var fgErr formattedGomegaError if errors.As(actual.(error), &fgErr) { return fgErr.FormattedGomegaError() @@ -37,6 +37,6 @@ func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message strin return fmt.Sprintf("Expected success, but got an error:\n%s", format.Object(actual, 1)) } -func (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *SucceedMatcher) NegatedFailureMessage(actual any) (message string) { return "Expected failure, but got no error." } diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go index 830e30827..0d78779d4 100644 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go +++ b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go @@ -11,7 +11,7 @@ type BipartiteGraph struct { Edges EdgeSet } -func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) { +func NewBipartiteGraph(leftValues, rightValues []any, neighbours func(any, any) (bool, error)) (*BipartiteGraph, error) { left := NodeOrderedSet{} for i, v := range leftValues { left = append(left, Node{ID: i, Value: v}) @@ -41,7 +41,7 @@ func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(in // FreeLeftRight returns left node values and right node values // of the BipartiteGraph's nodes which are not part of the given edges. -func (bg *BipartiteGraph) FreeLeftRight(edges EdgeSet) (leftValues, rightValues []interface{}) { +func (bg *BipartiteGraph) FreeLeftRight(edges EdgeSet) (leftValues, rightValues []any) { for _, node := range bg.Left { if edges.Free(node) { leftValues = append(leftValues, node.Value) diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go index cd597a2f2..66d3578d5 100644 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go +++ b/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go @@ -2,7 +2,7 @@ package node type Node struct { ID int - Value interface{} + Value any } type NodeOrderedSet []Node diff --git a/vendor/github.com/onsi/gomega/matchers/type_support.go b/vendor/github.com/onsi/gomega/matchers/type_support.go index b9440ac7a..d020dedc3 100644 --- a/vendor/github.com/onsi/gomega/matchers/type_support.go +++ b/vendor/github.com/onsi/gomega/matchers/type_support.go @@ -20,16 +20,16 @@ import ( ) type omegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) + Match(actual any) (success bool, err error) + FailureMessage(actual any) (message string) + NegatedFailureMessage(actual any) (message string) } -func isBool(a interface{}) bool { +func isBool(a any) bool { return reflect.TypeOf(a).Kind() == reflect.Bool } -func isNumber(a interface{}) bool { +func isNumber(a any) bool { if a == nil { return false } @@ -37,22 +37,22 @@ func isNumber(a interface{}) bool { return reflect.Int <= kind && kind <= reflect.Float64 } -func isInteger(a interface{}) bool { +func isInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Int <= kind && kind <= reflect.Int64 } -func isUnsignedInteger(a interface{}) bool { +func isUnsignedInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Uint <= kind && kind <= reflect.Uint64 } -func isFloat(a interface{}) bool { +func isFloat(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Float32 <= kind && kind <= reflect.Float64 } -func toInteger(a interface{}) int64 { +func toInteger(a any) int64 { if isInteger(a) { return reflect.ValueOf(a).Int() } else if isUnsignedInteger(a) { @@ -63,7 +63,7 @@ func toInteger(a interface{}) int64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func toUnsignedInteger(a interface{}) uint64 { +func toUnsignedInteger(a any) uint64 { if isInteger(a) { return uint64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { @@ -74,7 +74,7 @@ func toUnsignedInteger(a interface{}) uint64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func toFloat(a interface{}) float64 { +func toFloat(a any) float64 { if isInteger(a) { return float64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { @@ -85,26 +85,26 @@ func toFloat(a interface{}) float64 { panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } -func isError(a interface{}) bool { +func isError(a any) bool { _, ok := a.(error) return ok } -func isChan(a interface{}) bool { +func isChan(a any) bool { if isNil(a) { return false } return reflect.TypeOf(a).Kind() == reflect.Chan } -func isMap(a interface{}) bool { +func isMap(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.Map } -func isArrayOrSlice(a interface{}) bool { +func isArrayOrSlice(a any) bool { if a == nil { return false } @@ -116,14 +116,14 @@ func isArrayOrSlice(a interface{}) bool { } } -func isString(a interface{}) bool { +func isString(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.String } -func toString(a interface{}) (string, bool) { +func toString(a any) (string, bool) { aString, isString := a.(string) if isString { return aString, true @@ -147,7 +147,7 @@ func toString(a interface{}) (string, bool) { return "", false } -func lengthOf(a interface{}) (int, bool) { +func lengthOf(a any) (int, bool) { if a == nil { return 0, false } @@ -169,7 +169,7 @@ func lengthOf(a interface{}) (int, bool) { return 0, false } } -func capOf(a interface{}) (int, bool) { +func capOf(a any) (int, bool) { if a == nil { return 0, false } @@ -181,7 +181,7 @@ func capOf(a interface{}) (int, bool) { } } -func isNil(a interface{}) bool { +func isNil(a any) bool { if a == nil { return true } diff --git a/vendor/github.com/onsi/gomega/matchers/with_transform.go b/vendor/github.com/onsi/gomega/matchers/with_transform.go index 6f743b1b3..6231c3b47 100644 --- a/vendor/github.com/onsi/gomega/matchers/with_transform.go +++ b/vendor/github.com/onsi/gomega/matchers/with_transform.go @@ -9,20 +9,20 @@ import ( type WithTransformMatcher struct { // input - Transform interface{} // must be a function of one parameter that returns one value and an optional error + Transform any // must be a function of one parameter that returns one value and an optional error Matcher types.GomegaMatcher // cached value transformArgType reflect.Type // state - transformedValue interface{} + transformedValue any } // reflect.Type for error var errorT = reflect.TypeOf((*error)(nil)).Elem() -func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher { +func NewWithTransformMatcher(transform any, matcher types.GomegaMatcher) *WithTransformMatcher { if transform == nil { panic("transform function cannot be nil") } @@ -43,7 +43,7 @@ func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) } } -func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { +func (m *WithTransformMatcher) Match(actual any) (bool, error) { // prepare a parameter to pass to the Transform function var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.transformArgType) { @@ -72,15 +72,15 @@ func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { return m.Matcher.Match(m.transformedValue) } -func (m *WithTransformMatcher) FailureMessage(_ interface{}) (message string) { +func (m *WithTransformMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.transformedValue) } -func (m *WithTransformMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (m *WithTransformMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.transformedValue) } -func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ interface{}) bool { +func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ any) bool { // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.) // // Querying the next matcher is fine if the transformer always will return the same value. diff --git a/vendor/github.com/onsi/gomega/types/types.go b/vendor/github.com/onsi/gomega/types/types.go index 30f2beed3..685a46f37 100644 --- a/vendor/github.com/onsi/gomega/types/types.go +++ b/vendor/github.com/onsi/gomega/types/types.go @@ -10,20 +10,20 @@ type GomegaFailHandler func(message string, callerSkip ...int) // A simple *testing.T interface wrapper type GomegaTestingT interface { Helper() - Fatalf(format string, args ...interface{}) + Fatalf(format string, args ...any) } -// Gomega represents an object that can perform synchronous and assynchronous assertions with Gomega matchers +// Gomega represents an object that can perform synchronous and asynchronous assertions with Gomega matchers type Gomega interface { - Ω(actual interface{}, extra ...interface{}) Assertion - Expect(actual interface{}, extra ...interface{}) Assertion - ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion + Ω(actual any, extra ...any) Assertion + Expect(actual any, extra ...any) Assertion + ExpectWithOffset(offset int, actual any, extra ...any) Assertion - Eventually(actualOrCtx interface{}, args ...interface{}) AsyncAssertion - EventuallyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion + Eventually(actualOrCtx any, args ...any) AsyncAssertion + EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion - Consistently(actualOrCtx interface{}, args ...interface{}) AsyncAssertion - ConsistentlyWithOffset(offset int, actualOrCtx interface{}, args ...interface{}) AsyncAssertion + Consistently(actualOrCtx any, args ...any) AsyncAssertion + ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion SetDefaultEventuallyTimeout(time.Duration) SetDefaultEventuallyPollingInterval(time.Duration) @@ -37,9 +37,9 @@ type Gomega interface { // // For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers type GomegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) + Match(actual any) (success bool, err error) + FailureMessage(actual any) (message string) + NegatedFailureMessage(actual any) (message string) } /* @@ -52,10 +52,10 @@ For example, a process' exit code can never change. So, gexec's Exit matcher re for `MatchMayChangeInTheFuture` until the process exits, at which point it returns `false` forevermore. */ type OracleMatcher interface { - MatchMayChangeInTheFuture(actual interface{}) bool + MatchMayChangeInTheFuture(actual any) bool } -func MatchMayChangeInTheFuture(matcher GomegaMatcher, value interface{}) bool { +func MatchMayChangeInTheFuture(matcher GomegaMatcher, value any) bool { oracleMatcher, ok := matcher.(OracleMatcher) if !ok { return true @@ -67,8 +67,13 @@ func MatchMayChangeInTheFuture(matcher GomegaMatcher, value interface{}) bool { // AsyncAssertions are returned by Eventually and Consistently and enable matchers to be polled repeatedly to ensure // they are eventually satisfied type AsyncAssertion interface { - Should(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool + Should(matcher GomegaMatcher, optionalDescription ...any) bool + ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool + + // equivalent to above + To(matcher GomegaMatcher, optionalDescription ...any) bool + ToNot(matcher GomegaMatcher, optionalDescription ...any) bool + NotTo(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) AsyncAssertion WithTimeout(interval time.Duration) AsyncAssertion @@ -76,18 +81,18 @@ type AsyncAssertion interface { Within(timeout time.Duration) AsyncAssertion ProbeEvery(interval time.Duration) AsyncAssertion WithContext(ctx context.Context) AsyncAssertion - WithArguments(argsToForward ...interface{}) AsyncAssertion + WithArguments(argsToForward ...any) AsyncAssertion MustPassRepeatedly(count int) AsyncAssertion } // Assertions are returned by Ω and Expect and enable assertions against Gomega matchers type Assertion interface { - Should(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool + Should(matcher GomegaMatcher, optionalDescription ...any) bool + ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool - To(matcher GomegaMatcher, optionalDescription ...interface{}) bool - ToNot(matcher GomegaMatcher, optionalDescription ...interface{}) bool - NotTo(matcher GomegaMatcher, optionalDescription ...interface{}) bool + To(matcher GomegaMatcher, optionalDescription ...any) bool + ToNot(matcher GomegaMatcher, optionalDescription ...any) bool + NotTo(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) Assertion diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore new file mode 100644 index 000000000..c7b459e4d --- /dev/null +++ b/vendor/github.com/spf13/cobra/.gitignore @@ -0,0 +1,39 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + +*.exe +cobra.test +bin + +.idea/ +*.iml diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml new file mode 100644 index 000000000..2c8f4808c --- /dev/null +++ b/vendor/github.com/spf13/cobra/.golangci.yml @@ -0,0 +1,57 @@ +# Copyright 2013-2023 The Cobra Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +run: + deadline: 5m + +linters: + disable-all: true + enable: + #- bodyclose + # - deadcode ! deprecated since v1.49.0; replaced by 'unused' + #- depguard + #- dogsled + #- dupl + - errcheck + #- exhaustive + #- funlen + #- gochecknoinits + - goconst + - gocritic + #- gocyclo + - gofmt + - goimports + #- gomnd + #- goprintffuncname + - gosec + - gosimple + - govet + - ineffassign + #- lll + - misspell + #- nakedret + #- noctx + - nolintlint + #- rowserrcheck + #- scopelint + - staticcheck + #- structcheck ! deprecated since v1.49.0; replaced by 'unused' + - stylecheck + #- typecheck + - unconvert + #- unparam + - unused + # - varcheck ! deprecated since v1.49.0; replaced by 'unused' + #- whitespace + fast: false diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap new file mode 100644 index 000000000..94ec53068 --- /dev/null +++ b/vendor/github.com/spf13/cobra/.mailmap @@ -0,0 +1,3 @@ +Steve Francia +Bjørn Erik Pedersen +Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md new file mode 100644 index 000000000..9d16f88fd --- /dev/null +++ b/vendor/github.com/spf13/cobra/CONDUCT.md @@ -0,0 +1,37 @@ +## Cobra User Contract + +### Versioning +Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release. + +### Backward Compatibility +We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released. + +### Deprecation +Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github. + +### CVE +Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one. + +### Communication +Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors. + +### Breaking Changes +Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra. + +There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version. + +Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release. + +Examples of breaking changes include: +- Removing or renaming exported constant, variable, type, or function. +- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc... + - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing. + +There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging. + +### CI Testing +Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang. + +### Disclaimer +Changes to this document and the contents therein are at the discretion of the maintainers. +None of the contents of this document are legally binding in any way to the maintainers or the users. diff --git a/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/vendor/github.com/spf13/cobra/CONTRIBUTING.md new file mode 100644 index 000000000..6f356e6a8 --- /dev/null +++ b/vendor/github.com/spf13/cobra/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing to Cobra + +Thank you so much for contributing to Cobra. We appreciate your time and help. +Here are some guidelines to help you get started. + +## Code of Conduct + +Be kind and respectful to the members of the community. Take time to educate +others who are seeking help. Harassment of any kind will not be tolerated. + +## Questions + +If you have questions regarding Cobra, feel free to ask it in the community +[#cobra Slack channel][cobra-slack] + +## Filing a bug or feature + +1. Before filing an issue, please check the existing issues to see if a + similar one was already opened. If there is one already opened, feel free + to comment on it. +1. If you believe you've found a bug, please provide detailed steps of + reproduction, the version of Cobra and anything else you believe will be + useful to help troubleshoot it (e.g. OS environment, environment variables, + etc...). Also state the current behavior vs. the expected behavior. +1. If you'd like to see a feature or an enhancement please open an issue with + a clear title and description of what the feature is and why it would be + beneficial to the project and its users. + +## Submitting changes + +1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to + sign a CLA. Please sign the CLA :slightly_smiling_face: +1. Tests: If you are submitting code, please ensure you have adequate tests + for the feature. Tests can be run via `go test ./...` or `make test`. +1. Since this is golang project, ensure the new code is properly formatted to + ensure code consistency. Run `make all`. + +### Quick steps to contribute + +1. Fork the project. +1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) +1. Create your feature branch (`git checkout -b my-new-feature`) +1. Make changes and run tests (`make test`) +1. Add them to staging (`git add .`) +1. Commit your changes (`git commit -m 'Add some feature'`) +1. Push to the branch (`git push origin my-new-feature`) +1. Create new pull request + + +[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199 diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt new file mode 100644 index 000000000..298f0e266 --- /dev/null +++ b/vendor/github.com/spf13/cobra/LICENSE.txt @@ -0,0 +1,174 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/vendor/github.com/spf13/cobra/MAINTAINERS b/vendor/github.com/spf13/cobra/MAINTAINERS new file mode 100644 index 000000000..4c5ac3dd9 --- /dev/null +++ b/vendor/github.com/spf13/cobra/MAINTAINERS @@ -0,0 +1,13 @@ +maintainers: +- spf13 +- johnSchnake +- jpmcb +- marckhouzam +inactive: +- anthonyfok +- bep +- bogem +- broady +- eparis +- jharshman +- wfernandes diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile new file mode 100644 index 000000000..0da8d7aa0 --- /dev/null +++ b/vendor/github.com/spf13/cobra/Makefile @@ -0,0 +1,35 @@ +BIN="./bin" +SRC=$(shell find . -name "*.go") + +ifeq (, $(shell which golangci-lint)) +$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") +endif + +.PHONY: fmt lint test install_deps clean + +default: all + +all: fmt test + +fmt: + $(info ******************** checking formatting ********************) + @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) + +lint: + $(info ******************** running lint tools ********************) + golangci-lint run -v + +test: install_deps + $(info ******************** running tests ********************) + go test -v ./... + +richtest: install_deps + $(info ******************** running tests with kyoh86/richgo ********************) + richgo test -v ./... + +install_deps: + $(info ******************** downloading dependencies ********************) + go get -v ./... + +clean: + rm -rf $(BIN) diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md new file mode 100644 index 000000000..71757151c --- /dev/null +++ b/vendor/github.com/spf13/cobra/README.md @@ -0,0 +1,113 @@ + +![cobra logo](https://github.com/user-attachments/assets/cbc3adf8-0dff-46e9-a88d-5e2d971c169e) + +Cobra is a library for creating powerful modern CLI applications. + +Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), +[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to +name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. + +[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) +[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) +[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) + +# Overview + +Cobra is a library providing a simple interface to create powerful modern CLI +interfaces similar to git & go tools. + +Cobra provides: +* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. +* Fully POSIX-compliant flags (including short & long versions) +* Nested subcommands +* Global, local and cascading flags +* Intelligent suggestions (`app srver`... did you mean `app server`?) +* Automatic help generation for commands and flags +* Grouping help for subcommands +* Automatic help flag recognition of `-h`, `--help`, etc. +* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) +* Automatically generated man pages for your application +* Command aliases so you can change things without breaking them +* The flexibility to define your own help, usage, etc. +* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps + +# Concepts + +Cobra is built on a structure of commands, arguments & flags. + +**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. + +The best applications read like sentences when used, and as a result, users +intuitively know how to interact with them. + +The pattern to follow is +`APPNAME VERB NOUN --ADJECTIVE` + or +`APPNAME COMMAND ARG --FLAG`. + +A few good real world examples may better illustrate this point. + +In the following example, 'server' is a command, and 'port' is a flag: + + hugo server --port=1313 + +In this command we are telling Git to clone the url bare. + + git clone URL --bare + +## Commands + +Command is the central point of the application. Each interaction that +the application supports will be contained in a Command. A command can +have children commands and optionally run an action. + +In the example above, 'server' is the command. + +[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command) + +## Flags + +A flag is a way to modify the behavior of a command. Cobra supports +fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). +A Cobra command can define flags that persist through to children commands +and flags that are only available to that command. + +In the example above, 'port' is the flag. + +Flag functionality is provided by the [pflag +library](https://github.com/spf13/pflag), a fork of the flag standard library +which maintains the same interface while adding POSIX compliance. + +# Installing +Using Cobra is easy. First, use `go get` to install the latest version +of the library. + +``` +go get -u github.com/spf13/cobra@latest +``` + +Next, include Cobra in your application: + +```go +import "github.com/spf13/cobra" +``` + +# Usage +`cobra-cli` is a command line program to generate cobra applications and command files. +It will bootstrap your application scaffolding to rapidly +develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application. + +It can be installed by running: + +``` +go install github.com/spf13/cobra-cli@latest +``` + +For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) + +For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md). + +# License + +Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go new file mode 100644 index 000000000..b3e2dadfe --- /dev/null +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -0,0 +1,60 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "os" +) + +const ( + activeHelpMarker = "_activeHelp_ " + // The below values should not be changed: programs will be using them explicitly + // in their user documentation, and users will be using them explicitly. + activeHelpEnvVarSuffix = "ACTIVE_HELP" + activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix + activeHelpGlobalDisable = "0" +) + +// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. +// Such strings will be processed by the completion script and will be shown as ActiveHelp +// to the user. +// The array parameter should be the array that will contain the completions. +// This function can be called multiple times before and/or after completions are added to +// the array. Each time this function is called with the same array, the new +// ActiveHelp line will be shown below the previous ones when completion is triggered. +func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion { + return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) +} + +// GetActiveHelpConfig returns the value of the ActiveHelp environment variable +// _ACTIVE_HELP where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP +// is set to "0". +func GetActiveHelpConfig(cmd *Command) string { + activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar) + if activeHelpCfg != activeHelpGlobalDisable { + activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name())) + } + return activeHelpCfg +} + +// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment +// variable. It has the format _ACTIVE_HELP where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func activeHelpEnvVar(name string) string { + return configEnvVar(name, activeHelpEnvVarSuffix) +} diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go new file mode 100644 index 000000000..ed1e70cea --- /dev/null +++ b/vendor/github.com/spf13/cobra/args.go @@ -0,0 +1,131 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "strings" +) + +type PositionalArgs func(cmd *Command, args []string) error + +// legacyArgs validation has the following behaviour: +// - root commands with no subcommands can take arbitrary arguments +// - root commands with subcommands will do subcommand validity checking +// - subcommands will always accept arbitrary arguments +func legacyArgs(cmd *Command, args []string) error { + // no subcommand, always take args + if !cmd.HasSubCommands() { + return nil + } + + // root command with subcommands, do subcommand checking. + if !cmd.HasParent() && len(args) > 0 { + return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + return nil +} + +// NoArgs returns an error if any args are included. +func NoArgs(cmd *Command, args []string) error { + if len(args) > 0 { + return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) + } + return nil +} + +// OnlyValidArgs returns an error if there are any positional args that are not in +// the `ValidArgs` field of `Command` +func OnlyValidArgs(cmd *Command, args []string) error { + if len(cmd.ValidArgs) > 0 { + // Remove any description that may be included in ValidArgs. + // A description is following a tab character. + validArgs := make([]string, 0, len(cmd.ValidArgs)) + for _, v := range cmd.ValidArgs { + validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0]) + } + for _, v := range args { + if !stringInSlice(v, validArgs) { + return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + } + } + return nil +} + +// ArbitraryArgs never returns an error. +func ArbitraryArgs(cmd *Command, args []string) error { + return nil +} + +// MinimumNArgs returns an error if there is not at least N args. +func MinimumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < n { + return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) + } + return nil + } +} + +// MaximumNArgs returns an error if there are more than N args. +func MaximumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) > n { + return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// ExactArgs returns an error if there are not exactly n args. +func ExactArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) != n { + return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// RangeArgs returns an error if the number of args is not within the expected range. +func RangeArgs(min int, max int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < min || len(args) > max { + return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) + } + return nil + } +} + +// MatchAll allows combining several PositionalArgs to work in concert. +func MatchAll(pargs ...PositionalArgs) PositionalArgs { + return func(cmd *Command, args []string) error { + for _, parg := range pargs { + if err := parg(cmd, args); err != nil { + return err + } + } + return nil + } +} + +// ExactValidArgs returns an error if there are not exactly N positional args OR +// there are any positional args that are not in the `ValidArgs` field of `Command` +// +// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead +func ExactValidArgs(n int) PositionalArgs { + return MatchAll(ExactArgs(n), OnlyValidArgs) +} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go new file mode 100644 index 000000000..f4d198cbc --- /dev/null +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -0,0 +1,709 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "sort" + "strings" + + "github.com/spf13/pflag" +) + +// Annotations for Bash completion. +const ( + BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" + BashCompCustom = "cobra_annotation_bash_completion_custom" + BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" + BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" +) + +func writePreamble(buf io.StringWriter, name string) { + WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(` +__%[1]s_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +# Homebrew on Macs have version 1.3 of bash-completion which doesn't include +# _init_completion. This is a very minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +__%[1]s_index_of_word() +{ + local w word=$1 + shift + index=0 + for w in "$@"; do + [[ $w = "$word" ]] && return + index=$((index+1)) + done + index=-1 +} + +__%[1]s_contains_word() +{ + local w word=$1; shift + for w in "$@"; do + [[ $w = "$word" ]] && return + done + return 1 +} + +__%[1]s_handle_go_custom_completion() +{ + __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" + + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + + local out requestComp lastParam lastChar comp directive args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows handling aliases + args=("${words[@]:1}") + # Disable ActiveHelp which is not supported for bash completion v1 + requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" + __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + # Error code. No completion. + __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" + return + else + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no space" + compopt -o nospace + fi + fi + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" + compopt +o default + fi + fi + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local fullFilter filter filteringCmd + # Do not use quotes around the $out variable or else newline + # characters will be kept. + for filter in ${out}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __%[1]s_debug "File filtering command: $filteringCmd" + $filteringCmd + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subdir + # Use printf to strip any trailing newline + subdir=$(printf "%%s" "${out}") + if [ -n "$subdir" ]; then + __%[1]s_debug "Listing directories in $subdir" + __%[1]s_handle_subdirs_in_dir_flag "$subdir" + else + __%[1]s_debug "Listing directories in ." + _filedir -d + fi + else + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${out}" -- "$cur") + fi +} + +__%[1]s_handle_reply() +{ + __%[1]s_debug "${FUNCNAME[0]}" + local comp + case $cur in + -*) + if [[ $(type -t compopt) = "builtin" ]]; then + compopt -o nospace + fi + local allflags + if [ ${#must_have_one_flag[@]} -ne 0 ]; then + allflags=("${must_have_one_flag[@]}") + else + allflags=("${flags[*]} ${two_word_flags[*]}") + fi + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${allflags[*]}" -- "$cur") + if [[ $(type -t compopt) = "builtin" ]]; then + [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace + fi + + # complete after --flag=abc + if [[ $cur == *=* ]]; then + if [[ $(type -t compopt) = "builtin" ]]; then + compopt +o nospace + fi + + local index flag + flag="${cur%%=*}" + __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" + COMPREPLY=() + if [[ ${index} -ge 0 ]]; then + PREFIX="" + cur="${cur#*=}" + ${flags_completion[${index}]} + if [ -n "${ZSH_VERSION:-}" ]; then + # zsh completion needs --flag= prefix + eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" + fi + fi + fi + + if [[ -z "${flag_parsing_disabled}" ]]; then + # If flag parsing is enabled, we have completed the flags and can return. + # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough + # to possibly call handle_go_custom_completion. + return 0; + fi + ;; + esac + + # check if we are handling a flag with special work handling + local index + __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" + if [[ ${index} -ge 0 ]]; then + ${flags_completion[${index}]} + return + fi + + # we are parsing a flag and don't have a special handler, no completion + if [[ ${cur} != "${words[cword]}" ]]; then + return + fi + + local completions + completions=("${commands[@]}") + if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then + completions+=("${must_have_one_noun[@]}") + elif [[ -n "${has_completion_function}" ]]; then + # if a go completion function is provided, defer to that function + __%[1]s_handle_go_custom_completion + fi + if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then + completions+=("${must_have_one_flag[@]}") + fi + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${completions[*]}" -- "$cur") + + if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${noun_aliases[*]}" -- "$cur") + fi + + if [[ ${#COMPREPLY[@]} -eq 0 ]]; then + if declare -F __%[1]s_custom_func >/dev/null; then + # try command name qualified custom func + __%[1]s_custom_func + else + # otherwise fall back to unqualified for compatibility + declare -F __custom_func >/dev/null && __custom_func + fi + fi + + # available in bash-completion >= 2, not always present on macOS + if declare -F __ltrim_colon_completions >/dev/null; then + __ltrim_colon_completions "$cur" + fi + + # If there is only 1 completion and it is a flag with an = it will be completed + # but we don't want a space after the = + if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then + compopt -o nospace + fi +} + +# The arguments should be in the form "ext1|ext2|extn" +__%[1]s_handle_filename_extension_flag() +{ + local ext="$1" + _filedir "@(${ext})" +} + +__%[1]s_handle_subdirs_in_dir_flag() +{ + local dir="$1" + pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return +} + +__%[1]s_handle_flag() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + # if a command required a flag, and we found it, unset must_have_one_flag() + local flagname=${words[c]} + local flagvalue="" + # if the word contained an = + if [[ ${words[c]} == *"="* ]]; then + flagvalue=${flagname#*=} # take in as flagvalue after the = + flagname=${flagname%%=*} # strip everything after the = + flagname="${flagname}=" # but put the = back + fi + __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" + if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then + must_have_one_flag=() + fi + + # if you set a flag which only applies to this command, don't show subcommands + if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then + commands=() + fi + + # keep flag value with flagname as flaghash + # flaghash variable is an associative array which is only supported in bash > 3. + if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then + if [ -n "${flagvalue}" ] ; then + flaghash[${flagname}]=${flagvalue} + elif [ -n "${words[ $((c+1)) ]}" ] ; then + flaghash[${flagname}]=${words[ $((c+1)) ]} + else + flaghash[${flagname}]="true" # pad "true" for bool flag + fi + fi + + # skip the argument to a two word flag + if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then + __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" + c=$((c+1)) + # if we are looking for a flags value, don't show commands + if [[ $c -eq $cword ]]; then + commands=() + fi + fi + + c=$((c+1)) + +} + +__%[1]s_handle_noun() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then + must_have_one_noun=() + elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then + must_have_one_noun=() + fi + + nouns+=("${words[c]}") + c=$((c+1)) +} + +__%[1]s_handle_command() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + local next_command + if [[ -n ${last_command} ]]; then + next_command="_${last_command}_${words[c]//:/__}" + else + if [[ $c -eq 0 ]]; then + next_command="_%[1]s_root_command" + else + next_command="_${words[c]//:/__}" + fi + fi + c=$((c+1)) + __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" + declare -F "$next_command" >/dev/null && $next_command +} + +__%[1]s_handle_word() +{ + if [[ $c -ge $cword ]]; then + __%[1]s_handle_reply + return + fi + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + if [[ "${words[c]}" == -* ]]; then + __%[1]s_handle_flag + elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then + __%[1]s_handle_command + elif [[ $c -eq 0 ]]; then + __%[1]s_handle_command + elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then + # aliashash variable is an associative array which is only supported in bash > 3. + if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then + words[c]=${aliashash[${words[c]}]} + __%[1]s_handle_command + else + __%[1]s_handle_noun + fi + else + __%[1]s_handle_noun + fi + __%[1]s_handle_word +} + +`, name, ShellCompNoDescRequestCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) +} + +func writePostscript(buf io.StringWriter, name string) { + name = strings.ReplaceAll(name, ":", "__") + WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(`{ + local cur prev words cword split + declare -A flaghash 2>/dev/null || : + declare -A aliashash 2>/dev/null || : + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -s || return + else + __%[1]s_init_completion -n "=" || return + fi + + local c=0 + local flag_parsing_disabled= + local flags=() + local two_word_flags=() + local local_nonpersistent_flags=() + local flags_with_completion=() + local flags_completion=() + local commands=("%[1]s") + local command_aliases=() + local must_have_one_flag=() + local must_have_one_noun=() + local has_completion_function="" + local last_command="" + local nouns=() + local noun_aliases=() + + __%[1]s_handle_word +} + +`, name)) + WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%s %s +else + complete -o default -o nospace -F __start_%s %s +fi + +`, name, name, name, name)) + WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n") +} + +func writeCommands(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " commands=()\n") + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() && c != cmd.helpCommand { + continue + } + WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name())) + writeCmdAliases(buf, c) + } + WriteStringAndCheck(buf, "\n") +} + +func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) { + for key, value := range annotations { + switch key { + case BashCompFilenameExt: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + var ext string + if len(value) > 0 { + ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") + } else { + ext = "_filedir" + } + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) + case BashCompCustom: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + if len(value) > 0 { + handlers := strings.Join(value, "; ") + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) + } else { + WriteStringAndCheck(buf, " flags_completion+=(:)\n") + } + case BashCompSubdirsInDir: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + var ext string + if len(value) == 1 { + ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] + } else { + ext = "_filedir -d" + } + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) + } + } +} + +const cbn = "\")\n" + +func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { + name := flag.Shorthand + format := " " + if len(flag.NoOptDefVal) == 0 { + format += "two_word_" + } + format += "flags+=(\"-%s" + cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) +} + +func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { + name := flag.Name + format := " flags+=(\"--%s" + if len(flag.NoOptDefVal) == 0 { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + if len(flag.NoOptDefVal) == 0 { + format = " two_word_flags+=(\"--%s" + cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + } + writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) +} + +func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { + name := flag.Name + format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn + if len(flag.NoOptDefVal) == 0 { + format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn + } + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) + } +} + +// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags +func prepareCustomAnnotationsForFlags(cmd *Command) { + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + for flag := range flagCompletionFunctions { + // Make sure the completion script calls the __*_go_custom_completion function for + // every registered flag. We need to do this here (and not when the flag was registered + // for completion) so that we can know the root command name for the prefix + // of ___go_custom_completion + if flag.Annotations == nil { + flag.Annotations = map[string][]string{} + } + flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} + } +} + +func writeFlags(buf io.StringWriter, cmd *Command) { + prepareCustomAnnotationsForFlags(cmd) + WriteStringAndCheck(buf, ` flags=() + two_word_flags=() + local_nonpersistent_flags=() + flags_with_completion=() + flags_completion=() + +`) + + if cmd.DisableFlagParsing { + WriteStringAndCheck(buf, " flag_parsing_disabled=1\n") + } + + localNonPersistentFlags := cmd.LocalNonPersistentFlags() + cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) + if len(flag.Shorthand) > 0 { + writeShortFlag(buf, flag, cmd) + } + // localNonPersistentFlags are used to stop the completion of subcommands when one is set + // if TraverseChildren is true we should allow to complete subcommands + if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { + writeLocalNonPersistentFlag(buf, flag) + } + }) + cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) + if len(flag.Shorthand) > 0 { + writeShortFlag(buf, flag, cmd) + } + }) + + WriteStringAndCheck(buf, "\n") +} + +func writeRequiredFlag(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " must_have_one_flag=()\n") + flags := cmd.NonInheritedFlags() + flags.VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok { + format := " must_have_one_flag+=(\"--%s" + if flag.Value.Type() != "bool" { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) + + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) + } + } + }) +} + +func writeRequiredNouns(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " must_have_one_noun=()\n") + sort.Strings(cmd.ValidArgs) + for _, value := range cmd.ValidArgs { + // Remove any description that may be included following a tab character. + // Descriptions are not supported by bash completion. + value = strings.SplitN(value, "\t", 2)[0] + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) + } + if cmd.ValidArgsFunction != nil { + WriteStringAndCheck(buf, " has_completion_function=1\n") + } +} + +func writeCmdAliases(buf io.StringWriter, cmd *Command) { + if len(cmd.Aliases) == 0 { + return + } + + sort.Strings(cmd.Aliases) + + WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n")) + for _, value := range cmd.Aliases { + WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value)) + WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) + } + WriteStringAndCheck(buf, ` fi`) + WriteStringAndCheck(buf, "\n") +} +func writeArgAliases(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " noun_aliases=()\n") + sort.Strings(cmd.ArgAliases) + for _, value := range cmd.ArgAliases { + WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value)) + } +} + +func gen(buf io.StringWriter, cmd *Command) { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() && c != cmd.helpCommand { + continue + } + gen(buf, c) + } + commandName := cmd.CommandPath() + commandName = strings.ReplaceAll(commandName, " ", "_") + commandName = strings.ReplaceAll(commandName, ":", "__") + + if cmd.Root() == cmd { + WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) + } else { + WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName)) + } + + WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName)) + WriteStringAndCheck(buf, "\n") + WriteStringAndCheck(buf, " command_aliases=()\n") + WriteStringAndCheck(buf, "\n") + + writeCommands(buf, cmd) + writeFlags(buf, cmd) + writeRequiredFlag(buf, cmd) + writeRequiredNouns(buf, cmd) + writeArgAliases(buf, cmd) + WriteStringAndCheck(buf, "}\n\n") +} + +// GenBashCompletion generates bash completion file and writes to the passed writer. +func (c *Command) GenBashCompletion(w io.Writer) error { + buf := new(bytes.Buffer) + writePreamble(buf, c.Name()) + if len(c.BashCompletionFunction) > 0 { + buf.WriteString(c.BashCompletionFunction + "\n") + } + gen(buf, c) + writePostscript(buf, c.Name()) + + _, err := buf.WriteTo(w) + return err +} + +func nonCompletableFlag(flag *pflag.Flag) bool { + return flag.Hidden || len(flag.Deprecated) > 0 +} + +// GenBashCompletionFile generates bash completion file. +func (c *Command) GenBashCompletionFile(filename string) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenBashCompletion(outFile) +} diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go new file mode 100644 index 000000000..d2397aa36 --- /dev/null +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -0,0 +1,484 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genBashComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func genBashComp(buf io.StringWriter, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + + WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +# This function calls the %[1]s program to obtain the completion +# results and the directive. It fills the 'out' and 'directive' vars. +__%[1]s_get_completion_results() { + local requestComp lastParam lastChar args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows handling aliases + args=("${words[@]:1}") + requestComp="${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" + + if [[ -z ${cur} && ${lastChar} != = ]]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "Adding extra empty parameter" + requestComp="${requestComp} ''" + fi + + # When completing a flag with an = (e.g., %[1]s -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ ${cur} == -*=* ]]; then + cur="${cur#*=}" + fi + + __%[1]s_debug "Calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [[ ${directive} == "${out}" ]]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "The completion directive is: ${directive}" + __%[1]s_debug "The completions are: ${out}" +} + +__%[1]s_process_completion_results() { + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d + + if (((directive & shellCompDirectiveError) != 0)); then + # Error code. No completion. + __%[1]s_debug "Received error from custom completion go code" + return + else + if (((directive & shellCompDirectiveNoSpace) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + __%[1]s_debug "Activating no space" + compopt -o nospace + else + __%[1]s_debug "No space directive not supported in this version of bash" + fi + fi + if (((directive & shellCompDirectiveKeepOrder) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + # no sort isn't supported for bash less than < 4.4 + if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then + __%[1]s_debug "No sort directive not supported in this version of bash" + else + __%[1]s_debug "Activating keep order" + compopt -o nosort + fi + else + __%[1]s_debug "No sort directive not supported in this version of bash" + fi + fi + if (((directive & shellCompDirectiveNoFileComp) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + __%[1]s_debug "Activating no file completion" + compopt +o default + else + __%[1]s_debug "No file completion directive not supported in this version of bash" + fi + fi + fi + + # Separate activeHelp from normal completions + local completions=() + local activeHelp=() + __%[1]s_extract_activeHelp + + if (((directive & shellCompDirectiveFilterFileExt) != 0)); then + # File extension filtering + local fullFilter="" filter filteringCmd + + # Do not use quotes around the $completions variable or else newline + # characters will be kept. + for filter in ${completions[*]}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __%[1]s_debug "File filtering command: $filteringCmd" + $filteringCmd + elif (((directive & shellCompDirectiveFilterDirs) != 0)); then + # File completion for directories only + + local subdir + subdir=${completions[0]} + if [[ -n $subdir ]]; then + __%[1]s_debug "Listing directories in $subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return + else + __%[1]s_debug "Listing directories in ." + _filedir -d + fi + else + __%[1]s_handle_completion_types + fi + + __%[1]s_handle_special_char "$cur" : + __%[1]s_handle_special_char "$cur" = + + # Print the activeHelp statements before we finish + __%[1]s_handle_activeHelp +} + +__%[1]s_handle_activeHelp() { + # Print the activeHelp statements + if ((${#activeHelp[*]} != 0)); then + if [ -z $COMP_TYPE ]; then + # Bash v3 does not set the COMP_TYPE variable. + printf "\n"; + printf "%%s\n" "${activeHelp[@]}" + printf "\n" + __%[1]s_reprint_commandLine + return + fi + + # Only print ActiveHelp on the second TAB press + if [ $COMP_TYPE -eq 63 ]; then + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + if ((${#COMPREPLY[*]} == 0)); then + # When there are no completion choices from the program, file completion + # may kick in if the program has not disabled it; in such a case, we want + # to know if any files will match what the user typed, so that we know if + # there will be completions presented, so that we know how to handle ActiveHelp. + # To find out, we actually trigger the file completion ourselves; + # the call to _filedir will fill COMPREPLY if files match. + if (((directive & shellCompDirectiveNoFileComp) == 0)); then + __%[1]s_debug "Listing files" + _filedir + fi + fi + + if ((${#COMPREPLY[*]} != 0)); then + # If there are completion choices to be shown, print a delimiter. + # Re-printing the command-line will automatically be done + # by the shell when it prints the completion choices. + printf -- "--" + else + # When there are no completion choices at all, we need + # to re-print the command-line since the shell will + # not be doing it itself. + __%[1]s_reprint_commandLine + fi + elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then + # For completion type: menu-complete/menu-complete-backward and insert-completions + # the completions are immediately inserted into the command-line, so we first + # print the activeHelp message and reprint the command-line since the shell won't. + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + __%[1]s_reprint_commandLine + fi + fi +} + +__%[1]s_reprint_commandLine() { + # The prompt format is only available from bash 4.4. + # We test if it is available before using it. + if (x=${PS1@P}) 2> /dev/null; then + printf "%%s" "${PS1@P}${COMP_LINE[@]}" + else + # Can't print the prompt. Just print the + # text the user had typed, it is workable enough. + printf "%%s" "${COMP_LINE[@]}" + fi +} + +# Separate activeHelp lines from real completions. +# Fills the $activeHelp and $completions arrays. +__%[1]s_extract_activeHelp() { + local activeHelpMarker="%[9]s" + local endIndex=${#activeHelpMarker} + + while IFS='' read -r comp; do + [[ -z $comp ]] && continue + + if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then + comp=${comp:endIndex} + __%[1]s_debug "ActiveHelp found: $comp" + if [[ -n $comp ]]; then + activeHelp+=("$comp") + fi + else + # Not an activeHelp line but a normal completion + completions+=("$comp") + fi + done <<<"${out}" +} + +__%[1]s_handle_completion_types() { + __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE" + + case $COMP_TYPE in + 37|42) + # Type: menu-complete/menu-complete-backward and insert-completions + # If the user requested inserting one completion at a time, or all + # completions at once on the command-line we must remove the descriptions. + # https://github.com/spf13/cobra/issues/1508 + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 + + local tab=$'\t' + + # Strip any description and escape the completion to handled special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}") + + # Only consider the completions that match + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so we need to escape all completions again since they will + # all be inserted on the command-line. + IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}") + ;; + + *) + # Type: complete (normal completion) + __%[1]s_handle_standard_completion_case + ;; + esac +} + +__%[1]s_handle_standard_completion_case() { + local tab=$'\t' + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 + + # Short circuit to optimize if we don't have descriptions + if [[ "${completions[*]}" != *$tab* ]]; then + # First, escape the completions to handle special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}") + # Only consider the completions that match what the user typed + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so, if there is only a single completion, we need to + # escape it again because it will be inserted on the command-line. If there are multiple + # completions, we don't want to escape them because they will be printed in a list + # and we don't want to show escape characters in that list. + if (( ${#COMPREPLY[@]} == 1 )); then + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}") + fi + return 0 + fi + + local longest=0 + local compline + # Look for the longest completion so that we can format things nicely + while IFS='' read -r compline; do + [[ -z $compline ]] && continue + + # Before checking if the completion matches what the user typed, + # we need to strip any description and escape the completion to handle special + # characters because those escape characters are part of what the user typed. + # Don't call "printf" in a sub-shell because it will be much slower + # since we are in a loop. + printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}") + + # Only consider the completions that match + [[ $comp == "$cur"* ]] || continue + + # The completions matches. Add it to the list of full completions including + # its description. We don't escape the completion because it may get printed + # in a list if there are more than one and we don't want show escape characters + # in that list. + COMPREPLY+=("$compline") + + # Strip any description before checking the length, and again, don't escape + # the completion because this length is only used when printing the completions + # in a list and we don't want show escape characters in that list. + comp=${compline%%%%$tab*} + if ((${#comp}>longest)); then + longest=${#comp} + fi + done < <(printf "%%s\n" "${completions[@]}") + + # If there is a single completion left, remove the description text and escape any special characters + if ((${#COMPREPLY[*]} == 1)); then + __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}") + __%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}" + else + # Format the descriptions + __%[1]s_format_comp_descriptions $longest + fi +} + +__%[1]s_handle_special_char() +{ + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while ((--idx >= 0)); do + COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} + done + fi +} + +__%[1]s_format_comp_descriptions() +{ + local tab=$'\t' + local comp desc maxdesclength + local longest=$1 + + local i ci + for ci in ${!COMPREPLY[*]}; do + comp=${COMPREPLY[ci]} + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + __%[1]s_debug "Original comp: $comp" + desc=${comp#*$tab} + comp=${comp%%%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if ((maxdesclength > 8)); then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done + else + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) + fi + + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if ((maxdesclength > 0)); then + if ((${#desc} > maxdesclength)); then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" + fi + COMPREPLY[ci]=$comp + __%[1]s_debug "Final comp: $comp" + fi + done +} + +__start_%[1]s() +{ + local cur prev words cword split + + COMPREPLY=() + + # Call _init_completion from the bash-completion package + # to prepare the arguments properly + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n =: || return + else + __%[1]s_init_completion -n =: || return + fi + + __%[1]s_debug + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," + + local out directive + __%[1]s_get_completion_results + __%[1]s_process_completion_results +} + +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%[1]s %[1]s +else + complete -o default -o nospace -F __start_%[1]s %[1]s +fi + +# ex: ts=4 sw=4 et filetype=sh +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, + activeHelpMarker)) +} + +// GenBashCompletionFileV2 generates Bash completion version 2. +func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenBashCompletionV2(outFile, includeDesc) +} + +// GenBashCompletionV2 generates Bash completion file version 2 +// and writes it to the passed writer. +func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { + return c.genBashCompletion(w, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go new file mode 100644 index 000000000..d9cd2414e --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -0,0 +1,246 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Commands similar to git, go tools and other modern CLI tools +// inspired by go, go-Commander, gh and subcommand + +package cobra + +import ( + "fmt" + "io" + "os" + "reflect" + "strconv" + "strings" + "text/template" + "time" + "unicode" +) + +var templateFuncs = template.FuncMap{ + "trim": strings.TrimSpace, + "trimRightSpace": trimRightSpace, + "trimTrailingWhitespaces": trimRightSpace, + "appendIfNotPresent": appendIfNotPresent, + "rpad": rpad, + "gt": Gt, + "eq": Eq, +} + +var initializers []func() +var finalizers []func() + +const ( + defaultPrefixMatching = false + defaultCommandSorting = true + defaultCaseInsensitive = false + defaultTraverseRunHooks = false +) + +// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing +// to automatically enable in CLI tools. +// Set this to true to enable it. +var EnablePrefixMatching = defaultPrefixMatching + +// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. +// To disable sorting, set it to false. +var EnableCommandSorting = defaultCommandSorting + +// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) +var EnableCaseInsensitive = defaultCaseInsensitive + +// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. +// By default this is disabled, which means only the first run hook to be found is executed. +var EnableTraverseRunHooks = defaultTraverseRunHooks + +// MousetrapHelpText enables an information splash screen on Windows +// if the CLI is started from explorer.exe. +// To disable the mousetrap, just set this variable to blank string (""). +// Works only on Microsoft Windows. +var MousetrapHelpText = `This is a command line tool. + +You need to open cmd.exe and run it from there. +` + +// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows +// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. +// To disable the mousetrap, just set MousetrapHelpText to blank string (""). +// Works only on Microsoft Windows. +var MousetrapDisplayDuration = 5 * time.Second + +// AddTemplateFunc adds a template function that's available to Usage and Help +// template generation. +func AddTemplateFunc(name string, tmplFunc interface{}) { + templateFuncs[name] = tmplFunc +} + +// AddTemplateFuncs adds multiple template functions that are available to Usage and +// Help template generation. +func AddTemplateFuncs(tmplFuncs template.FuncMap) { + for k, v := range tmplFuncs { + templateFuncs[k] = v + } +} + +// OnInitialize sets the passed functions to be run when each command's +// Execute method is called. +func OnInitialize(y ...func()) { + initializers = append(initializers, y...) +} + +// OnFinalize sets the passed functions to be run when each command's +// Execute method is terminated. +func OnFinalize(y ...func()) { + finalizers = append(finalizers, y...) +} + +// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, +// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as +// ints and then compared. +func Gt(a interface{}, b interface{}) bool { + var left, right int64 + av := reflect.ValueOf(a) + + switch av.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + left = int64(av.Len()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + left = av.Int() + case reflect.String: + left, _ = strconv.ParseInt(av.String(), 10, 64) + } + + bv := reflect.ValueOf(b) + + switch bv.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + right = int64(bv.Len()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + right = bv.Int() + case reflect.String: + right, _ = strconv.ParseInt(bv.String(), 10, 64) + } + + return left > right +} + +// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. +func Eq(a interface{}, b interface{}) bool { + av := reflect.ValueOf(a) + bv := reflect.ValueOf(b) + + switch av.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + panic("Eq called on unsupported type") + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return av.Int() == bv.Int() + case reflect.String: + return av.String() == bv.String() + } + return false +} + +func trimRightSpace(s string) string { + return strings.TrimRightFunc(s, unicode.IsSpace) +} + +// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. +func appendIfNotPresent(s, stringToAppend string) string { + if strings.Contains(s, stringToAppend) { + return s + } + return s + " " + stringToAppend +} + +// rpad adds padding to the right of a string. +func rpad(s string, padding int) string { + formattedString := fmt.Sprintf("%%-%ds", padding) + return fmt.Sprintf(formattedString, s) +} + +func tmpl(text string) *tmplFunc { + return &tmplFunc{ + tmpl: text, + fn: func(w io.Writer, data interface{}) error { + t := template.New("top") + t.Funcs(templateFuncs) + template.Must(t.Parse(text)) + return t.Execute(w, data) + }, + } +} + +// ld compares two strings and returns the levenshtein distance between them. +func ld(s, t string, ignoreCase bool) int { + if ignoreCase { + s = strings.ToLower(s) + t = strings.ToLower(t) + } + d := make([][]int, len(s)+1) + for i := range d { + d[i] = make([]int, len(t)+1) + d[i][0] = i + } + for j := range d[0] { + d[0][j] = j + } + for j := 1; j <= len(t); j++ { + for i := 1; i <= len(s); i++ { + if s[i-1] == t[j-1] { + d[i][j] = d[i-1][j-1] + } else { + min := d[i-1][j] + if d[i][j-1] < min { + min = d[i][j-1] + } + if d[i-1][j-1] < min { + min = d[i-1][j-1] + } + d[i][j] = min + 1 + } + } + + } + return d[len(s)][len(t)] +} + +func stringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} + +// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing. +func CheckErr(msg interface{}) { + if msg != nil { + fmt.Fprintln(os.Stderr, "Error:", msg) + os.Exit(1) + } +} + +// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil. +func WriteStringAndCheck(b io.StringWriter, s string) { + _, err := b.WriteString(s) + CheckErr(err) +} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go new file mode 100644 index 000000000..dbb2c298b --- /dev/null +++ b/vendor/github.com/spf13/cobra/command.go @@ -0,0 +1,2067 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. +// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. +package cobra + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + flag "github.com/spf13/pflag" +) + +const ( + FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" + CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" + + helpFlagName = "help" + helpCommandName = "help" +) + +// FParseErrWhitelist configures Flag parse errors to be ignored +type FParseErrWhitelist flag.ParseErrorsWhitelist + +// Group Structure to manage groups for commands +type Group struct { + ID string + Title string +} + +// Command is just that, a command for your application. +// E.g. 'go run ...' - 'run' is the command. Cobra requires +// you to define the usage and description as part of your command +// definition to ensure usability. +type Command struct { + // Use is the one-line usage message. + // Recommended syntax is as follows: + // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. + // ... indicates that you can specify multiple values for the previous argument. + // | indicates mutually exclusive information. You can use the argument to the left of the separator or the + // argument to the right of the separator. You cannot use both arguments in a single use of the command. + // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are + // optional, they are enclosed in brackets ([ ]). + // Example: add [-F file | -D dir]... [-f format] profile + Use string + + // Aliases is an array of aliases that can be used instead of the first word in Use. + Aliases []string + + // SuggestFor is an array of command names for which this command will be suggested - + // similar to aliases but only suggests. + SuggestFor []string + + // Short is the short description shown in the 'help' output. + Short string + + // The group id under which this subcommand is grouped in the 'help' output of its parent. + GroupID string + + // Long is the long message shown in the 'help ' output. + Long string + + // Example is examples of how to use the command. + Example string + + // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions + ValidArgs []Completion + // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. + // It is a dynamic version of using ValidArgs. + // Only one of ValidArgs and ValidArgsFunction can be used for a command. + ValidArgsFunction CompletionFunc + + // Expected arguments + Args PositionalArgs + + // ArgAliases is List of aliases for ValidArgs. + // These are not suggested to the user in the shell completion, + // but accepted if entered manually. + ArgAliases []string + + // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + // For portability with other shells, it is recommended to instead use ValidArgsFunction + BashCompletionFunction string + + // Deprecated defines, if this command is deprecated and should print this string when used. + Deprecated string + + // Annotations are key/value pairs that can be used by applications to identify or + // group commands or set special options. + Annotations map[string]string + + // Version defines the version for this command. If this value is non-empty and the command does not + // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, + // will print content of the "Version" variable. A shorthand "v" flag will also be added if the + // command does not define one. + Version string + + // The *Run functions are executed in the following order: + // * PersistentPreRun() + // * PreRun() + // * Run() + // * PostRun() + // * PersistentPostRun() + // All functions get the same args, the arguments after the command name. + // The *PreRun and *PostRun functions will only be executed if the Run function of the current + // command has been declared. + // + // PersistentPreRun: children of this command will inherit and execute. + PersistentPreRun func(cmd *Command, args []string) + // PersistentPreRunE: PersistentPreRun but returns an error. + PersistentPreRunE func(cmd *Command, args []string) error + // PreRun: children of this command will not inherit. + PreRun func(cmd *Command, args []string) + // PreRunE: PreRun but returns an error. + PreRunE func(cmd *Command, args []string) error + // Run: Typically the actual work function. Most commands will only implement this. + Run func(cmd *Command, args []string) + // RunE: Run but returns an error. + RunE func(cmd *Command, args []string) error + // PostRun: run after the Run command. + PostRun func(cmd *Command, args []string) + // PostRunE: PostRun but returns an error. + PostRunE func(cmd *Command, args []string) error + // PersistentPostRun: children of this command will inherit and execute after PostRun. + PersistentPostRun func(cmd *Command, args []string) + // PersistentPostRunE: PersistentPostRun but returns an error. + PersistentPostRunE func(cmd *Command, args []string) error + + // groups for subcommands + commandgroups []*Group + + // args is actual args parsed from flags. + args []string + // flagErrorBuf contains all error messages from pflag. + flagErrorBuf *bytes.Buffer + // flags is full set of flags. + flags *flag.FlagSet + // pflags contains persistent flags. + pflags *flag.FlagSet + // lflags contains local flags. + // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call + lflags *flag.FlagSet + // iflags contains inherited flags. + // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call + iflags *flag.FlagSet + // parentsPflags is all persistent flags of cmd's parents. + parentsPflags *flag.FlagSet + // globNormFunc is the global normalization function + // that we can use on every pflag set and children commands + globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName + + // usageFunc is usage func defined by user. + usageFunc func(*Command) error + // usageTemplate is usage template defined by user. + usageTemplate *tmplFunc + // flagErrorFunc is func defined by user and it's called when the parsing of + // flags returns an error. + flagErrorFunc func(*Command, error) error + // helpTemplate is help template defined by user. + helpTemplate *tmplFunc + // helpFunc is help func defined by user. + helpFunc func(*Command, []string) + // helpCommand is command with usage 'help'. If it's not defined by user, + // cobra uses default help command. + helpCommand *Command + // helpCommandGroupID is the group id for the helpCommand + helpCommandGroupID string + + // completionCommandGroupID is the group id for the completion command + completionCommandGroupID string + + // versionTemplate is the version template defined by user. + versionTemplate *tmplFunc + + // errPrefix is the error message prefix defined by user. + errPrefix string + + // inReader is a reader defined by the user that replaces stdin + inReader io.Reader + // outWriter is a writer defined by the user that replaces stdout + outWriter io.Writer + // errWriter is a writer defined by the user that replaces stderr + errWriter io.Writer + + // FParseErrWhitelist flag parse errors to be ignored + FParseErrWhitelist FParseErrWhitelist + + // CompletionOptions is a set of options to control the handling of shell completion + CompletionOptions CompletionOptions + + // commandsAreSorted defines, if command slice are sorted or not. + commandsAreSorted bool + // commandCalledAs is the name or alias value used to call this command. + commandCalledAs struct { + name string + called bool + } + + ctx context.Context + + // commands is the list of commands supported by this program. + commands []*Command + // parent is a parent command for this command. + parent *Command + // Max lengths of commands' string lengths for use in padding. + commandsMaxUseLen int + commandsMaxCommandPathLen int + commandsMaxNameLen int + + // TraverseChildren parses flags on all parents before executing child command. + TraverseChildren bool + + // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. + Hidden bool + + // SilenceErrors is an option to quiet errors down stream. + SilenceErrors bool + + // SilenceUsage is an option to silence usage when an error occurs. + SilenceUsage bool + + // DisableFlagParsing disables the flag parsing. + // If this is true all flags will be passed to the command as arguments. + DisableFlagParsing bool + + // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") + // will be printed by generating docs for this command. + DisableAutoGenTag bool + + // DisableFlagsInUseLine will disable the addition of [flags] to the usage + // line of a command when printing help or generating docs + DisableFlagsInUseLine bool + + // DisableSuggestions disables the suggestions based on Levenshtein distance + // that go along with 'unknown command' messages. + DisableSuggestions bool + + // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. + // Must be > 0. + SuggestionsMinimumDistance int +} + +// Context returns underlying command context. If command was executed +// with ExecuteContext or the context was set with SetContext, the +// previously set context will be returned. Otherwise, nil is returned. +// +// Notice that a call to Execute and ExecuteC will replace a nil context of +// a command with a context.Background, so a background context will be +// returned by Context after one of these functions has been called. +func (c *Command) Context() context.Context { + return c.ctx +} + +// SetContext sets context for the command. This context will be overwritten by +// Command.ExecuteContext or Command.ExecuteContextC. +func (c *Command) SetContext(ctx context.Context) { + c.ctx = ctx +} + +// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden +// particularly useful when testing. +func (c *Command) SetArgs(a []string) { + c.args = a +} + +// SetOutput sets the destination for usage and error messages. +// If output is nil, os.Stderr is used. +// +// Deprecated: Use SetOut and/or SetErr instead +func (c *Command) SetOutput(output io.Writer) { + c.outWriter = output + c.errWriter = output +} + +// SetOut sets the destination for usage messages. +// If newOut is nil, os.Stdout is used. +func (c *Command) SetOut(newOut io.Writer) { + c.outWriter = newOut +} + +// SetErr sets the destination for error messages. +// If newErr is nil, os.Stderr is used. +func (c *Command) SetErr(newErr io.Writer) { + c.errWriter = newErr +} + +// SetIn sets the source for input data +// If newIn is nil, os.Stdin is used. +func (c *Command) SetIn(newIn io.Reader) { + c.inReader = newIn +} + +// SetUsageFunc sets usage function. Usage can be defined by application. +func (c *Command) SetUsageFunc(f func(*Command) error) { + c.usageFunc = f +} + +// SetUsageTemplate sets usage template. Can be defined by Application. +func (c *Command) SetUsageTemplate(s string) { + if s == "" { + c.usageTemplate = nil + return + } + c.usageTemplate = tmpl(s) +} + +// SetFlagErrorFunc sets a function to generate an error when flag parsing +// fails. +func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { + c.flagErrorFunc = f +} + +// SetHelpFunc sets help function. Can be defined by Application. +func (c *Command) SetHelpFunc(f func(*Command, []string)) { + c.helpFunc = f +} + +// SetHelpCommand sets help command. +func (c *Command) SetHelpCommand(cmd *Command) { + c.helpCommand = cmd +} + +// SetHelpCommandGroupID sets the group id of the help command. +func (c *Command) SetHelpCommandGroupID(groupID string) { + if c.helpCommand != nil { + c.helpCommand.GroupID = groupID + } + // helpCommandGroupID is used if no helpCommand is defined by the user + c.helpCommandGroupID = groupID +} + +// SetCompletionCommandGroupID sets the group id of the completion command. +func (c *Command) SetCompletionCommandGroupID(groupID string) { + // completionCommandGroupID is used if no completion command is defined by the user + c.Root().completionCommandGroupID = groupID +} + +// SetHelpTemplate sets help template to be used. Application can use it to set custom template. +func (c *Command) SetHelpTemplate(s string) { + if s == "" { + c.helpTemplate = nil + return + } + c.helpTemplate = tmpl(s) +} + +// SetVersionTemplate sets version template to be used. Application can use it to set custom template. +func (c *Command) SetVersionTemplate(s string) { + if s == "" { + c.versionTemplate = nil + return + } + c.versionTemplate = tmpl(s) +} + +// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. +func (c *Command) SetErrPrefix(s string) { + c.errPrefix = s +} + +// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. +// The user should not have a cyclic dependency on commands. +func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { + c.Flags().SetNormalizeFunc(n) + c.PersistentFlags().SetNormalizeFunc(n) + c.globNormFunc = n + + for _, command := range c.commands { + command.SetGlobalNormalizationFunc(n) + } +} + +// OutOrStdout returns output to stdout. +func (c *Command) OutOrStdout() io.Writer { + return c.getOut(os.Stdout) +} + +// OutOrStderr returns output to stderr +func (c *Command) OutOrStderr() io.Writer { + return c.getOut(os.Stderr) +} + +// ErrOrStderr returns output to stderr +func (c *Command) ErrOrStderr() io.Writer { + return c.getErr(os.Stderr) +} + +// InOrStdin returns input to stdin +func (c *Command) InOrStdin() io.Reader { + return c.getIn(os.Stdin) +} + +func (c *Command) getOut(def io.Writer) io.Writer { + if c.outWriter != nil { + return c.outWriter + } + if c.HasParent() { + return c.parent.getOut(def) + } + return def +} + +func (c *Command) getErr(def io.Writer) io.Writer { + if c.errWriter != nil { + return c.errWriter + } + if c.HasParent() { + return c.parent.getErr(def) + } + return def +} + +func (c *Command) getIn(def io.Reader) io.Reader { + if c.inReader != nil { + return c.inReader + } + if c.HasParent() { + return c.parent.getIn(def) + } + return def +} + +// UsageFunc returns either the function set by SetUsageFunc for this command +// or a parent, or it returns a default usage function. +func (c *Command) UsageFunc() (f func(*Command) error) { + if c.usageFunc != nil { + return c.usageFunc + } + if c.HasParent() { + return c.Parent().UsageFunc() + } + return func(c *Command) error { + c.mergePersistentFlags() + fn := c.getUsageTemplateFunc() + err := fn(c.OutOrStderr(), c) + if err != nil { + c.PrintErrln(err) + } + return err + } +} + +// getUsageTemplateFunc returns the usage template function for the command +// going up the command tree if necessary. +func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error { + if c.usageTemplate != nil { + return c.usageTemplate.fn + } + + if c.HasParent() { + return c.parent.getUsageTemplateFunc() + } + return defaultUsageFunc +} + +// Usage puts out the usage for the command. +// Used when a user provides invalid input. +// Can be defined by user by overriding UsageFunc. +func (c *Command) Usage() error { + return c.UsageFunc()(c) +} + +// HelpFunc returns either the function set by SetHelpFunc for this command +// or a parent, or it returns a function with default help behavior. +func (c *Command) HelpFunc() func(*Command, []string) { + if c.helpFunc != nil { + return c.helpFunc + } + if c.HasParent() { + return c.Parent().HelpFunc() + } + return func(c *Command, a []string) { + c.mergePersistentFlags() + fn := c.getHelpTemplateFunc() + // The help should be sent to stdout + // See https://github.com/spf13/cobra/issues/1002 + err := fn(c.OutOrStdout(), c) + if err != nil { + c.PrintErrln(err) + } + } +} + +// getHelpTemplateFunc returns the help template function for the command +// going up the command tree if necessary. +func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error { + if c.helpTemplate != nil { + return c.helpTemplate.fn + } + + if c.HasParent() { + return c.parent.getHelpTemplateFunc() + } + + return defaultHelpFunc +} + +// Help puts out the help for the command. +// Used when a user calls help [command]. +// Can be defined by user by overriding HelpFunc. +func (c *Command) Help() error { + c.HelpFunc()(c, []string{}) + return nil +} + +// UsageString returns usage string. +func (c *Command) UsageString() string { + // Storing normal writers + tmpOutput := c.outWriter + tmpErr := c.errWriter + + bb := new(bytes.Buffer) + c.outWriter = bb + c.errWriter = bb + + CheckErr(c.Usage()) + + // Setting things back to normal + c.outWriter = tmpOutput + c.errWriter = tmpErr + + return bb.String() +} + +// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this +// command or a parent, or it returns a function which returns the original +// error. +func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { + if c.flagErrorFunc != nil { + return c.flagErrorFunc + } + + if c.HasParent() { + return c.parent.FlagErrorFunc() + } + return func(c *Command, err error) error { + return err + } +} + +var minUsagePadding = 25 + +// UsagePadding return padding for the usage. +func (c *Command) UsagePadding() int { + if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { + return minUsagePadding + } + return c.parent.commandsMaxUseLen +} + +var minCommandPathPadding = 11 + +// CommandPathPadding return padding for the command path. +func (c *Command) CommandPathPadding() int { + if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { + return minCommandPathPadding + } + return c.parent.commandsMaxCommandPathLen +} + +var minNamePadding = 11 + +// NamePadding returns padding for the name. +func (c *Command) NamePadding() int { + if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { + return minNamePadding + } + return c.parent.commandsMaxNameLen +} + +// UsageTemplate returns usage template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) UsageTemplate() string { + if c.usageTemplate != nil { + return c.usageTemplate.tmpl + } + + if c.HasParent() { + return c.parent.UsageTemplate() + } + return defaultUsageTemplate +} + +// HelpTemplate return help template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) HelpTemplate() string { + if c.helpTemplate != nil { + return c.helpTemplate.tmpl + } + + if c.HasParent() { + return c.parent.HelpTemplate() + } + return defaultHelpTemplate +} + +// VersionTemplate return version template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) VersionTemplate() string { + if c.versionTemplate != nil { + return c.versionTemplate.tmpl + } + + if c.HasParent() { + return c.parent.VersionTemplate() + } + return defaultVersionTemplate +} + +// getVersionTemplateFunc returns the version template function for the command +// going up the command tree if necessary. +func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error { + if c.versionTemplate != nil { + return c.versionTemplate.fn + } + + if c.HasParent() { + return c.parent.getVersionTemplateFunc() + } + return defaultVersionFunc +} + +// ErrPrefix return error message prefix for the command +func (c *Command) ErrPrefix() string { + if c.errPrefix != "" { + return c.errPrefix + } + + if c.HasParent() { + return c.parent.ErrPrefix() + } + return "Error:" +} + +func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { + flag := fs.Lookup(name) + if flag == nil { + return false + } + return flag.NoOptDefVal != "" +} + +func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { + if len(name) == 0 { + return false + } + + flag := fs.ShorthandLookup(name[:1]) + if flag == nil { + return false + } + return flag.NoOptDefVal != "" +} + +func stripFlags(args []string, c *Command) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + + commands := []string{} + flags := c.Flags() + +Loop: + for len(args) > 0 { + s := args[0] + args = args[1:] + switch { + case s == "--": + // "--" terminates the flags + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + // If '--flag arg' then + // delete arg from args. + fallthrough // (do the same as below) + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // If '-f arg' then + // delete 'arg' from args or break the loop if len(args) <= 1. + if len(args) <= 1 { + break Loop + } else { + args = args[1:] + continue + } + case s != "" && !strings.HasPrefix(s, "-"): + commands = append(commands, s) + } + } + + return commands +} + +// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like +// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). +// Special care needs to be taken not to remove a flag value. +func (c *Command) argsMinusFirstX(args []string, x string) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + flags := c.Flags() + +Loop: + for pos := 0; pos < len(args); pos++ { + s := args[pos] + switch { + case s == "--": + // -- means we have reached the end of the parseable args. Break out of the loop now. + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + fallthrough + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip + // over the next arg, because that is the value of this flag. + pos++ + continue + case !strings.HasPrefix(s, "-"): + // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, + // return the args, excluding the one at this position. + if s == x { + ret := make([]string, 0, len(args)-1) + ret = append(ret, args[:pos]...) + ret = append(ret, args[pos+1:]...) + return ret + } + } + } + return args +} + +func isFlagArg(arg string) bool { + return ((len(arg) >= 3 && arg[0:2] == "--") || + (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) +} + +// Find the target command given the args and command tree +// Meant to be run on the highest node. Only searches down. +func (c *Command) Find(args []string) (*Command, []string, error) { + var innerfind func(*Command, []string) (*Command, []string) + + innerfind = func(c *Command, innerArgs []string) (*Command, []string) { + argsWOflags := stripFlags(innerArgs, c) + if len(argsWOflags) == 0 { + return c, innerArgs + } + nextSubCmd := argsWOflags[0] + + cmd := c.findNext(nextSubCmd) + if cmd != nil { + return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) + } + return c, innerArgs + } + + commandFound, a := innerfind(c, args) + if commandFound.Args == nil { + return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) + } + return commandFound, a, nil +} + +func (c *Command) findSuggestions(arg string) string { + if c.DisableSuggestions { + return "" + } + if c.SuggestionsMinimumDistance <= 0 { + c.SuggestionsMinimumDistance = 2 + } + var sb strings.Builder + if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { + sb.WriteString("\n\nDid you mean this?\n") + for _, s := range suggestions { + _, _ = fmt.Fprintf(&sb, "\t%v\n", s) + } + } + return sb.String() +} + +func (c *Command) findNext(next string) *Command { + matches := make([]*Command, 0) + for _, cmd := range c.commands { + if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) { + cmd.commandCalledAs.name = next + return cmd + } + if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { + matches = append(matches, cmd) + } + } + + if len(matches) == 1 { + // Temporarily disable gosec G602, which produces a false positive. + // See https://github.com/securego/gosec/issues/1005. + return matches[0] // #nosec G602 + } + + return nil +} + +// Traverse the command tree to find the command, and parse args for +// each parent. +func (c *Command) Traverse(args []string) (*Command, []string, error) { + flags := []string{} + inFlag := false + + for i, arg := range args { + switch { + // A long flag with a space separated value + case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): + // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' + inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) + flags = append(flags, arg) + continue + // A short flag with a space separated value + case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): + inFlag = true + flags = append(flags, arg) + continue + // The value for a flag + case inFlag: + inFlag = false + flags = append(flags, arg) + continue + // A flag without a value, or with an `=` separated value + case isFlagArg(arg): + flags = append(flags, arg) + continue + } + + cmd := c.findNext(arg) + if cmd == nil { + return c, args, nil + } + + if err := c.ParseFlags(flags); err != nil { + return nil, args, err + } + return cmd.Traverse(args[i+1:]) + } + return c, args, nil +} + +// SuggestionsFor provides suggestions for the typedName. +func (c *Command) SuggestionsFor(typedName string) []string { + suggestions := []string{} + for _, cmd := range c.commands { + if cmd.IsAvailableCommand() { + levenshteinDistance := ld(typedName, cmd.Name(), true) + suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance + suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) + if suggestByLevenshtein || suggestByPrefix { + suggestions = append(suggestions, cmd.Name()) + } + for _, explicitSuggestion := range cmd.SuggestFor { + if strings.EqualFold(typedName, explicitSuggestion) { + suggestions = append(suggestions, cmd.Name()) + } + } + } + } + return suggestions +} + +// VisitParents visits all parents of the command and invokes fn on each parent. +func (c *Command) VisitParents(fn func(*Command)) { + if c.HasParent() { + fn(c.Parent()) + c.Parent().VisitParents(fn) + } +} + +// Root finds root command. +func (c *Command) Root() *Command { + if c.HasParent() { + return c.Parent().Root() + } + return c +} + +// ArgsLenAtDash will return the length of c.Flags().Args at the moment +// when a -- was found during args parsing. +func (c *Command) ArgsLenAtDash() int { + return c.Flags().ArgsLenAtDash() +} + +func (c *Command) execute(a []string) (err error) { + if c == nil { + return fmt.Errorf("called Execute() on a nil Command") + } + + if len(c.Deprecated) > 0 { + c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) + } + + // initialize help and version flag at the last point possible to allow for user + // overriding + c.InitDefaultHelpFlag() + c.InitDefaultVersionFlag() + + err = c.ParseFlags(a) + if err != nil { + return c.FlagErrorFunc()(c, err) + } + + // If help is called, regardless of other flags, return we want help. + // Also say we need help if the command isn't runnable. + helpVal, err := c.Flags().GetBool(helpFlagName) + if err != nil { + // should be impossible to get here as we always declare a help + // flag in InitDefaultHelpFlag() + c.Println("\"help\" flag declared as non-bool. Please correct your code") + return err + } + + if helpVal { + return flag.ErrHelp + } + + // for back-compat, only add version flag behavior if version is defined + if c.Version != "" { + versionVal, err := c.Flags().GetBool("version") + if err != nil { + c.Println("\"version\" flag declared as non-bool. Please correct your code") + return err + } + if versionVal { + fn := c.getVersionTemplateFunc() + err := fn(c.OutOrStdout(), c) + if err != nil { + c.Println(err) + } + return err + } + } + + if !c.Runnable() { + return flag.ErrHelp + } + + c.preRun() + + defer c.postRun() + + argWoFlags := c.Flags().Args() + if c.DisableFlagParsing { + argWoFlags = a + } + + if err := c.ValidateArgs(argWoFlags); err != nil { + return err + } + + parents := make([]*Command, 0, 5) + for p := c; p != nil; p = p.Parent() { + if EnableTraverseRunHooks { + // When EnableTraverseRunHooks is set: + // - Execute all persistent pre-runs from the root parent till this command. + // - Execute all persistent post-runs from this command till the root parent. + parents = append([]*Command{p}, parents...) + } else { + // Otherwise, execute only the first found persistent hook. + parents = append(parents, p) + } + } + for _, p := range parents { + if p.PersistentPreRunE != nil { + if err := p.PersistentPreRunE(c, argWoFlags); err != nil { + return err + } + if !EnableTraverseRunHooks { + break + } + } else if p.PersistentPreRun != nil { + p.PersistentPreRun(c, argWoFlags) + if !EnableTraverseRunHooks { + break + } + } + } + if c.PreRunE != nil { + if err := c.PreRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PreRun != nil { + c.PreRun(c, argWoFlags) + } + + if err := c.ValidateRequiredFlags(); err != nil { + return err + } + if err := c.ValidateFlagGroups(); err != nil { + return err + } + + if c.RunE != nil { + if err := c.RunE(c, argWoFlags); err != nil { + return err + } + } else { + c.Run(c, argWoFlags) + } + if c.PostRunE != nil { + if err := c.PostRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PostRun != nil { + c.PostRun(c, argWoFlags) + } + for p := c; p != nil; p = p.Parent() { + if p.PersistentPostRunE != nil { + if err := p.PersistentPostRunE(c, argWoFlags); err != nil { + return err + } + if !EnableTraverseRunHooks { + break + } + } else if p.PersistentPostRun != nil { + p.PersistentPostRun(c, argWoFlags) + if !EnableTraverseRunHooks { + break + } + } + } + + return nil +} + +func (c *Command) preRun() { + for _, x := range initializers { + x() + } +} + +func (c *Command) postRun() { + for _, x := range finalizers { + x() + } +} + +// ExecuteContext is the same as Execute(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. +func (c *Command) ExecuteContext(ctx context.Context) error { + c.ctx = ctx + return c.Execute() +} + +// Execute uses the args (os.Args[1:] by default) +// and run through the command tree finding appropriate matches +// for commands and then corresponding flags. +func (c *Command) Execute() error { + _, err := c.ExecuteC() + return err +} + +// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. +func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { + c.ctx = ctx + return c.ExecuteC() +} + +// ExecuteC executes the command. +func (c *Command) ExecuteC() (cmd *Command, err error) { + if c.ctx == nil { + c.ctx = context.Background() + } + + // Regardless of what command execute is called on, run on Root only + if c.HasParent() { + return c.Root().ExecuteC() + } + + // windows hook + if preExecHookFn != nil { + preExecHookFn(c) + } + + // initialize help at the last point to allow for user overriding + c.InitDefaultHelpCmd() + + args := c.args + + // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 + if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { + args = os.Args[1:] + } + + // initialize the __complete command to be used for shell completion + c.initCompleteCmd(args) + + // initialize the default completion command + c.InitDefaultCompletionCmd(args...) + + // Now that all commands have been created, let's make sure all groups + // are properly created also + c.checkCommandGroups() + + var flags []string + if c.TraverseChildren { + cmd, flags, err = c.Traverse(args) + } else { + cmd, flags, err = c.Find(args) + } + if err != nil { + // If found parse to a subcommand and then failed, talk about the subcommand + if cmd != nil { + c = cmd + } + if !c.SilenceErrors { + c.PrintErrln(c.ErrPrefix(), err.Error()) + c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) + } + return c, err + } + + cmd.commandCalledAs.called = true + if cmd.commandCalledAs.name == "" { + cmd.commandCalledAs.name = cmd.Name() + } + + // We have to pass global context to children command + // if context is present on the parent command. + if cmd.ctx == nil { + cmd.ctx = c.ctx + } + + err = cmd.execute(flags) + if err != nil { + // Always show help if requested, even if SilenceErrors is in + // effect + if errors.Is(err, flag.ErrHelp) { + cmd.HelpFunc()(cmd, args) + return cmd, nil + } + + // If root command has SilenceErrors flagged, + // all subcommands should respect it + if !cmd.SilenceErrors && !c.SilenceErrors { + c.PrintErrln(cmd.ErrPrefix(), err.Error()) + } + + // If root command has SilenceUsage flagged, + // all subcommands should respect it + if !cmd.SilenceUsage && !c.SilenceUsage { + c.Println(cmd.UsageString()) + } + } + return cmd, err +} + +func (c *Command) ValidateArgs(args []string) error { + if c.Args == nil { + return ArbitraryArgs(c, args) + } + return c.Args(c, args) +} + +// ValidateRequiredFlags validates all required flags are present and returns an error otherwise +func (c *Command) ValidateRequiredFlags() error { + if c.DisableFlagParsing { + return nil + } + + flags := c.Flags() + missingFlagNames := []string{} + flags.VisitAll(func(pflag *flag.Flag) { + requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] + if !found { + return + } + if (requiredAnnotation[0] == "true") && !pflag.Changed { + missingFlagNames = append(missingFlagNames, pflag.Name) + } + }) + + if len(missingFlagNames) > 0 { + return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) + } + return nil +} + +// checkCommandGroups checks if a command has been added to a group that does not exists. +// If so, we panic because it indicates a coding error that should be corrected. +func (c *Command) checkCommandGroups() { + for _, sub := range c.commands { + // if Group is not defined let the developer know right away + if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) { + panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath())) + } + + sub.checkCommandGroups() + } +} + +// InitDefaultHelpFlag adds default help flag to c. +// It is called automatically by executing the c or by calling help and usage. +// If c already has help flag, it will do nothing. +func (c *Command) InitDefaultHelpFlag() { + c.mergePersistentFlags() + if c.Flags().Lookup(helpFlagName) == nil { + usage := "help for " + name := c.DisplayName() + if name == "" { + usage += "this command" + } else { + usage += name + } + c.Flags().BoolP(helpFlagName, "h", false, usage) + _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"}) + } +} + +// InitDefaultVersionFlag adds default version flag to c. +// It is called automatically by executing the c. +// If c already has a version flag, it will do nothing. +// If c.Version is empty, it will do nothing. +func (c *Command) InitDefaultVersionFlag() { + if c.Version == "" { + return + } + + c.mergePersistentFlags() + if c.Flags().Lookup("version") == nil { + usage := "version for " + if c.Name() == "" { + usage += "this command" + } else { + usage += c.DisplayName() + } + if c.Flags().ShorthandLookup("v") == nil { + c.Flags().BoolP("version", "v", false, usage) + } else { + c.Flags().Bool("version", false, usage) + } + _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"}) + } +} + +// InitDefaultHelpCmd adds default help command to c. +// It is called automatically by executing the c or by calling help and usage. +// If c already has help command or c has no subcommands, it will do nothing. +func (c *Command) InitDefaultHelpCmd() { + if !c.HasSubCommands() { + return + } + + if c.helpCommand == nil { + c.helpCommand = &Command{ + Use: "help [command]", + Short: "Help about any command", + Long: `Help provides help for any command in the application. +Simply type ` + c.DisplayName() + ` help [path to command] for full details.`, + ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + var completions []Completion + cmd, _, e := c.Root().Find(args) + if e != nil { + return nil, ShellCompDirectiveNoFileComp + } + if cmd == nil { + // Root help command. + cmd = c.Root() + } + for _, subCmd := range cmd.Commands() { + if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { + if strings.HasPrefix(subCmd.Name(), toComplete) { + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) + } + } + } + return completions, ShellCompDirectiveNoFileComp + }, + Run: func(c *Command, args []string) { + cmd, _, e := c.Root().Find(args) + if cmd == nil || e != nil { + c.Printf("Unknown help topic %#q\n", args) + CheckErr(c.Root().Usage()) + } else { + cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown + cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown + CheckErr(cmd.Help()) + } + }, + GroupID: c.helpCommandGroupID, + } + } + c.RemoveCommand(c.helpCommand) + c.AddCommand(c.helpCommand) +} + +// ResetCommands delete parent, subcommand and help command from c. +func (c *Command) ResetCommands() { + c.parent = nil + c.commands = nil + c.helpCommand = nil + c.parentsPflags = nil +} + +// Sorts commands by their names. +type commandSorterByName []*Command + +func (c commandSorterByName) Len() int { return len(c) } +func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } +func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } + +// Commands returns a sorted slice of child commands. +func (c *Command) Commands() []*Command { + // do not sort commands if it already sorted or sorting was disabled + if EnableCommandSorting && !c.commandsAreSorted { + sort.Sort(commandSorterByName(c.commands)) + c.commandsAreSorted = true + } + return c.commands +} + +// AddCommand adds one or more commands to this parent command. +func (c *Command) AddCommand(cmds ...*Command) { + for i, x := range cmds { + if cmds[i] == c { + panic("Command can't be a child of itself") + } + cmds[i].parent = c + // update max lengths + usageLen := len(x.Use) + if usageLen > c.commandsMaxUseLen { + c.commandsMaxUseLen = usageLen + } + commandPathLen := len(x.CommandPath()) + if commandPathLen > c.commandsMaxCommandPathLen { + c.commandsMaxCommandPathLen = commandPathLen + } + nameLen := len(x.Name()) + if nameLen > c.commandsMaxNameLen { + c.commandsMaxNameLen = nameLen + } + // If global normalization function exists, update all children + if c.globNormFunc != nil { + x.SetGlobalNormalizationFunc(c.globNormFunc) + } + c.commands = append(c.commands, x) + c.commandsAreSorted = false + } +} + +// Groups returns a slice of child command groups. +func (c *Command) Groups() []*Group { + return c.commandgroups +} + +// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group +func (c *Command) AllChildCommandsHaveGroup() bool { + for _, sub := range c.commands { + if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" { + return false + } + } + return true +} + +// ContainsGroup return if groupID exists in the list of command groups. +func (c *Command) ContainsGroup(groupID string) bool { + for _, x := range c.commandgroups { + if x.ID == groupID { + return true + } + } + return false +} + +// AddGroup adds one or more command groups to this parent command. +func (c *Command) AddGroup(groups ...*Group) { + c.commandgroups = append(c.commandgroups, groups...) +} + +// RemoveCommand removes one or more commands from a parent command. +func (c *Command) RemoveCommand(cmds ...*Command) { + commands := []*Command{} +main: + for _, command := range c.commands { + for _, cmd := range cmds { + if command == cmd { + command.parent = nil + continue main + } + } + commands = append(commands, command) + } + c.commands = commands + // recompute all lengths + c.commandsMaxUseLen = 0 + c.commandsMaxCommandPathLen = 0 + c.commandsMaxNameLen = 0 + for _, command := range c.commands { + usageLen := len(command.Use) + if usageLen > c.commandsMaxUseLen { + c.commandsMaxUseLen = usageLen + } + commandPathLen := len(command.CommandPath()) + if commandPathLen > c.commandsMaxCommandPathLen { + c.commandsMaxCommandPathLen = commandPathLen + } + nameLen := len(command.Name()) + if nameLen > c.commandsMaxNameLen { + c.commandsMaxNameLen = nameLen + } + } +} + +// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. +func (c *Command) Print(i ...interface{}) { + fmt.Fprint(c.OutOrStderr(), i...) +} + +// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. +func (c *Command) Println(i ...interface{}) { + c.Print(fmt.Sprintln(i...)) +} + +// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. +func (c *Command) Printf(format string, i ...interface{}) { + c.Print(fmt.Sprintf(format, i...)) +} + +// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErr(i ...interface{}) { + fmt.Fprint(c.ErrOrStderr(), i...) +} + +// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErrln(i ...interface{}) { + c.PrintErr(fmt.Sprintln(i...)) +} + +// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErrf(format string, i ...interface{}) { + c.PrintErr(fmt.Sprintf(format, i...)) +} + +// CommandPath returns the full path to this command. +func (c *Command) CommandPath() string { + if c.HasParent() { + return c.Parent().CommandPath() + " " + c.Name() + } + return c.DisplayName() +} + +// DisplayName returns the name to display in help text. Returns command Name() +// If CommandDisplayNameAnnoation is not set +func (c *Command) DisplayName() string { + if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { + return displayName + } + return c.Name() +} + +// UseLine puts out the full usage for a given command (including parents). +func (c *Command) UseLine() string { + var useline string + use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1) + if c.HasParent() { + useline = c.parent.CommandPath() + " " + use + } else { + useline = use + } + if c.DisableFlagsInUseLine { + return useline + } + if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { + useline += " [flags]" + } + return useline +} + +// DebugFlags used to determine which flags have been assigned to which commands +// and which persist. +func (c *Command) DebugFlags() { + c.Println("DebugFlags called on", c.Name()) + var debugflags func(*Command) + + debugflags = func(x *Command) { + if x.HasFlags() || x.HasPersistentFlags() { + c.Println(x.Name()) + } + if x.HasFlags() { + x.flags.VisitAll(func(f *flag.Flag) { + if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") + } else { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") + } + }) + } + if x.HasPersistentFlags() { + x.pflags.VisitAll(func(f *flag.Flag) { + if x.HasFlags() { + if x.flags.Lookup(f.Name) == nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") + } + } else { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") + } + }) + } + c.Println(x.flagErrorBuf) + if x.HasSubCommands() { + for _, y := range x.commands { + debugflags(y) + } + } + } + + debugflags(c) +} + +// Name returns the command's name: the first word in the use line. +func (c *Command) Name() string { + name := c.Use + i := strings.Index(name, " ") + if i >= 0 { + name = name[:i] + } + return name +} + +// HasAlias determines if a given string is an alias of the command. +func (c *Command) HasAlias(s string) bool { + for _, a := range c.Aliases { + if commandNameMatches(a, s) { + return true + } + } + return false +} + +// CalledAs returns the command name or alias that was used to invoke +// this command or an empty string if the command has not been called. +func (c *Command) CalledAs() string { + if c.commandCalledAs.called { + return c.commandCalledAs.name + } + return "" +} + +// hasNameOrAliasPrefix returns true if the Name or any of aliases start +// with prefix +func (c *Command) hasNameOrAliasPrefix(prefix string) bool { + if strings.HasPrefix(c.Name(), prefix) { + c.commandCalledAs.name = c.Name() + return true + } + for _, alias := range c.Aliases { + if strings.HasPrefix(alias, prefix) { + c.commandCalledAs.name = alias + return true + } + } + return false +} + +// NameAndAliases returns a list of the command name and all aliases +func (c *Command) NameAndAliases() string { + return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") +} + +// HasExample determines if the command has example. +func (c *Command) HasExample() bool { + return len(c.Example) > 0 +} + +// Runnable determines if the command is itself runnable. +func (c *Command) Runnable() bool { + return c.Run != nil || c.RunE != nil +} + +// HasSubCommands determines if the command has children commands. +func (c *Command) HasSubCommands() bool { + return len(c.commands) > 0 +} + +// IsAvailableCommand determines if a command is available as a non-help command +// (this includes all non deprecated/hidden commands). +func (c *Command) IsAvailableCommand() bool { + if len(c.Deprecated) != 0 || c.Hidden { + return false + } + + if c.HasParent() && c.Parent().helpCommand == c { + return false + } + + if c.Runnable() || c.HasAvailableSubCommands() { + return true + } + + return false +} + +// IsAdditionalHelpTopicCommand determines if a command is an additional +// help topic command; additional help topic command is determined by the +// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that +// are runnable/hidden/deprecated. +// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. +func (c *Command) IsAdditionalHelpTopicCommand() bool { + // if a command is runnable, deprecated, or hidden it is not a 'help' command + if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { + return false + } + + // if any non-help sub commands are found, the command is not a 'help' command + for _, sub := range c.commands { + if !sub.IsAdditionalHelpTopicCommand() { + return false + } + } + + // the command either has no sub commands, or no non-help sub commands + return true +} + +// HasHelpSubCommands determines if a command has any available 'help' sub commands +// that need to be shown in the usage/help default template under 'additional help +// topics'. +func (c *Command) HasHelpSubCommands() bool { + // return true on the first found available 'help' sub command + for _, sub := range c.commands { + if sub.IsAdditionalHelpTopicCommand() { + return true + } + } + + // the command either has no sub commands, or no available 'help' sub commands + return false +} + +// HasAvailableSubCommands determines if a command has available sub commands that +// need to be shown in the usage/help default template under 'available commands'. +func (c *Command) HasAvailableSubCommands() bool { + // return true on the first found available (non deprecated/help/hidden) + // sub command + for _, sub := range c.commands { + if sub.IsAvailableCommand() { + return true + } + } + + // the command either has no sub commands, or no available (non deprecated/help/hidden) + // sub commands + return false +} + +// HasParent determines if the command is a child command. +func (c *Command) HasParent() bool { + return c.parent != nil +} + +// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. +func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { + return c.globNormFunc +} + +// Flags returns the complete FlagSet that applies +// to this command (local and persistent declared here and by all parents). +func (c *Command) Flags() *flag.FlagSet { + if c.flags == nil { + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.flags.SetOutput(c.flagErrorBuf) + } + + return c.flags +} + +// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { + persistentFlags := c.PersistentFlags() + + out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.LocalFlags().VisitAll(func(f *flag.Flag) { + if persistentFlags.Lookup(f.Name) == nil { + out.AddFlag(f) + } + }) + return out +} + +// LocalFlags returns the local FlagSet specifically set in the current command. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) LocalFlags() *flag.FlagSet { + c.mergePersistentFlags() + + if c.lflags == nil { + c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.lflags.SetOutput(c.flagErrorBuf) + } + c.lflags.SortFlags = c.Flags().SortFlags + if c.globNormFunc != nil { + c.lflags.SetNormalizeFunc(c.globNormFunc) + } + + addToLocal := func(f *flag.Flag) { + // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag + if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) { + c.lflags.AddFlag(f) + } + } + c.Flags().VisitAll(addToLocal) + c.PersistentFlags().VisitAll(addToLocal) + return c.lflags +} + +// InheritedFlags returns all flags which were inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) InheritedFlags() *flag.FlagSet { + c.mergePersistentFlags() + + if c.iflags == nil { + c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.iflags.SetOutput(c.flagErrorBuf) + } + + local := c.LocalFlags() + if c.globNormFunc != nil { + c.iflags.SetNormalizeFunc(c.globNormFunc) + } + + c.parentsPflags.VisitAll(func(f *flag.Flag) { + if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { + c.iflags.AddFlag(f) + } + }) + return c.iflags +} + +// NonInheritedFlags returns all flags which were not inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) NonInheritedFlags() *flag.FlagSet { + return c.LocalFlags() +} + +// PersistentFlags returns the persistent FlagSet specifically set in the current command. +func (c *Command) PersistentFlags() *flag.FlagSet { + if c.pflags == nil { + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.pflags.SetOutput(c.flagErrorBuf) + } + return c.pflags +} + +// ResetFlags deletes all flags from command. +func (c *Command) ResetFlags() { + c.flagErrorBuf = new(bytes.Buffer) + c.flagErrorBuf.Reset() + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.flags.SetOutput(c.flagErrorBuf) + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.pflags.SetOutput(c.flagErrorBuf) + + c.lflags = nil + c.iflags = nil + c.parentsPflags = nil +} + +// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). +func (c *Command) HasFlags() bool { + return c.Flags().HasFlags() +} + +// HasPersistentFlags checks if the command contains persistent flags. +func (c *Command) HasPersistentFlags() bool { + return c.PersistentFlags().HasFlags() +} + +// HasLocalFlags checks if the command has flags specifically declared locally. +func (c *Command) HasLocalFlags() bool { + return c.LocalFlags().HasFlags() +} + +// HasInheritedFlags checks if the command has flags inherited from its parent command. +func (c *Command) HasInheritedFlags() bool { + return c.InheritedFlags().HasFlags() +} + +// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire +// structure) which are not hidden or deprecated. +func (c *Command) HasAvailableFlags() bool { + return c.Flags().HasAvailableFlags() +} + +// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. +func (c *Command) HasAvailablePersistentFlags() bool { + return c.PersistentFlags().HasAvailableFlags() +} + +// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden +// or deprecated. +func (c *Command) HasAvailableLocalFlags() bool { + return c.LocalFlags().HasAvailableFlags() +} + +// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are +// not hidden or deprecated. +func (c *Command) HasAvailableInheritedFlags() bool { + return c.InheritedFlags().HasAvailableFlags() +} + +// Flag climbs up the command tree looking for matching flag. +func (c *Command) Flag(name string) (flag *flag.Flag) { + flag = c.Flags().Lookup(name) + + if flag == nil { + flag = c.persistentFlag(name) + } + + return +} + +// Recursively find matching persistent flag. +func (c *Command) persistentFlag(name string) (flag *flag.Flag) { + if c.HasPersistentFlags() { + flag = c.PersistentFlags().Lookup(name) + } + + if flag == nil { + c.updateParentsPflags() + flag = c.parentsPflags.Lookup(name) + } + return +} + +// ParseFlags parses persistent flag tree and local flags. +func (c *Command) ParseFlags(args []string) error { + if c.DisableFlagParsing { + return nil + } + + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + beforeErrorBufLen := c.flagErrorBuf.Len() + c.mergePersistentFlags() + + // do it here after merging all flags and just before parse + c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) + + err := c.Flags().Parse(args) + // Print warnings if they occurred (e.g. deprecated flag messages). + if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { + c.Print(c.flagErrorBuf.String()) + } + + return err +} + +// Parent returns a commands parent command. +func (c *Command) Parent() *Command { + return c.parent +} + +// mergePersistentFlags merges c.PersistentFlags() to c.Flags() +// and adds missing persistent flags of all parents. +func (c *Command) mergePersistentFlags() { + c.updateParentsPflags() + c.Flags().AddFlagSet(c.PersistentFlags()) + c.Flags().AddFlagSet(c.parentsPflags) +} + +// updateParentsPflags updates c.parentsPflags by adding +// new persistent flags of all parents. +// If c.parentsPflags == nil, it makes new. +func (c *Command) updateParentsPflags() { + if c.parentsPflags == nil { + c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.parentsPflags.SetOutput(c.flagErrorBuf) + c.parentsPflags.SortFlags = false + } + + if c.globNormFunc != nil { + c.parentsPflags.SetNormalizeFunc(c.globNormFunc) + } + + c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) + + c.VisitParents(func(parent *Command) { + c.parentsPflags.AddFlagSet(parent.PersistentFlags()) + }) +} + +// commandNameMatches checks if two command names are equal +// taking into account case sensitivity according to +// EnableCaseInsensitive global configuration. +func commandNameMatches(s string, t string) bool { + if EnableCaseInsensitive { + return strings.EqualFold(s, t) + } + + return s == t +} + +// tmplFunc holds a template and a function that will execute said template. +type tmplFunc struct { + tmpl string + fn func(io.Writer, interface{}) error +} + +var defaultUsageTemplate = `Usage:{{if .Runnable}} + {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} + +Aliases: + {{.NameAndAliases}}{{end}}{{if .HasExample}} + +Examples: +{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} + +Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} + +{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} + +Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} + +Flags: +{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} + +Global Flags: +{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} + +Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} + +Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} +` + +// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync. +func defaultUsageFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + fmt.Fprint(w, "Usage:") + if c.Runnable() { + fmt.Fprintf(w, "\n %s", c.UseLine()) + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n %s [command]", c.CommandPath()) + } + if len(c.Aliases) > 0 { + fmt.Fprintf(w, "\n\nAliases:\n") + fmt.Fprintf(w, " %s", c.NameAndAliases()) + } + if c.HasExample() { + fmt.Fprintf(w, "\n\nExamples:\n") + fmt.Fprintf(w, "%s", c.Example) + } + if c.HasAvailableSubCommands() { + cmds := c.Commands() + if len(c.Groups()) == 0 { + fmt.Fprintf(w, "\n\nAvailable Commands:") + for _, subcmd := range cmds { + if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } else { + for _, group := range c.Groups() { + fmt.Fprintf(w, "\n\n%s", group.Title) + for _, subcmd := range cmds { + if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + if !c.AllChildCommandsHaveGroup() { + fmt.Fprintf(w, "\n\nAdditional Commands:") + for _, subcmd := range cmds { + if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + } + } + if c.HasAvailableLocalFlags() { + fmt.Fprintf(w, "\n\nFlags:\n") + fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages())) + } + if c.HasAvailableInheritedFlags() { + fmt.Fprintf(w, "\n\nGlobal Flags:\n") + fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages())) + } + if c.HasHelpSubCommands() { + fmt.Fprintf(w, "\n\nAdditional help topcis:") + for _, subcmd := range c.Commands() { + if subcmd.IsAdditionalHelpTopicCommand() { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short) + } + } + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath()) + } + fmt.Fprintln(w) + return nil +} + +var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} + +{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` + +// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync. +func defaultHelpFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + usage := c.Long + if usage == "" { + usage = c.Short + } + usage = trimRightSpace(usage) + if usage != "" { + fmt.Fprintln(w, usage) + fmt.Fprintln(w) + } + if c.Runnable() || c.HasSubCommands() { + fmt.Fprint(w, c.UsageString()) + } + return nil +} + +var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} +` + +// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync. +func defaultVersionFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + _, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version) + return err +} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go new file mode 100644 index 000000000..307f0c127 --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_notwin.go @@ -0,0 +1,20 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !windows +// +build !windows + +package cobra + +var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go new file mode 100644 index 000000000..adbef395c --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_win.go @@ -0,0 +1,41 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build windows +// +build windows + +package cobra + +import ( + "fmt" + "os" + "time" + + "github.com/inconshreveable/mousetrap" +) + +var preExecHookFn = preExecHook + +func preExecHook(c *Command) { + if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { + c.Print(MousetrapHelpText) + if MousetrapDisplayDuration > 0 { + time.Sleep(MousetrapDisplayDuration) + } else { + c.Println("Press return to continue...") + fmt.Scanln() + } + os.Exit(1) + } +} diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go new file mode 100644 index 000000000..a1752f763 --- /dev/null +++ b/vendor/github.com/spf13/cobra/completions.go @@ -0,0 +1,1005 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "os" + "regexp" + "strconv" + "strings" + "sync" + + "github.com/spf13/pflag" +) + +const ( + // ShellCompRequestCmd is the name of the hidden command that is used to request + // completion results from the program. It is used by the shell completion scripts. + ShellCompRequestCmd = "__complete" + // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request + // completion results without their description. It is used by the shell completion scripts. + ShellCompNoDescRequestCmd = "__completeNoDesc" +) + +// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. +var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{} + +// lock for reading and writing from flagCompletionFunctions +var flagCompletionMutex = &sync.RWMutex{} + +// ShellCompDirective is a bit map representing the different behaviors the shell +// can be instructed to have once completions have been provided. +type ShellCompDirective int + +type flagCompError struct { + subCommand string + flagName string +} + +func (e *flagCompError) Error() string { + return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" +} + +const ( + // ShellCompDirectiveError indicates an error occurred and completions should be ignored. + ShellCompDirectiveError ShellCompDirective = 1 << iota + + // ShellCompDirectiveNoSpace indicates that the shell should not add a space + // after the completion even if there is a single completion provided. + ShellCompDirectiveNoSpace + + // ShellCompDirectiveNoFileComp indicates that the shell should not provide + // file completion even when no completion is provided. + ShellCompDirectiveNoFileComp + + // ShellCompDirectiveFilterFileExt indicates that the provided completions + // should be used as file extension filters. + // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() + // is a shortcut to using this directive explicitly. The BashCompFilenameExt + // annotation can also be used to obtain the same behavior for flags. + ShellCompDirectiveFilterFileExt + + // ShellCompDirectiveFilterDirs indicates that only directory names should + // be provided in file completion. To request directory names within another + // directory, the returned completions should specify the directory within + // which to search. The BashCompSubdirsInDir annotation can be used to + // obtain the same behavior but only for flags. + ShellCompDirectiveFilterDirs + + // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order + // in which the completions are provided + ShellCompDirectiveKeepOrder + + // =========================================================================== + + // All directives using iota should be above this one. + // For internal use. + shellCompDirectiveMaxValue + + // ShellCompDirectiveDefault indicates to let the shell perform its default + // behavior after completions have been provided. + // This one must be last to avoid messing up the iota count. + ShellCompDirectiveDefault ShellCompDirective = 0 +) + +const ( + // Constants for the completion command + compCmdName = "completion" + compCmdNoDescFlagName = "no-descriptions" + compCmdNoDescFlagDesc = "disable completion descriptions" + compCmdNoDescFlagDefault = false +) + +// CompletionOptions are the options to control shell completion +type CompletionOptions struct { + // DisableDefaultCmd prevents Cobra from creating a default 'completion' command + DisableDefaultCmd bool + // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + // for shells that support completion descriptions + DisableNoDescFlag bool + // DisableDescriptions turns off all completion descriptions for shells + // that support them + DisableDescriptions bool + // HiddenDefaultCmd makes the default 'completion' command hidden + HiddenDefaultCmd bool +} + +// Completion is a string that can be used for completions +// +// two formats are supported: +// - the completion choice +// - the completion choice with a textual description (separated by a TAB). +// +// [CompletionWithDesc] can be used to create a completion string with a textual description. +// +// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used. +type Completion = string + +// CompletionFunc is a function that provides completion results. +type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) + +// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format. +func CompletionWithDesc(choice string, description string) Completion { + return choice + "\t" + description +} + +// NoFileCompletions can be used to disable file completion for commands that should +// not trigger file completions. +// +// This method satisfies [CompletionFunc]. +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + return nil, ShellCompDirectiveNoFileComp +} + +// FixedCompletions can be used to create a completion function which always +// returns the same results. +// +// This method returns a function that satisfies [CompletionFunc] +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc { + return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + return choices, directive + } +} + +// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. +// +// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions], +// or you can define your own. +func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error { + flag := c.Flag(flagName) + if flag == nil { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) + } + flagCompletionMutex.Lock() + defer flagCompletionMutex.Unlock() + + if _, exists := flagCompletionFunctions[flag]; exists { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) + } + flagCompletionFunctions[flag] = f + return nil +} + +// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. +func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) { + flag := c.Flag(flagName) + if flag == nil { + return nil, false + } + + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + + completionFunc, exists := flagCompletionFunctions[flag] + return completionFunc, exists +} + +// Returns a string listing the different directive enabled in the specified parameter +func (d ShellCompDirective) string() string { + var directives []string + if d&ShellCompDirectiveError != 0 { + directives = append(directives, "ShellCompDirectiveError") + } + if d&ShellCompDirectiveNoSpace != 0 { + directives = append(directives, "ShellCompDirectiveNoSpace") + } + if d&ShellCompDirectiveNoFileComp != 0 { + directives = append(directives, "ShellCompDirectiveNoFileComp") + } + if d&ShellCompDirectiveFilterFileExt != 0 { + directives = append(directives, "ShellCompDirectiveFilterFileExt") + } + if d&ShellCompDirectiveFilterDirs != 0 { + directives = append(directives, "ShellCompDirectiveFilterDirs") + } + if d&ShellCompDirectiveKeepOrder != 0 { + directives = append(directives, "ShellCompDirectiveKeepOrder") + } + if len(directives) == 0 { + directives = append(directives, "ShellCompDirectiveDefault") + } + + if d >= shellCompDirectiveMaxValue { + return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) + } + return strings.Join(directives, ", ") +} + +// initCompleteCmd adds a special hidden command that can be used to request custom completions. +func (c *Command) initCompleteCmd(args []string) { + completeCmd := &Command{ + Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), + Aliases: []string{ShellCompNoDescRequestCmd}, + DisableFlagsInUseLine: true, + Hidden: true, + DisableFlagParsing: true, + Args: MinimumNArgs(1), + Short: "Request shell completion choices for the specified command-line", + Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", + "to request completion choices for the specified command-line.", ShellCompRequestCmd), + Run: func(cmd *Command, args []string) { + finalCmd, completions, directive, err := cmd.getCompletions(args) + if err != nil { + CompErrorln(err.Error()) + // Keep going for multiple reasons: + // 1- There could be some valid completions even though there was an error + // 2- Even without completions, we need to print the directive + } + + noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd + if !noDescriptions { + if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil { + noDescriptions = !doDescriptions + } + } + noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable + out := finalCmd.OutOrStdout() + for _, comp := range completions { + if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { + // Remove all activeHelp entries if it's disabled. + continue + } + if noDescriptions { + // Remove any description that may be included following a tab character. + comp = strings.SplitN(comp, "\t", 2)[0] + } + + // Make sure we only write the first line to the output. + // This is needed if a description contains a linebreak. + // Otherwise the shell scripts will interpret the other lines as new flags + // and could therefore provide a wrong completion. + comp = strings.SplitN(comp, "\n", 2)[0] + + // Finally trim the completion. This is especially important to get rid + // of a trailing tab when there are no description following it. + // For example, a sub-command without a description should not be completed + // with a tab at the end (or else zsh will show a -- following it + // although there is no description). + comp = strings.TrimSpace(comp) + + // Print each possible completion to the output for the completion script to consume. + fmt.Fprintln(out, comp) + } + + // As the last printout, print the completion directive for the completion script to parse. + // The directive integer must be that last character following a single colon (:). + // The completion script expects : + fmt.Fprintf(out, ":%d\n", directive) + + // Print some helpful info to stderr for the user to understand. + // Output from stderr must be ignored by the completion script. + fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) + }, + } + c.AddCommand(completeCmd) + subCmd, _, err := c.Find(args) + if err != nil || subCmd.Name() != ShellCompRequestCmd { + // Only create this special command if it is actually being called. + // This reduces possible side-effects of creating such a command; + // for example, having this command would cause problems to a + // cobra program that only consists of the root command, since this + // command would cause the root command to suddenly have a subcommand. + c.RemoveCommand(completeCmd) + } +} + +// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect +// flags that accept multiple values and therefore can provide completion +// multiple times. +type SliceValue interface { + // GetSlice returns the flag value list as an array of strings. + GetSlice() []string +} + +func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) { + // The last argument, which is not completely typed by the user, + // should not be part of the list of arguments + toComplete := args[len(args)-1] + trimmedArgs := args[:len(args)-1] + + var finalCmd *Command + var finalArgs []string + var err error + // Find the real command for which completion must be performed + // check if we need to traverse here to parse local flags on parent commands + if c.Root().TraverseChildren { + finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) + } else { + // For Root commands that don't specify any value for their Args fields, when we call + // Find(), if those Root commands don't have any sub-commands, they will accept arguments. + // However, because we have added the __complete sub-command in the current code path, the + // call to Find() -> legacyArgs() will return an error if there are any arguments. + // To avoid this, we first remove the __complete command to get back to having no sub-commands. + rootCmd := c.Root() + if len(rootCmd.Commands()) == 1 { + rootCmd.RemoveCommand(c) + } + + finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs) + } + if err != nil { + // Unable to find the real command. E.g., someInvalidCmd + return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) + } + finalCmd.ctx = c.ctx + + // These flags are normally added when `execute()` is called on `finalCmd`, + // however, when doing completion, we don't call `finalCmd.execute()`. + // Let's add the --help and --version flag ourselves but only if the finalCmd + // has not disabled flag parsing; if flag parsing is disabled, it is up to the + // finalCmd itself to handle the completion of *all* flags. + if !finalCmd.DisableFlagParsing { + finalCmd.InitDefaultHelpFlag() + finalCmd.InitDefaultVersionFlag() + } + + // Check if we are doing flag value completion before parsing the flags. + // This is important because if we are completing a flag value, we need to also + // remove the flag name argument from the list of finalArgs or else the parsing + // could fail due to an invalid value (incomplete) for the flag. + flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) + + // Check if interspersed is false or -- was set on a previous arg. + // This works by counting the arguments. Normally -- is not counted as arg but + // if -- was already set or interspersed is false and there is already one arg then + // the extra added -- is counted as arg. + flagCompletion := true + _ = finalCmd.ParseFlags(append(finalArgs, "--")) + newArgCount := finalCmd.Flags().NArg() + + // Parse the flags early so we can check if required flags are set + if err = finalCmd.ParseFlags(finalArgs); err != nil { + return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) + } + + realArgCount := finalCmd.Flags().NArg() + if newArgCount > realArgCount { + // don't do flag completion (see above) + flagCompletion = false + } + // Error while attempting to parse flags + if flagErr != nil { + // If error type is flagCompError and we don't want flagCompletion we should ignore the error + if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { + return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr + } + } + + // Look for the --help or --version flags. If they are present, + // there should be no further completions. + if helpOrVersionFlagPresent(finalCmd) { + return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil + } + + // We only remove the flags from the arguments if DisableFlagParsing is not set. + // This is important for commands which have requested to do their own flag completion. + if !finalCmd.DisableFlagParsing { + finalArgs = finalCmd.Flags().Args() + } + + if flag != nil && flagCompletion { + // Check if we are completing a flag value subject to annotations + if validExts, present := flag.Annotations[BashCompFilenameExt]; present { + if len(validExts) != 0 { + // File completion filtered by extensions + return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil + } + + // The annotation requests simple file completion. There is no reason to do + // that since it is the default behavior anyway. Let's ignore this annotation + // in case the program also registered a completion function for this flag. + // Even though it is a mistake on the program's side, let's be nice when we can. + } + + if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { + if len(subDir) == 1 { + // Directory completion from within a directory + return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil + } + // Directory completion + return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil + } + } + + var completions []Completion + var directive ShellCompDirective + + // Enforce flag groups before doing flag completions + finalCmd.enforceFlagGroupsForCompletion() + + // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; + // doing this allows for completion of persistent flag names even for commands that disable flag parsing. + // + // When doing completion of a flag name, as soon as an argument starts with + // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires + // the flag name to be complete + if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { + // First check for required flags + completions = completeRequireFlags(finalCmd, toComplete) + + // If we have not found any required flags, only then can we show regular flags + if len(completions) == 0 { + doCompleteFlags := func(flag *pflag.Flag) { + _, acceptsMultiple := flag.Value.(SliceValue) + acceptsMultiple = acceptsMultiple || + strings.Contains(flag.Value.Type(), "Slice") || + strings.Contains(flag.Value.Type(), "Array") || + strings.HasPrefix(flag.Value.Type(), "stringTo") + + if !flag.Changed || acceptsMultiple { + // If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo) + // we suggest it as a completion + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + } + } + + // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands + // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and + // non-inherited flags. + finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteFlags(flag) + }) + // Try to complete non-inherited flags even if DisableFlagParsing==true. + // This allows programs to tell Cobra about flags for completion even + // if the actual parsing of flags is not done by Cobra. + // For instance, Helm uses this to provide flag name completion for + // some of its plugins. + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteFlags(flag) + }) + } + + directive = ShellCompDirectiveNoFileComp + if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { + // If there is a single completion, the shell usually adds a space + // after the completion. We don't want that if the flag ends with an = + directive = ShellCompDirectiveNoSpace + } + + if !finalCmd.DisableFlagParsing { + // If DisableFlagParsing==false, we have completed the flags as known by Cobra; + // we can return what we found. + // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we + // let the logic continue to see if ValidArgsFunction needs to be called. + return finalCmd, completions, directive, nil + } + } else { + directive = ShellCompDirectiveDefault + if flag == nil { + foundLocalNonPersistentFlag := false + // If TraverseChildren is true on the root command we don't check for + // local flags because we can use a local flag on a parent command + if !finalCmd.Root().TraverseChildren { + // Check if there are any local, non-persistent flags on the command-line + localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { + foundLocalNonPersistentFlag = true + } + }) + } + + // Complete subcommand names, including the help command + if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { + // We only complete sub-commands if: + // - there are no arguments on the command-line and + // - there are no local, non-persistent flags on the command-line or TraverseChildren is true + for _, subCmd := range finalCmd.Commands() { + if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { + if strings.HasPrefix(subCmd.Name(), toComplete) { + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) + } + directive = ShellCompDirectiveNoFileComp + } + } + } + + // Complete required flags even without the '-' prefix + completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) + + // Always complete ValidArgs, even if we are completing a subcommand name. + // This is for commands that have both subcommands and ValidArgs. + if len(finalCmd.ValidArgs) > 0 { + if len(finalArgs) == 0 { + // ValidArgs are only for the first argument + for _, validArg := range finalCmd.ValidArgs { + if strings.HasPrefix(validArg, toComplete) { + completions = append(completions, validArg) + } + } + directive = ShellCompDirectiveNoFileComp + + // If no completions were found within commands or ValidArgs, + // see if there are any ArgAliases that should be completed. + if len(completions) == 0 { + for _, argAlias := range finalCmd.ArgAliases { + if strings.HasPrefix(argAlias, toComplete) { + completions = append(completions, argAlias) + } + } + } + } + + // If there are ValidArgs specified (even if they don't match), we stop completion. + // Only one of ValidArgs or ValidArgsFunction can be used for a single command. + return finalCmd, completions, directive, nil + } + + // Let the logic continue so as to add any ValidArgsFunction completions, + // even if we already found sub-commands. + // This is for commands that have subcommands but also specify a ValidArgsFunction. + } + } + + // Find the completion function for the flag or command + var completionFn CompletionFunc + if flag != nil && flagCompletion { + flagCompletionMutex.RLock() + completionFn = flagCompletionFunctions[flag] + flagCompletionMutex.RUnlock() + } else { + completionFn = finalCmd.ValidArgsFunction + } + if completionFn != nil { + // Go custom completion defined for this flag or command. + // Call the registered completion function to get the completions. + var comps []Completion + comps, directive = completionFn(finalCmd, finalArgs, toComplete) + completions = append(completions, comps...) + } + + return finalCmd, completions, directive, nil +} + +func helpOrVersionFlagPresent(cmd *Command) bool { + if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil && + len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { + return true + } + if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil && + len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { + return true + } + return false +} + +func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion { + if nonCompletableFlag(flag) { + return []Completion{} + } + + var completions []Completion + flagName := "--" + flag.Name + if strings.HasPrefix(flagName, toComplete) { + // Flag without the = + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + + // Why suggest both long forms: --flag and --flag= ? + // This forces the user to *always* have to type either an = or a space after the flag name. + // Let's be nice and avoid making users have to do that. + // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. + // The = form will still work, we just won't suggest it. + // This also makes the list of suggested flags shorter as we avoid all the = forms. + // + // if len(flag.NoOptDefVal) == 0 { + // // Flag requires a value, so it can be suffixed with = + // flagName += "=" + // completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + // } + } + + flagName = "-" + flag.Shorthand + if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + } + + return completions +} + +func completeRequireFlags(finalCmd *Command, toComplete string) []Completion { + var completions []Completion + + doCompleteRequiredFlags := func(flag *pflag.Flag) { + if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { + if !flag.Changed { + // If the flag is not already present, we suggest it as a completion + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + } + } + } + + // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands + // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and + // non-inherited flags. + finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteRequiredFlags(flag) + }) + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteRequiredFlags(flag) + }) + + return completions +} + +func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { + if finalCmd.DisableFlagParsing { + // We only do flag completion if we are allowed to parse flags + // This is important for commands which have requested to do their own flag completion. + return nil, args, lastArg, nil + } + + var flagName string + trimmedArgs := args + flagWithEqual := false + orgLastArg := lastArg + + // When doing completion of a flag name, as soon as an argument starts with + // a '-' we know it is a flag. We cannot use isFlagArg() here as that function + // requires the flag name to be complete + if len(lastArg) > 0 && lastArg[0] == '-' { + if index := strings.Index(lastArg, "="); index >= 0 { + // Flag with an = + if strings.HasPrefix(lastArg[:index], "--") { + // Flag has full name + flagName = lastArg[2:index] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = lastArg[index-1 : index] + } + lastArg = lastArg[index+1:] + flagWithEqual = true + } else { + // Normal flag completion + return nil, args, lastArg, nil + } + } + + if len(flagName) == 0 { + if len(args) > 0 { + prevArg := args[len(args)-1] + if isFlagArg(prevArg) { + // Only consider the case where the flag does not contain an =. + // If the flag contains an = it means it has already been fully processed, + // so we don't need to deal with it here. + if index := strings.Index(prevArg, "="); index < 0 { + if strings.HasPrefix(prevArg, "--") { + // Flag has full name + flagName = prevArg[2:] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = prevArg[len(prevArg)-1:] + } + // Remove the uncompleted flag or else there could be an error created + // for an invalid value for that flag + trimmedArgs = args[:len(args)-1] + } + } + } + } + + if len(flagName) == 0 { + // Not doing flag completion + return nil, trimmedArgs, lastArg, nil + } + + flag := findFlag(finalCmd, flagName) + if flag == nil { + // Flag not supported by this command, the interspersed option might be set so return the original args + return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} + } + + if !flagWithEqual { + if len(flag.NoOptDefVal) != 0 { + // We had assumed dealing with a two-word flag but the flag is a boolean flag. + // In that case, there is no value following it, so we are not really doing flag completion. + // Reset everything to do noun completion. + trimmedArgs = args + flag = nil + } + } + + return flag, trimmedArgs, lastArg, nil +} + +// InitDefaultCompletionCmd adds a default 'completion' command to c. +// This function will do nothing if any of the following is true: +// 1- the feature has been explicitly disabled by the program, +// 2- c has no subcommands (to avoid creating one), +// 3- c already has a 'completion' command provided by the program. +func (c *Command) InitDefaultCompletionCmd(args ...string) { + if c.CompletionOptions.DisableDefaultCmd { + return + } + + for _, cmd := range c.commands { + if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { + // A completion command is already available + return + } + } + + haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions + + // Special case to know if there are sub-commands or not. + hasSubCommands := false + for _, cmd := range c.commands { + if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName { + // We found a real sub-command (not 'help' or '__complete') + hasSubCommands = true + break + } + } + + completionCmd := &Command{ + Use: compCmdName, + Short: "Generate the autocompletion script for the specified shell", + Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell. +See each sub-command's help for details on how to use the generated script. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + Hidden: c.CompletionOptions.HiddenDefaultCmd, + GroupID: c.completionCommandGroupID, + } + c.AddCommand(completionCmd) + + if !hasSubCommands { + // If the 'completion' command will be the only sub-command, + // we only create it if it is actually being called. + // This avoids breaking programs that would suddenly find themselves with + // a subcommand, which would prevent them from accepting arguments. + // We also create the 'completion' command if the user is triggering + // shell completion for it (prog __complete completion '') + subCmd, cmdArgs, err := c.Find(args) + if err != nil || subCmd.Name() != compCmdName && + !(subCmd.Name() == ShellCompRequestCmd && len(cmdArgs) > 1 && cmdArgs[0] == compCmdName) { + // The completion command is not being called or being completed so we remove it. + c.RemoveCommand(completionCmd) + return + } + } + + out := c.OutOrStdout() + noDesc := c.CompletionOptions.DisableDescriptions + shortDesc := "Generate the autocompletion script for %s" + bash := &Command{ + Use: "bash", + Short: fmt.Sprintf(shortDesc, "bash"), + Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell. + +This script depends on the 'bash-completion' package. +If it is not installed already, you can install it via your OS's package manager. + +To load completions in your current shell session: + + source <(%[1]s completion bash) + +To load completions for every new session, execute once: + +#### Linux: + + %[1]s completion bash > /etc/bash_completion.d/%[1]s + +#### macOS: + + %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + DisableFlagsInUseLine: true, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenBashCompletionV2(out, !noDesc) + }, + } + if haveNoDescFlag { + bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + zsh := &Command{ + Use: "zsh", + Short: fmt.Sprintf(shortDesc, "zsh"), + Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell. + +If shell completion is not already enabled in your environment you will need +to enable it. You can execute the following once: + + echo "autoload -U compinit; compinit" >> ~/.zshrc + +To load completions in your current shell session: + + source <(%[1]s completion zsh) + +To load completions for every new session, execute once: + +#### Linux: + + %[1]s completion zsh > "${fpath[1]}/_%[1]s" + +#### macOS: + + %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenZshCompletionNoDesc(out) + } + return cmd.Root().GenZshCompletion(out) + }, + } + if haveNoDescFlag { + zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + fish := &Command{ + Use: "fish", + Short: fmt.Sprintf(shortDesc, "fish"), + Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell. + +To load completions in your current shell session: + + %[1]s completion fish | source + +To load completions for every new session, execute once: + + %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenFishCompletion(out, !noDesc) + }, + } + if haveNoDescFlag { + fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + powershell := &Command{ + Use: "powershell", + Short: fmt.Sprintf(shortDesc, "powershell"), + Long: fmt.Sprintf(`Generate the autocompletion script for powershell. + +To load completions in your current shell session: + + %[1]s completion powershell | Out-String | Invoke-Expression + +To load completions for every new session, add the output of the above command +to your powershell profile. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenPowerShellCompletion(out) + } + return cmd.Root().GenPowerShellCompletionWithDesc(out) + + }, + } + if haveNoDescFlag { + powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + completionCmd.AddCommand(bash, zsh, fish, powershell) +} + +func findFlag(cmd *Command, name string) *pflag.Flag { + flagSet := cmd.Flags() + if len(name) == 1 { + // First convert the short flag into a long flag + // as the cmd.Flag() search only accepts long flags + if short := flagSet.ShorthandLookup(name); short != nil { + name = short.Name + } else { + set := cmd.InheritedFlags() + if short = set.ShorthandLookup(name); short != nil { + name = short.Name + } else { + return nil + } + } + } + return cmd.Flag(name) +} + +// CompDebug prints the specified string to the same file as where the +// completion script prints its logs. +// Note that completion printouts should never be on stdout as they would +// be wrongly interpreted as actual completion choices by the completion script. +func CompDebug(msg string, printToStdErr bool) { + msg = fmt.Sprintf("[Debug] %s", msg) + + // Such logs are only printed when the user has set the environment + // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. + if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { + f, err := os.OpenFile(path, + os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err == nil { + defer f.Close() + WriteStringAndCheck(f, msg) + } + } + + if printToStdErr { + // Must print to stderr for this not to be read by the completion script. + fmt.Fprint(os.Stderr, msg) + } +} + +// CompDebugln prints the specified string with a newline at the end +// to the same file as where the completion script prints its logs. +// Such logs are only printed when the user has set the environment +// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. +func CompDebugln(msg string, printToStdErr bool) { + CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) +} + +// CompError prints the specified completion message to stderr. +func CompError(msg string) { + msg = fmt.Sprintf("[Error] %s", msg) + CompDebug(msg, true) +} + +// CompErrorln prints the specified completion message to stderr with a newline at the end. +func CompErrorln(msg string) { + CompError(fmt.Sprintf("%s\n", msg)) +} + +// These values should not be changed: users will be using them explicitly. +const ( + configEnvVarGlobalPrefix = "COBRA" + configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS" +) + +var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) + +// configEnvVar returns the name of the program-specific configuration environment +// variable. It has the format _ where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func configEnvVar(name, suffix string) string { + // This format should not be changed: users will be using it explicitly. + v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix)) + v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_") + return v +} + +// getEnvConfig returns the value of the configuration environment variable +// _ where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// If the value is empty or not set, the value of the environment variable +// COBRA_ is returned instead. +func getEnvConfig(cmd *Command, suffix string) string { + v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix)) + if v == "" { + v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix)) + } + return v +} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go new file mode 100644 index 000000000..12d61b691 --- /dev/null +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -0,0 +1,292 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "strings" +) + +func genFishComp(buf io.StringWriter, name string, includeDesc bool) { + // Variables should not contain a '-' or ':' character + nameForVar := name + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") + + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(` +function __%[1]s_debug + set -l file "$BASH_COMP_DEBUG_FILE" + if test -n "$file" + echo "$argv" >> $file + end +end + +function __%[1]s_perform_completion + __%[1]s_debug "Starting __%[1]s_perform_completion" + + # Extract all args except the last one + set -l args (commandline -opc) + # Extract the last arg and escape it in case it is a space + set -l lastArg (string escape -- (commandline -ct)) + + __%[1]s_debug "args: $args" + __%[1]s_debug "last arg: $lastArg" + + # Disable ActiveHelp which is not supported for fish shell + set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" + + __%[1]s_debug "Calling $requestComp" + set -l results (eval $requestComp 2> /dev/null) + + # Some programs may output extra empty lines after the directive. + # Let's ignore them or else it will break completion. + # Ref: https://github.com/spf13/cobra/issues/1279 + for line in $results[-1..1] + if test (string trim -- $line) = "" + # Found an empty line, remove it + set results $results[1..-2] + else + # Found non-empty line, we have our proper output + break + end + end + + set -l comps $results[1..-2] + set -l directiveLine $results[-1] + + # For Fish, when completing a flag with an = (e.g., -n=) + # completions must be prefixed with the flag + set -l flagPrefix (string match -r -- '-.*=' "$lastArg") + + __%[1]s_debug "Comps: $comps" + __%[1]s_debug "DirectiveLine: $directiveLine" + __%[1]s_debug "flagPrefix: $flagPrefix" + + for comp in $comps + printf "%%s%%s\n" "$flagPrefix" "$comp" + end + + printf "%%s\n" "$directiveLine" +end + +# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result +function __%[1]s_perform_completion_once + __%[1]s_debug "Starting __%[1]s_perform_completion_once" + + if test -n "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion" + return 0 + end + + set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion) + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completions, probably due to a failure" + return 1 + end + + __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result" + return 0 +end + +# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run +function __%[1]s_clear_perform_completion_once_result + __%[1]s_debug "" + __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" + set --erase __%[1]s_perform_completion_once_result + __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" +end + +function __%[1]s_requires_order_preservation + __%[1]s_debug "" + __%[1]s_debug "========= checking if order preservation is required ==========" + + __%[1]s_perform_completion_once + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Error determining if order preservation is required" + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveKeepOrder %[9]d + set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2) + __%[1]s_debug "Keeporder is: $keeporder" + + if test $keeporder -ne 0 + __%[1]s_debug "This does require order preservation" + return 0 + end + + __%[1]s_debug "This doesn't require order preservation" + return 1 +end + + +# This function does two things: +# - Obtain the completions and store them in the global __%[1]s_comp_results +# - Return false if file completion should be performed +function __%[1]s_prepare_completions + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + + # Start fresh + set --erase __%[1]s_comp_results + + __%[1]s_perform_completion_once + __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" + + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completion, probably due to a failure" + # Might as well do file completion, in case it helps + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] + + __%[1]s_debug "Completions are: $__%[1]s_comp_results" + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveError %[4]d + set -l shellCompDirectiveNoSpace %[5]d + set -l shellCompDirectiveNoFileComp %[6]d + set -l shellCompDirectiveFilterFileExt %[7]d + set -l shellCompDirectiveFilterDirs %[8]d + + if test -z "$directive" + set directive 0 + end + + set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) + if test $compErr -eq 1 + __%[1]s_debug "Received error directive: aborting." + # Might as well do file completion, in case it helps + return 1 + end + + set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) + set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) + if test $filefilter -eq 1; or test $dirfilter -eq 1 + __%[1]s_debug "File extension filtering or directory filtering not supported" + # Do full file completion instead + return 1 + end + + set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) + set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) + + __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" + + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than the prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set -l prefix (commandline -t | string escape --style=regex) + __%[1]s_debug "prefix: $prefix" + + set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) + set --global __%[1]s_comp_results $completions + __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" + + # Important not to quote the variable for count to work + set -l numComps (count $__%[1]s_comp_results) + __%[1]s_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # We must first split on \t to get rid of the descriptions to be + # able to check what the actual completion will be. + # We don't need descriptions anyway since there is only a single + # real completion which the shell will expand immediately. + set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) + + # Fish won't add a space if the completion ends with any + # of the following characters: @=/:., + set -l lastChar (string sub -s -1 -- $split) + if not string match -r -q "[@=/:.,]" -- "$lastChar" + # In other cases, to support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + __%[1]s_debug "Adding second completion to perform nospace directive" + set --global __%[1]s_comp_results $split[1] $split[1]. + __%[1]s_debug "Completions are now: $__%[1]s_comp_results" + end + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __%[1]s_debug "Requesting file completion" + return 1 + end + end + + return 0 +end + +# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves +# so we can properly delete any completions provided by another script. +# Only do this if the program can be found, or else fish may print some errors; besides, +# the existing completions will only be loaded if the program can be found. +if type -q "%[2]s" + # The space after the program name is essential to trigger completion for the program + # and not completion of the program name itself. + # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. + complete --do-complete "%[2]s " > /dev/null 2>&1 +end + +# Remove any pre-existing completions for the program since we will be handling all of them. +complete -c %[2]s -e + +# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global +complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result' +# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results +# which provides the program's completion choices. +# If this doesn't require order preservation, we don't use the -k flag +complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +# otherwise we use the -k flag +complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +`, nameForVar, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) +} + +// GenFishCompletion generates fish completion file and writes to the passed writer. +func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genFishComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +// GenFishCompletionFile generates fish completion file. +func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenFishCompletion(outFile, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go new file mode 100644 index 000000000..560612fd3 --- /dev/null +++ b/vendor/github.com/spf13/cobra/flag_groups.go @@ -0,0 +1,290 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "sort" + "strings" + + flag "github.com/spf13/pflag" +) + +const ( + requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" + oneRequiredAnnotation = "cobra_annotation_one_required" + mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" +) + +// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors +// if the command is invoked with a subset (but not all) of the given flags. +func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) + } + if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + +// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors +// if the command is invoked without at least one flag from the given set of flags. +func (c *Command) MarkFlagsOneRequired(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) + } + if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + +// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors +// if the command is invoked with more than one flag from the given set of flags. +func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v)) + } + // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. + if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { + panic(err) + } + } +} + +// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the +// first error encountered. +func (c *Command) ValidateFlagGroups() error { + if c.DisableFlagParsing { + return nil + } + + flags := c.Flags() + + // groupStatus format is the list of flags as a unique ID, + // then a map of each flag name and whether it is set or not. + groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} + mutuallyExclusiveGroupStatus := map[string]map[string]bool{} + flags.VisitAll(func(pflag *flag.Flag) { + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) + }) + + if err := validateRequiredFlagGroups(groupStatus); err != nil { + return err + } + if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { + return err + } + if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { + return err + } + return nil +} + +func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool { + for _, fname := range flagnames { + f := fs.Lookup(fname) + if f == nil { + return false + } + } + return true +} + +func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) { + groupInfo, found := pflag.Annotations[annotation] + if found { + for _, group := range groupInfo { + if groupStatus[group] == nil { + flagnames := strings.Split(group, " ") + + // Only consider this flag group at all if all the flags are defined. + if !hasAllFlags(flags, flagnames...) { + continue + } + + groupStatus[group] = make(map[string]bool, len(flagnames)) + for _, name := range flagnames { + groupStatus[group][name] = false + } + } + + groupStatus[group][pflag.Name] = pflag.Changed + } + } +} + +func validateRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + + unset := []string{} + for flagname, isSet := range flagnameAndStatus { + if !isSet { + unset = append(unset, flagname) + } + } + if len(unset) == len(flagnameAndStatus) || len(unset) == 0 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(unset) + return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset) + } + + return nil +} + +func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) >= 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) + } + return nil +} + +func validateExclusiveFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) == 0 || len(set) == 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set) + } + return nil +} + +func sortedKeys(m map[string]map[string]bool) []string { + keys := make([]string, len(m)) + i := 0 + for k := range m { + keys[i] = k + i++ + } + sort.Strings(keys) + return keys +} + +// enforceFlagGroupsForCompletion will do the following: +// - when a flag in a group is present, other flags in the group will be marked required +// - when none of the flags in a one-required group are present, all flags in the group will be marked required +// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden +// This allows the standard completion logic to behave appropriately for flag groups +func (c *Command) enforceFlagGroupsForCompletion() { + if c.DisableFlagParsing { + return + } + + flags := c.Flags() + groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} + mutuallyExclusiveGroupStatus := map[string]map[string]bool{} + c.Flags().VisitAll(func(pflag *flag.Flag) { + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) + }) + + // If a flag that is part of a group is present, we make all the other flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range groupStatus { + for _, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the group is set, mark the other ones as required + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + } + + // If none of the flags of a one-required group are present, we make all the flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range oneRequiredGroupStatus { + isSet := false + + for _, isSet = range flagnameAndStatus { + if isSet { + break + } + } + + // None of the flags of the group are set, mark all flags in the group + // as required + if !isSet { + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + + // If a flag that is mutually exclusive to others is present, we hide the other + // flags of that group so the shell completion does not suggest them + for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { + for flagName, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the mutually exclusive group is set, mark the other ones as hidden + // Don't mark the flag that is already set as hidden because it may be an + // array or slice flag and therefore must continue being suggested + for _, fName := range strings.Split(flagList, " ") { + if fName != flagName { + flag := c.Flags().Lookup(fName) + flag.Hidden = true + } + } + } + } + } +} diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go new file mode 100644 index 000000000..746dcb92e --- /dev/null +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -0,0 +1,350 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but +// can be downloaded separately for windows 7 or 8.1). + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "strings" +) + +func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { + // Variables should not contain a '-' or ':' character + nameForVar := name + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") + + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*- + +function __%[1]s_debug { + if ($env:BASH_COMP_DEBUG_FILE) { + "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" + } +} + +filter __%[1]s_escapeStringWithSpecialChars { +`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` +} + +[scriptblock]${__%[2]sCompleterBlock} = { + param( + $WordToComplete, + $CommandAst, + $CursorPosition + ) + + # Get the current command line and convert into a string + $Command = $CommandAst.CommandElements + $Command = "$Command" + + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CursorPosition location, so we need + # to truncate the command-line ($Command) up to the $CursorPosition location. + # Make sure the $Command is longer then the $CursorPosition before we truncate. + # This happens because the $Command does not include the last space. + if ($Command.Length -gt $CursorPosition) { + $Command=$Command.Substring(0,$CursorPosition) + } + __%[1]s_debug "Truncated command: $Command" + + $ShellCompDirectiveError=%[4]d + $ShellCompDirectiveNoSpace=%[5]d + $ShellCompDirectiveNoFileComp=%[6]d + $ShellCompDirectiveFilterFileExt=%[7]d + $ShellCompDirectiveFilterDirs=%[8]d + $ShellCompDirectiveKeepOrder=%[9]d + + # Prepare the command to request completions for the program. + # Split the command at the first space to separate the program and arguments. + $Program,$Arguments = $Command.Split(" ",2) + + $RequestComp="$Program %[3]s $Arguments" + __%[1]s_debug "RequestComp: $RequestComp" + + # we cannot use $WordToComplete because it + # has the wrong values if the cursor was moved + # so use the last argument + if ($WordToComplete -ne "" ) { + $WordToComplete = $Arguments.Split(" ")[-1] + } + __%[1]s_debug "New WordToComplete: $WordToComplete" + + + # Check for flag with equal sign + $IsEqualFlag = ($WordToComplete -Like "--*=*" ) + if ( $IsEqualFlag ) { + __%[1]s_debug "Completing equal sign flag" + # Remove the flag part + $Flag,$WordToComplete = $WordToComplete.Split("=",2) + } + + if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "Adding extra empty parameter" + # PowerShell 7.2+ changed the way how the arguments are passed to executables, + # so for pre-7.2 or when Legacy argument passing is enabled we need to use +`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+` + if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or + ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or + (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and + $PSNativeCommandArgumentPassing -eq 'Legacy')) { +`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` + } else { + $RequestComp="$RequestComp" + ' ""' + } + } + + __%[1]s_debug "Calling $RequestComp" + # First disable ActiveHelp which is not supported for Powershell + ${env:%[10]s}=0 + + #call the command store the output in $out and redirect stderr and stdout to null + # $Out is an array contains each line per element + Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null + + # get directive from last line + [int]$Directive = $Out[-1].TrimStart(':') + if ($Directive -eq "") { + # There is no directive specified + $Directive = 0 + } + __%[1]s_debug "The completion directive is: $Directive" + + # remove directive (last element) from out + $Out = $Out | Where-Object { $_ -ne $Out[-1] } + __%[1]s_debug "The completions are: $Out" + + if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { + # Error code. No completion. + __%[1]s_debug "Received error from custom completion go code" + return + } + + $Longest = 0 + [Array]$Values = $Out | ForEach-Object { + #Split the output in name and description +`+" $Name, $Description = $_.Split(\"`t\",2)"+` + __%[1]s_debug "Name: $Name Description: $Description" + + # Look for the longest completion so that we can format things nicely + if ($Longest -lt $Name.Length) { + $Longest = $Name.Length + } + + # Set the description to a one space string if there is none set. + # This is needed because the CompletionResult does not accept an empty string as argument + if (-Not $Description) { + $Description = " " + } + New-Object -TypeName PSCustomObject -Property @{ + Name = "$Name" + Description = "$Description" + } + } + + + $Space = " " + if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { + # remove the space here + __%[1]s_debug "ShellCompDirectiveNoSpace is called" + $Space = "" + } + + if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or + (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { + __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" + + # return here to prevent the completion of the extensions + return + } + + $Values = $Values | Where-Object { + # filter the result + $_.Name -like "$WordToComplete*" + + # Join the flag back if we have an equal sign flag + if ( $IsEqualFlag ) { + __%[1]s_debug "Join the equal sign flag back to the completion value" + $_.Name = $Flag + "=" + $_.Name + } + } + + # we sort the values in ascending order by name if keep order isn't passed + if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { + $Values = $Values | Sort-Object -Property Name + } + + if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { + __%[1]s_debug "ShellCompDirectiveNoFileComp is called" + + if ($Values.Length -eq 0) { + # Just print an empty string here so the + # shell does not start to complete paths. + # We cannot use CompletionResult here because + # it does not accept an empty string as argument. + "" + return + } + } + + # Get the current mode + $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function + __%[1]s_debug "Mode: $Mode" + + $Values | ForEach-Object { + + # store temporary because switch will overwrite $_ + $comp = $_ + + # PowerShell supports three different completion modes + # - TabCompleteNext (default windows style - on each key press the next option is displayed) + # - Complete (works like bash) + # - MenuComplete (works like zsh) + # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function + + # CompletionResult Arguments: + # 1) CompletionText text to be used as the auto completion result + # 2) ListItemText text to be displayed in the suggestion list + # 3) ResultType type of completion result + # 4) ToolTip text for the tooltip with details about the object + + switch ($Mode) { + + # bash like + "Complete" { + + if ($Values.Length -eq 1) { + __%[1]s_debug "Only one completion left" + + # insert space after value + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + + } else { + # Add the proper number of spaces to align the descriptions + while($comp.Name.Length -lt $Longest) { + $comp.Name = $comp.Name + " " + } + + # Check for empty description and only add parentheses if needed + if ($($comp.Description) -eq " " ) { + $Description = "" + } else { + $Description = " ($($comp.Description))" + } + + $CompletionText = "$($comp.Name)$Description" + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + } + + # zsh like + "MenuComplete" { + # insert space after value + # MenuComplete will automatically show the ToolTip of + # the highlighted value at the bottom of the suggestions. + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + + # TabCompleteNext and in case we get something unknown + Default { + # Like MenuComplete but we don't want to add a space here because + # the user need to press space anyway to get the completion. + # Description will not be shown because that's not possible with TabCompleteNext + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + } + + } +} + +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} +`, name, nameForVar, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) +} + +func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genPowerShellComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.genPowerShellCompletion(outFile, includeDesc) +} + +// GenPowerShellCompletionFile generates powershell completion file without descriptions. +func (c *Command) GenPowerShellCompletionFile(filename string) error { + return c.genPowerShellCompletionFile(filename, false) +} + +// GenPowerShellCompletion generates powershell completion file without descriptions +// and writes it to the passed writer. +func (c *Command) GenPowerShellCompletion(w io.Writer) error { + return c.genPowerShellCompletion(w, false) +} + +// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. +func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error { + return c.genPowerShellCompletionFile(filename, true) +} + +// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions +// and writes it to the passed writer. +func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error { + return c.genPowerShellCompletion(w, true) +} diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go new file mode 100644 index 000000000..b035742d3 --- /dev/null +++ b/vendor/github.com/spf13/cobra/shell_completions.go @@ -0,0 +1,98 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "github.com/spf13/pflag" +) + +// MarkFlagRequired instructs the various shell completion implementations to +// prioritize the named flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkFlagRequired(name string) error { + return MarkFlagRequired(c.Flags(), name) +} + +// MarkPersistentFlagRequired instructs the various shell completion implementations to +// prioritize the named persistent flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkPersistentFlagRequired(name string) error { + return MarkFlagRequired(c.PersistentFlags(), name) +} + +// MarkFlagRequired instructs the various shell completion implementations to +// prioritize the named flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func MarkFlagRequired(flags *pflag.FlagSet, name string) error { + return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) +} + +// MarkFlagFilename instructs the various shell completion implementations to +// limit completions for the named flag to the specified file extensions. +func (c *Command) MarkFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.Flags(), name, extensions...) +} + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// The bash completion script will call the bash function f for the flag. +// +// This will only work for bash completion. +// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows +// to register a Go function which will work across all shells. +func (c *Command) MarkFlagCustom(name string, f string) error { + return MarkFlagCustom(c.Flags(), name, f) +} + +// MarkPersistentFlagFilename instructs the various shell completion +// implementations to limit completions for the named persistent flag to the +// specified file extensions. +func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.PersistentFlags(), name, extensions...) +} + +// MarkFlagFilename instructs the various shell completion implementations to +// limit completions for the named flag to the specified file extensions. +func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { + return flags.SetAnnotation(name, BashCompFilenameExt, extensions) +} + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// The bash completion script will call the bash function f for the flag. +// +// This will only work for bash completion. +// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows +// to register a Go function which will work across all shells. +func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { + return flags.SetAnnotation(name, BashCompCustom, []string{f}) +} + +// MarkFlagDirname instructs the various shell completion implementations to +// limit completions for the named flag to directory names. +func (c *Command) MarkFlagDirname(name string) error { + return MarkFlagDirname(c.Flags(), name) +} + +// MarkPersistentFlagDirname instructs the various shell completion +// implementations to limit completions for the named persistent flag to +// directory names. +func (c *Command) MarkPersistentFlagDirname(name string) error { + return MarkFlagDirname(c.PersistentFlags(), name) +} + +// MarkFlagDirname instructs the various shell completion implementations to +// limit completions for the named flag to directory names. +func MarkFlagDirname(flags *pflag.FlagSet, name string) error { + return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{}) +} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go new file mode 100644 index 000000000..1856e4c7f --- /dev/null +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -0,0 +1,308 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// GenZshCompletionFile generates zsh completion file including descriptions. +func (c *Command) GenZshCompletionFile(filename string) error { + return c.genZshCompletionFile(filename, true) +} + +// GenZshCompletion generates zsh completion file including descriptions +// and writes it to the passed writer. +func (c *Command) GenZshCompletion(w io.Writer) error { + return c.genZshCompletion(w, true) +} + +// GenZshCompletionFileNoDesc generates zsh completion file without descriptions. +func (c *Command) GenZshCompletionFileNoDesc(filename string) error { + return c.genZshCompletionFile(filename, false) +} + +// GenZshCompletionNoDesc generates zsh completion file without descriptions +// and writes it to the passed writer. +func (c *Command) GenZshCompletionNoDesc(w io.Writer) error { + return c.genZshCompletion(w, false) +} + +// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was +// not consistent with Bash completion. It has therefore been disabled. +// Instead, when no other completion is specified, file completion is done by +// default for every argument. One can disable file completion on a per-argument +// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. +// To achieve file extension filtering, one can use ValidArgsFunction and +// ShellCompDirectiveFilterFileExt. +// +// Deprecated +func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error { + return nil +} + +// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore +// been disabled. +// To achieve the same behavior across all shells, one can use +// ValidArgs (for the first argument only) or ValidArgsFunction for +// any argument (can include the first one also). +// +// Deprecated +func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error { + return nil +} + +func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.genZshCompletion(outFile, includeDesc) +} + +func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genZshComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func genZshComp(buf io.StringWriter, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s +compdef _%[1]s %[1]s + +# zsh completion for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() +{ + local file="$BASH_COMP_DEBUG_FILE" + if [[ -n ${file} ]]; then + echo "$*" >> "${file}" + fi +} + +_%[1]s() +{ + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d + + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder + local -a completions + + __%[1]s_debug "\n========= starting completion logic ==========" + __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," + + lastParam=${words[-1]} + lastChar=${lastParam[-1]} + __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" + + # For zsh, when completing a flag with an = (e.g., %[1]s -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi + + # Prepare the command to obtain completions + requestComp="${words[1]} %[2]s ${words[2,-1]}" + if [ "${lastChar}" = "" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go completion code. + __%[1]s_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __%[1]s_debug "About to call: eval ${requestComp}" + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + __%[1]s_debug "completion output: ${out}" + + # Extract the directive integer following a : from the last line + local lastLine + while IFS='\n' read -r line; do + lastLine=${line} + done < <(printf "%%s\n" "${out[@]}") + __%[1]s_debug "last line: ${lastLine}" + + if [ "${lastLine[1]}" = : ]; then + directive=${lastLine[2,-1]} + # Remove the directive including the : and the newline + local suffix + (( suffix=${#lastLine}+2)) + out=${out[1,-$suffix]} + else + # There is no directive specified. Leave $out as is. + __%[1]s_debug "No directive found. Setting do default" + directive=0 + fi + + __%[1]s_debug "directive: ${directive}" + __%[1]s_debug "completions: ${out}" + __%[1]s_debug "flagPrefix: ${flagPrefix}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + __%[1]s_debug "Completion received error. Ignoring completions." + return + fi + + local activeHelpMarker="%[9]s" + local endIndex=${#activeHelpMarker} + local startIndex=$((${#activeHelpMarker}+1)) + local hasActiveHelp=0 + while IFS='\n' read -r comp; do + # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker) + if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then + __%[1]s_debug "ActiveHelp found: $comp" + comp="${comp[$startIndex,-1]}" + if [ -n "$comp" ]; then + compadd -x "${comp}" + __%[1]s_debug "ActiveHelp will need delimiter" + hasActiveHelp=1 + fi + + continue + fi + + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} + + local tab="$(printf '\t')" + comp=${comp//$tab/:} + + __%[1]s_debug "Adding completion: ${comp}" + completions+=${comp} + lastComp=$comp + fi + done < <(printf "%%s\n" "${out[@]}") + + # Add a delimiter after the activeHelp statements, but only if: + # - there are completions following the activeHelp statements, or + # - file completion will be performed (so there will be choices after the activeHelp) + if [ $hasActiveHelp -eq 1 ]; then + if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then + __%[1]s_debug "Adding activeHelp delimiter" + compadd -x "--" + hasActiveHelp=0 + fi + fi + + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __%[1]s_debug "Activating nospace." + noSpace="-S ''" + fi + + if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then + __%[1]s_debug "Activating keep order." + keepOrder="-V" + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local filteringCmd + filteringCmd='_files' + for filter in ${completions[@]}; do + if [ ${filter[1]} != '*' ]; then + # zsh requires a glob pattern to do file filtering + filter="\*.$filter" + fi + filteringCmd+=" -g $filter" + done + filteringCmd+=" ${flagPrefix}" + + __%[1]s_debug "File filtering command: $filteringCmd" + _arguments '*:filename:'"$filteringCmd" + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subdir + subdir="${completions[1]}" + if [ -n "$subdir" ]; then + __%[1]s_debug "Listing directories in $subdir" + pushd "${subdir}" >/dev/null 2>&1 + else + __%[1]s_debug "Listing directories in ." + fi + + local result + _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? + if [ -n "$subdir" ]; then + popd >/dev/null 2>&1 + fi + return $result + else + __%[1]s_debug "Calling _describe" + if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then + __%[1]s_debug "_describe found some completions" + + # Return the success of having called _describe + return 0 + else + __%[1]s_debug "_describe did not find completions." + __%[1]s_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __%[1]s_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __%[1]s_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi + fi + fi +} + +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_%[1]s" ]; then + _%[1]s +fi +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, + activeHelpMarker)) +} diff --git a/vendor/github.com/spf13/pflag/.editorconfig b/vendor/github.com/spf13/pflag/.editorconfig new file mode 100644 index 000000000..4492e9f9f --- /dev/null +++ b/vendor/github.com/spf13/pflag/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.go] +indent_style = tab diff --git a/vendor/github.com/spf13/pflag/.golangci.yaml b/vendor/github.com/spf13/pflag/.golangci.yaml new file mode 100644 index 000000000..b274f2484 --- /dev/null +++ b/vendor/github.com/spf13/pflag/.golangci.yaml @@ -0,0 +1,4 @@ +linters: + disable-all: true + enable: + - nolintlint diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 24a5036e9..7c058de37 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -160,7 +160,7 @@ type FlagSet struct { args []string // arguments after flags argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- errorHandling ErrorHandling - output io.Writer // nil means stderr; use out() accessor + output io.Writer // nil means stderr; use Output() accessor interspersed bool // allow interspersed option/non-option args normalizeNameFunc func(f *FlagSet, name string) NormalizedName @@ -255,13 +255,20 @@ func (f *FlagSet) normalizeFlagName(name string) NormalizedName { return n(f, name) } -func (f *FlagSet) out() io.Writer { +// Output returns the destination for usage and error messages. os.Stderr is returned if +// output was not set or was set to nil. +func (f *FlagSet) Output() io.Writer { if f.output == nil { return os.Stderr } return f.output } +// Name returns the name of the flag set. +func (f *FlagSet) Name() string { + return f.name +} + // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (f *FlagSet) SetOutput(output io.Writer) { @@ -358,7 +365,7 @@ func (f *FlagSet) ShorthandLookup(name string) *Flag { } if len(name) > 1 { msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) - fmt.Fprintf(f.out(), msg) + fmt.Fprintf(f.Output(), msg) panic(msg) } c := name[0] @@ -482,7 +489,7 @@ func (f *FlagSet) Set(name, value string) error { } if flag.Deprecated != "" { - fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) + fmt.Fprintf(f.Output(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) } return nil } @@ -523,7 +530,7 @@ func Set(name, value string) error { // otherwise, the default values of all defined flags in the set. func (f *FlagSet) PrintDefaults() { usages := f.FlagUsages() - fmt.Fprint(f.out(), usages) + fmt.Fprint(f.Output(), usages) } // defaultIsZeroValue returns true if the default value for this flag represents @@ -758,7 +765,7 @@ func PrintDefaults() { // defaultUsage is the default function to print a usage message. func defaultUsage(f *FlagSet) { - fmt.Fprintf(f.out(), "Usage of %s:\n", f.name) + fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name) f.PrintDefaults() } @@ -844,7 +851,7 @@ func (f *FlagSet) AddFlag(flag *Flag) { _, alreadyThere := f.formal[normalizedFlagName] if alreadyThere { msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) - fmt.Fprintln(f.out(), msg) + fmt.Fprintln(f.Output(), msg) panic(msg) // Happens only if flags are declared with identical names } if f.formal == nil { @@ -860,7 +867,7 @@ func (f *FlagSet) AddFlag(flag *Flag) { } if len(flag.Shorthand) > 1 { msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) - fmt.Fprintf(f.out(), msg) + fmt.Fprintf(f.Output(), msg) panic(msg) } if f.shorthands == nil { @@ -870,7 +877,7 @@ func (f *FlagSet) AddFlag(flag *Flag) { used, alreadyThere := f.shorthands[c] if alreadyThere { msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) - fmt.Fprintf(f.out(), msg) + fmt.Fprintf(f.Output(), msg) panic(msg) } f.shorthands[c] = flag @@ -909,7 +916,7 @@ func VarP(value Value, name, shorthand, usage string) { func (f *FlagSet) failf(format string, a ...interface{}) error { err := fmt.Errorf(format, a...) if f.errorHandling != ContinueOnError { - fmt.Fprintln(f.out(), err) + fmt.Fprintln(f.Output(), err) f.usage() } return err @@ -1060,7 +1067,7 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse } if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) + fmt.Fprintf(f.Output(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) } err = fn(flag, value) diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go index 3d414ba69..06b8bcb57 100644 --- a/vendor/github.com/spf13/pflag/ip.go +++ b/vendor/github.com/spf13/pflag/ip.go @@ -16,6 +16,9 @@ func newIPValue(val net.IP, p *net.IP) *ipValue { func (i *ipValue) String() string { return net.IP(*i).String() } func (i *ipValue) Set(s string) error { + if s == "" { + return nil + } ip := net.ParseIP(strings.TrimSpace(s)) if ip == nil { return fmt.Errorf("failed to parse IP: %q", s) diff --git a/vendor/github.com/spf13/pflag/ipnet_slice.go b/vendor/github.com/spf13/pflag/ipnet_slice.go new file mode 100644 index 000000000..6b541aa87 --- /dev/null +++ b/vendor/github.com/spf13/pflag/ipnet_slice.go @@ -0,0 +1,147 @@ +package pflag + +import ( + "fmt" + "io" + "net" + "strings" +) + +// -- ipNetSlice Value +type ipNetSliceValue struct { + value *[]net.IPNet + changed bool +} + +func newIPNetSliceValue(val []net.IPNet, p *[]net.IPNet) *ipNetSliceValue { + ipnsv := new(ipNetSliceValue) + ipnsv.value = p + *ipnsv.value = val + return ipnsv +} + +// Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag. +// If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended. +func (s *ipNetSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + ipNetStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse ip values into slice + out := make([]net.IPNet, 0, len(ipNetStrSlice)) + for _, ipNetStr := range ipNetStrSlice { + _, n, err := net.ParseCIDR(strings.TrimSpace(ipNetStr)) + if err != nil { + return fmt.Errorf("invalid string being converted to CIDR: %s", ipNetStr) + } + out = append(out, *n) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *ipNetSliceValue) Type() string { + return "ipNetSlice" +} + +// String defines a "native" format for this net.IPNet slice flag value. +func (s *ipNetSliceValue) String() string { + + ipNetStrSlice := make([]string, len(*s.value)) + for i, n := range *s.value { + ipNetStrSlice[i] = n.String() + } + + out, _ := writeAsCSV(ipNetStrSlice) + return "[" + out + "]" +} + +func ipNetSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Emtpy string would cause a slice with one (empty) entry + if len(val) == 0 { + return []net.IPNet{}, nil + } + ss := strings.Split(val, ",") + out := make([]net.IPNet, len(ss)) + for i, sval := range ss { + _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) + if err != nil { + return nil, fmt.Errorf("invalid string being converted to CIDR: %s", sval) + } + out[i] = *n + } + return out, nil +} + +// GetIPNetSlice returns the []net.IPNet value of a flag with the given name +func (f *FlagSet) GetIPNetSlice(name string) ([]net.IPNet, error) { + val, err := f.getFlagType(name, "ipNetSlice", ipNetSliceConv) + if err != nil { + return []net.IPNet{}, err + } + return val.([]net.IPNet), nil +} + +// IPNetSliceVar defines a ipNetSlice flag with specified name, default value, and usage string. +// The argument p points to a []net.IPNet variable in which to store the value of the flag. +func (f *FlagSet) IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { + f.VarP(newIPNetSliceValue(value, p), name, "", usage) +} + +// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { + f.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) +} + +// IPNetSliceVar defines a []net.IPNet flag with specified name, default value, and usage string. +// The argument p points to a []net.IPNet variable in which to store the value of the flag. +func IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { + CommandLine.VarP(newIPNetSliceValue(value, p), name, "", usage) +} + +// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. +func IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { + CommandLine.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) +} + +// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of a []net.IPNet variable that stores the value of that flag. +func (f *FlagSet) IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { + p := []net.IPNet{} + f.IPNetSliceVarP(&p, name, "", value, usage) + return &p +} + +// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { + p := []net.IPNet{} + f.IPNetSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of the flag. +func IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { + return CommandLine.IPNetSliceP(name, "", value, usage) +} + +// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. +func IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { + return CommandLine.IPNetSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go index 4894af818..d1ff0a96b 100644 --- a/vendor/github.com/spf13/pflag/string_array.go +++ b/vendor/github.com/spf13/pflag/string_array.go @@ -31,11 +31,7 @@ func (s *stringArrayValue) Append(val string) error { func (s *stringArrayValue) Replace(val []string) error { out := make([]string, len(val)) for i, d := range val { - var err error out[i] = d - if err != nil { - return err - } } *s.value = out return nil diff --git a/vendor/go.yaml.in/yaml/v2/.travis.yml b/vendor/go.yaml.in/yaml/v2/.travis.yml new file mode 100644 index 000000000..7348c50c0 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/.travis.yml @@ -0,0 +1,17 @@ +language: go + +go: + - "1.4.x" + - "1.5.x" + - "1.6.x" + - "1.7.x" + - "1.8.x" + - "1.9.x" + - "1.10.x" + - "1.11.x" + - "1.12.x" + - "1.13.x" + - "1.14.x" + - "tip" + +go_import_path: gopkg.in/yaml.v2 diff --git a/vendor/go.yaml.in/yaml/v2/LICENSE b/vendor/go.yaml.in/yaml/v2/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/go.yaml.in/yaml/v2/LICENSE.libyaml b/vendor/go.yaml.in/yaml/v2/LICENSE.libyaml new file mode 100644 index 000000000..8da58fbf6 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/LICENSE.libyaml @@ -0,0 +1,31 @@ +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original copyright and license: + + apic.go + emitterc.go + parserc.go + readerc.go + scannerc.go + writerc.go + yamlh.go + yamlprivateh.go + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/go.yaml.in/yaml/v2/NOTICE b/vendor/go.yaml.in/yaml/v2/NOTICE new file mode 100644 index 000000000..866d74a7a --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/go.yaml.in/yaml/v2/README.md b/vendor/go.yaml.in/yaml/v2/README.md new file mode 100644 index 000000000..c9388da42 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/README.md @@ -0,0 +1,131 @@ +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.1 and 1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *go.yaml.in/yaml/v2*. + +To install it, run: + + go get go.yaml.in/yaml/v2 + +API documentation +----------------- + +See: + +API stability +------------- + +The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "go.yaml.in/yaml/v2" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/go.yaml.in/yaml/v2/apic.go b/vendor/go.yaml.in/yaml/v2/apic.go new file mode 100644 index 000000000..acf71402c --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/apic.go @@ -0,0 +1,744 @@ +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +var disableLineWrapping = false + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + } + if disableLineWrapping { + emitter.best_width = -1 + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +//// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +///* +// * Create ALIAS. +// */ +// +//YAML_DECLARE(int) +//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) +//{ +// mark yaml_mark_t = { 0, 0, 0 } +// anchor_copy *yaml_char_t = NULL +// +// assert(event) // Non-NULL event object is expected. +// assert(anchor) // Non-NULL anchor is expected. +// +// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 +// +// anchor_copy = yaml_strdup(anchor) +// if (!anchor_copy) +// return 0 +// +// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) +// +// return 1 +//} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/go.yaml.in/yaml/v2/decode.go b/vendor/go.yaml.in/yaml/v2/decode.go new file mode 100644 index 000000000..129bc2a97 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/decode.go @@ -0,0 +1,815 @@ +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +const ( + documentNode = 1 << iota + mappingNode + sequenceNode + scalarNode + aliasNode +) + +type node struct { + kind int + line, column int + tag string + // For an alias node, alias holds the resolved alias. + alias *node + value string + implicit bool + children []*node + anchors map[string]*node +} + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *node + doneInit bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *node, anchor []byte) { + if anchor != nil { + p.doc.anchors[string(anchor)] = n + } +} + +func (p *parser) parse() *node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + default: + panic("attempted to parse unknown event: " + p.event.typ.String()) + } +} + +func (p *parser) node(kind int) *node { + return &node{ + kind: kind, + line: p.event.start_mark.line, + column: p.event.start_mark.column, + } +} + +func (p *parser) document() *node { + n := p.node(documentNode) + n.anchors = make(map[string]*node) + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + n.children = append(n.children, p.parse()) + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *node { + n := p.node(aliasNode) + n.value = string(p.event.anchor) + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *node { + n := p.node(scalarNode) + n.value = string(p.event.value) + n.tag = string(p.event.tag) + n.implicit = p.event.implicit + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *node { + n := p.node(sequenceNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + n.children = append(n.children, p.parse()) + } + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *node { + n := p.node(mappingNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + n.children = append(n.children, p.parse(), p.parse()) + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *node + aliases map[*node]bool + mapType reflect.Type + terrors []string + strict bool + + decodeCount int + aliasCount int + aliasDepth int +} + +var ( + mapItemType = reflect.TypeOf(MapItem{}) + durationType = reflect.TypeOf(time.Duration(0)) + defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = defaultMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder(strict bool) *decoder { + d := &decoder{mapType: defaultMapType, strict: strict} + d.aliases = make(map[*node]bool) + return d +} + +func (d *decoder) terror(n *node, tag string, out reflect.Value) { + if n.tag != "" { + tag = n.tag + } + value := n.value + if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + if u, ok := out.Addr().Interface().(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + switch n.kind { + case documentNode: + return d.document(n, out) + case aliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.kind { + case scalarNode: + good = d.scalar(n, out) + case mappingNode: + good = d.mapping(n, out) + case sequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) + } + return good +} + +func (d *decoder) document(n *node, out reflect.Value) (good bool) { + if len(n.children) == 1 { + d.doc = n + d.unmarshal(n.children[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) scalar(n *node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.tag == "" && !n.implicit { + tag = yaml_STR_TAG + resolved = n.value + } else { + tag, resolved = resolve(n.tag, n.value) + if tag == yaml_BINARY_TAG { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.Kind() == reflect.Map && !out.CanAddr() { + resetMap(out) + } else { + out.Set(reflect.Zero(out.Type())) + } + return true + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == yaml_BINARY_TAG { + out.SetString(resolved.(string)) + return true + } + if resolved != nil { + out.SetString(n.value) + return true + } + case reflect.Interface: + if resolved == nil { + out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) + } else { + out.Set(reflect.ValueOf(resolved)) + } + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch resolved := resolved.(type) { + case int: + if !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + if out.Type().Elem() == reflect.TypeOf(resolved) { + // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? + elem := reflect.New(out.Type().Elem()) + elem.Elem().Set(reflect.ValueOf(resolved)) + out.Set(elem) + return true + } + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { + l := len(n.children) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, yaml_SEQ_TAG, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.children[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Slice: + return d.mappingSlice(n, out) + case reflect.Map: + // okay + case reflect.Interface: + if d.mapType.Kind() == reflect.Map { + iface := out + out = reflect.MakeMap(d.mapType) + iface.Set(out) + } else { + slicev := reflect.New(d.mapType).Elem() + if !d.mappingSlice(n, slicev) { + return false + } + out.Set(slicev) + return true + } + default: + d.terror(n, yaml_MAP_TAG, out) + return false + } + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + mapType := d.mapType + if outt.Key() == ifaceType && outt.Elem() == ifaceType { + d.mapType = outt + } + + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + l := len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.children[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.children[i+1], e) { + d.setMapIndex(n.children[i+1], out, k, e) + } + } + } + d.mapType = mapType + return true +} + +func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) +} + +func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { + outt := out.Type() + if outt.Elem() != mapItemType { + d.terror(n, yaml_MAP_TAG, out) + return false + } + + mapType := d.mapType + d.mapType = outt + + var slice []MapItem + var l = len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + item := MapItem{} + k := reflect.ValueOf(&item.Key).Elem() + if d.unmarshal(n.children[i], k) { + v := reflect.ValueOf(&item.Value).Elem() + if d.unmarshal(n.children[i+1], v) { + slice = append(slice, item) + } + } + } + out.Set(reflect.ValueOf(slice)) + d.mapType = mapType + return true +} + +func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + name := settableValueOf("") + l := len(n.children) + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } + + var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + for i := 0; i < l; i += 2 { + ni := n.children[i] + if isMerge(ni) { + d.merge(n.children[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = out.FieldByIndex(info.Inline) + } + d.unmarshal(n.children[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.children[i+1], value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) + } else if d.strict { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) + } + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(n *node, out reflect.Value) { + switch n.kind { + case mappingNode: + d.unmarshal(n, out) + case aliasNode: + if n.alias != nil && n.alias.kind != mappingNode { + failWantMap() + } + d.unmarshal(n, out) + case sequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.children) - 1; i >= 0; i-- { + ni := n.children[i] + if ni.kind == aliasNode { + if ni.alias != nil && ni.alias.kind != mappingNode { + failWantMap() + } + } else if ni.kind != mappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } +} + +func isMerge(n *node) bool { + return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) +} diff --git a/vendor/go.yaml.in/yaml/v2/emitterc.go b/vendor/go.yaml.in/yaml/v2/emitterc.go new file mode 100644 index 000000000..a1c2cc526 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/emitterc.go @@ -0,0 +1,1685 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + emitter.column = 0 + emitter.line++ + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + emitter.column = 0 + emitter.line++ + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + emitter.indent += emitter.best_indent + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + return yaml_emitter_emit_node(emitter, event, true, false, false, false) +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + emitter.indention = true + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + emitter.whitespace = false + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} diff --git a/vendor/go.yaml.in/yaml/v2/encode.go b/vendor/go.yaml.in/yaml/v2/encode.go new file mode 100644 index 000000000..0ee738e11 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/encode.go @@ -0,0 +1,390 @@ +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// jsonNumber is the interface of the encoding/json.Number datatype. +// Repeating the interface here avoids a dependency on encoding/json, and also +// supports other libraries like jsoniter, which use a similar datatype with +// the same interface. Detecting this interface is useful when dealing with +// structures containing json.Number, which is a string under the hood. The +// encoder should prefer the use of Int64(), Float64() and string(), in that +// order, when encoding this type. +type jsonNumber interface { + Float64() (float64, error) + Int64() (int64, error) + String() string +} + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch m := iface.(type) { + case jsonNumber: + integer, err := m.Int64() + if err == nil { + // In this case the json.Number is a valid int64 + in = reflect.ValueOf(integer) + break + } + float, err := m.Float64() + if err == nil { + // In this case the json.Number is a valid float64 + in = reflect.ValueOf(float) + break + } + // fallback case - no number could be obtained + in = reflect.ValueOf(m.String()) + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: + v, err := m.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + in = reflect.ValueOf(v) + case encoding.TextMarshaler: + text, err := m.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) + } else { + e.marshal(tag, in.Elem()) + } + case reflect.Struct: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: + if in.Type().Elem() == mapItemType { + e.itemsv(tag, in) + } else { + e.slicev(tag, in) + } + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if in.Type() == durationType { + e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) + } else { + e.intv(tag, in) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) itemsv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) + for _, item := range slice { + e.marshal("", reflect.ValueOf(item.Key)) + e.marshal("", reflect.ValueOf(item.Value)) + } + }) +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = in.FieldByIndex(info.Inline) + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { + implicit := tag == "" + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.emit() +} diff --git a/vendor/go.yaml.in/yaml/v2/parserc.go b/vendor/go.yaml.in/yaml/v2/parserc.go new file mode 100644 index 000000000..81d05dfe5 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/parserc.go @@ -0,0 +1,1095 @@ +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + return &parser.tokens[parser.tokens_head] + } + return nil +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** +// +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + return true +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* +// +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +// +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// +// +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true +} + +// +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * +// +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * +// +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/go.yaml.in/yaml/v2/readerc.go b/vendor/go.yaml.in/yaml/v2/readerc.go new file mode 100644 index 000000000..7c1f5fac3 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/readerc.go @@ -0,0 +1,412 @@ +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/go.yaml.in/yaml/v2/resolve.go b/vendor/go.yaml.in/yaml/v2/resolve.go new file mode 100644 index 000000000..4120e0c91 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/resolve.go @@ -0,0 +1,258 @@ +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, + {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, + {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, + {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, + {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, + {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, + {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", yaml_MERGE_TAG, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + // TODO This can easily be made faster and produce less garbage. + if strings.HasPrefix(tag, longTagPrefix) { + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: + return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + } + default: + panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") + } + } + return yaml_STR_TAG, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/go.yaml.in/yaml/v2/scannerc.go b/vendor/go.yaml.in/yaml/v2/scannerc.go new file mode 100644 index 000000000..0b9bb6030 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/scannerc.go @@ -0,0 +1,2711 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + if parser.tokens_head != len(parser.tokens) { + // If queue is non-empty, check if any potential simple key may + // occupy the head position. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + } + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true +} + +// max_flow_level limits the flow_level +const max_flow_level = 10000 + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) + + // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true +} + +// max_indents limits the indents stack size +const max_indents = 10000 + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + // Loop through the indentation levels in the stack. + for parser.indent > column { + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + parser.simple_keys_by_tok = make(map[int]int) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +// +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} diff --git a/vendor/go.yaml.in/yaml/v2/sorter.go b/vendor/go.yaml.in/yaml/v2/sorter.go new file mode 100644 index 000000000..4c45e660a --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/sorter.go @@ -0,0 +1,113 @@ +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + return bl + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/go.yaml.in/yaml/v2/writerc.go b/vendor/go.yaml.in/yaml/v2/writerc.go new file mode 100644 index 000000000..a2dde608c --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/writerc.go @@ -0,0 +1,26 @@ +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/go.yaml.in/yaml/v2/yaml.go b/vendor/go.yaml.in/yaml/v2/yaml.go new file mode 100644 index 000000000..5248e1263 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/yaml.go @@ -0,0 +1,478 @@ +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/yaml/go-yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" +) + +// MapSlice encodes and decodes as a YAML map. +// The order of keys is preserved when encoding and decoding. +type MapSlice []MapItem + +// MapItem is an item in a MapSlice. +type MapItem struct { + Key, Value interface{} +} + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. The UnmarshalYAML +// method receives a function that may be called to unmarshal the original +// YAML value into a field or variable. It is safe to call the unmarshal +// function parameter more than once if necessary. +type Unmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// UnmarshalStrict is like Unmarshal except that any fields that are found +// in the data that do not have corresponding struct members, or mapping +// keys that are duplicates, will result in +// an error. +func UnmarshalStrict(in []byte, out interface{}) (err error) { + return unmarshal(in, out, true) +} + +// A Decoder reads and decodes YAML values from an input stream. +type Decoder struct { + strict bool + parser *parser +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// SetStrict sets whether strict decoding behaviour is enabled when +// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. +func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder(strict) + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("Multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct: + sinfo, err := getStructInfo(field.Type) + if err != nil { + return nil, err + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + default: + //return nil, errors.New("Option ,inline needs a struct value or map field") + return nil, errors.New("Option ,inline needs a struct value field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "Duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} + +// FutureLineWrap globally disables line wrapping when encoding long strings. +// This is a temporary and thus deprecated method introduced to faciliate +// migration towards v3, which offers more control of line lengths on +// individual encodings, and has a default matching the behavior introduced +// by this function. +// +// The default formatting of v2 was erroneously changed in v2.3.0 and reverted +// in v2.4.0, at which point this function was introduced to help migration. +func FutureLineWrap() { + disableLineWrapping = true +} diff --git a/vendor/go.yaml.in/yaml/v2/yamlh.go b/vendor/go.yaml.in/yaml/v2/yamlh.go new file mode 100644 index 000000000..f6a9c8e34 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/yamlh.go @@ -0,0 +1,739 @@ +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota + + yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +// +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/go.yaml.in/yaml/v2/yamlprivateh.go b/vendor/go.yaml.in/yaml/v2/yamlprivateh.go new file mode 100644 index 000000000..8110ce3c3 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v2/yamlprivateh.go @@ -0,0 +1,173 @@ +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +} diff --git a/vendor/go.yaml.in/yaml/v3/LICENSE b/vendor/go.yaml.in/yaml/v3/LICENSE new file mode 100644 index 000000000..2683e4bb1 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/LICENSE @@ -0,0 +1,50 @@ + +This project is covered by two different licenses: MIT and Apache. + +#### MIT License #### + +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original MIT license, with the additional +copyright staring in 2011 when the project was ported over: + + apic.go emitterc.go parserc.go readerc.go scannerc.go + writerc.go yamlh.go yamlprivateh.go + +Copyright (c) 2006-2010 Kirill Simonov +Copyright (c) 2006-2011 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +### Apache License ### + +All the remaining project files are covered by the Apache license: + +Copyright (c) 2011-2019 Canonical Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/go.yaml.in/yaml/v3/NOTICE b/vendor/go.yaml.in/yaml/v3/NOTICE new file mode 100644 index 000000000..866d74a7a --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/go.yaml.in/yaml/v3/README.md b/vendor/go.yaml.in/yaml/v3/README.md new file mode 100644 index 000000000..15a85a635 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/README.md @@ -0,0 +1,171 @@ +go.yaml.in/yaml +=============== + +YAML Support for the Go Language + + +## Introduction + +The `yaml` package enables [Go](https://go.dev/) programs to comfortably encode +and decode [YAML](https://yaml.org/) values. + +It was originally developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a pure Go +port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) C library to +parse and generate YAML data quickly and reliably. + + +## Project Status + +This project started as a fork of the extremely popular [go-yaml]( +https://github.com/go-yaml/yaml/) +project, and is being maintained by the official [YAML organization]( +https://github.com/yaml/). + +The YAML team took over ongoing maintenance and development of the project after +discussion with go-yaml's author, @niemeyer, following his decision to +[label the project repository as "unmaintained"]( +https://github.com/go-yaml/yaml/blob/944c86a7d2/README.md) in April 2025. + +We have put together a team of dedicated maintainers including representatives +of go-yaml's most important downstream projects. + +We will strive to earn the trust of the various go-yaml forks to switch back to +this repository as their upstream. + +Please [contact us](https://cloud-native.slack.com/archives/C08PPAT8PS7) if you +would like to contribute or be involved. + + +## Compatibility + +The `yaml` package supports most of YAML 1.2, but preserves some behavior from +1.1 for backwards compatibility. + +Specifically, v3 of the `yaml` package: + +* Supports YAML 1.1 bools (`yes`/`no`, `on`/`off`) as long as they are being + decoded into a typed bool value. + Otherwise they behave as a string. + Booleans in YAML 1.2 are `true`/`false` only. +* Supports octals encoded and decoded as `0777` per YAML 1.1, rather than + `0o777` as specified in YAML 1.2, because most parsers still use the old + format. + Octals in the `0o777` format are supported though, so new files work. +* Does not support base-60 floats. + These are gone from YAML 1.2, and were actually never supported by this + package as it's clearly a poor choice. + + +## Installation and Usage + +The import path for the package is *go.yaml.in/yaml/v3*. + +To install it, run: + +```bash +go get go.yaml.in/yaml/v3 +``` + + +## API Documentation + +See: + + +## API Stability + +The package API for yaml v3 will remain stable as described in [gopkg.in]( +https://gopkg.in). + + +## Example + +```go +package main + +import ( + "fmt" + "log" + + "go.yaml.in/yaml/v3" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + + +## License + +The yaml package is licensed under the MIT and Apache License 2.0 licenses. +Please see the LICENSE file for details. diff --git a/vendor/go.yaml.in/yaml/v3/apic.go b/vendor/go.yaml.in/yaml/v3/apic.go new file mode 100644 index 000000000..05fd305da --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/apic.go @@ -0,0 +1,747 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + best_width: -1, + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +// Create ALIAS. +func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) bool { + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + anchor: anchor, + } + return true +} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/go.yaml.in/yaml/v3/decode.go b/vendor/go.yaml.in/yaml/v3/decode.go new file mode 100644 index 000000000..02e2b17bf --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/decode.go @@ -0,0 +1,1018 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *Node + anchors map[string]*Node + doneInit bool + textless bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.anchors = make(map[string]*Node) + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + // It's curious choice from the underlying API to generally return a + // positive result on success, but on this case return true in an error + // scenario. This was the source of bugs in the past (issue #666). + if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *Node, anchor []byte) { + if anchor != nil { + n.Anchor = string(anchor) + p.anchors[n.Anchor] = n + } +} + +func (p *parser) parse() *Node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + case yaml_TAIL_COMMENT_EVENT: + panic("internal error: unexpected tail comment event (please report)") + default: + panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) + } +} + +func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { + var style Style + if tag != "" && tag != "!" { + tag = shortTag(tag) + style = TaggedStyle + } else if defaultTag != "" { + tag = defaultTag + } else if kind == ScalarNode { + tag, _ = resolve("", value) + } + n := &Node{ + Kind: kind, + Tag: tag, + Value: value, + Style: style, + } + if !p.textless { + n.Line = p.event.start_mark.line + 1 + n.Column = p.event.start_mark.column + 1 + n.HeadComment = string(p.event.head_comment) + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + } + return n +} + +func (p *parser) parseChild(parent *Node) *Node { + child := p.parse() + parent.Content = append(parent.Content, child) + return child +} + +func (p *parser) document() *Node { + n := p.node(DocumentNode, "", "", "") + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + p.parseChild(n) + if p.peek() == yaml_DOCUMENT_END_EVENT { + n.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *Node { + n := p.node(AliasNode, "", "", string(p.event.anchor)) + n.Alias = p.anchors[n.Value] + if n.Alias == nil { + failf("unknown anchor '%s' referenced", n.Value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *Node { + var parsedStyle = p.event.scalar_style() + var nodeStyle Style + switch { + case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = DoubleQuotedStyle + case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = SingleQuotedStyle + case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: + nodeStyle = LiteralStyle + case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: + nodeStyle = FoldedStyle + } + var nodeValue = string(p.event.value) + var nodeTag = string(p.event.tag) + var defaultTag string + if nodeStyle == 0 { + if nodeValue == "<<" { + defaultTag = mergeTag + } + } else { + defaultTag = strTag + } + n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) + n.Style |= nodeStyle + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *Node { + n := p.node(SequenceNode, seqTag, string(p.event.tag), "") + if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + p.parseChild(n) + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *Node { + n := p.node(MappingNode, mapTag, string(p.event.tag), "") + block := true + if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { + block = false + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + k := p.parseChild(n) + if block && k.FootComment != "" { + // Must be a foot comment for the prior value when being dedented. + if len(n.Content) > 2 { + n.Content[len(n.Content)-3].FootComment = k.FootComment + k.FootComment = "" + } + } + v := p.parseChild(n) + if k.FootComment == "" && v.FootComment != "" { + k.FootComment = v.FootComment + v.FootComment = "" + } + if p.peek() == yaml_TAIL_COMMENT_EVENT { + if k.FootComment == "" { + k.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_TAIL_COMMENT_EVENT) + } + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { + n.Content[len(n.Content)-2].FootComment = n.FootComment + n.FootComment = "" + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *Node + aliases map[*Node]bool + terrors []string + + stringMapType reflect.Type + generalMapType reflect.Type + + knownFields bool + uniqueKeys bool + decodeCount int + aliasCount int + aliasDepth int + + mergedFields map[interface{}]bool +} + +var ( + nodeType = reflect.TypeOf(Node{}) + durationType = reflect.TypeOf(time.Duration(0)) + stringMapType = reflect.TypeOf(map[string]interface{}{}) + generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = generalMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder() *decoder { + d := &decoder{ + stringMapType: stringMapType, + generalMapType: generalMapType, + uniqueKeys: true, + } + d.aliases = make(map[*Node]bool) + return d +} + +func (d *decoder) terror(n *Node, tag string, out reflect.Value) { + if n.Tag != "" { + tag = n.Tag + } + value := n.Value + if tag != seqTag && tag != mapTag { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { + err := u.UnmarshalYAML(n) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.ShortTag() == nullTag { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + outi := out.Addr().Interface() + if u, ok := outi.(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + if u, ok := outi.(obsoleteUnmarshaler); ok { + good = d.callObsoleteUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { + if n.ShortTag() == nullTag { + return reflect.Value{} + } + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + if out.Type() == nodeType { + out.Set(reflect.ValueOf(n).Elem()) + return true + } + switch n.Kind { + case DocumentNode: + return d.document(n, out) + case AliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.Kind { + case ScalarNode: + good = d.scalar(n, out) + case MappingNode: + good = d.mapping(n, out) + case SequenceNode: + good = d.sequence(n, out) + case 0: + if n.IsZero() { + return d.null(out) + } + fallthrough + default: + failf("cannot decode node with unknown kind %d", n.Kind) + } + return good +} + +func (d *decoder) document(n *Node, out reflect.Value) (good bool) { + if len(n.Content) == 1 { + d.doc = n + d.unmarshal(n.Content[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.Value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.Alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) null(out reflect.Value) bool { + if out.CanAddr() { + switch out.Kind() { + case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + out.Set(reflect.Zero(out.Type())) + return true + } + } + return false +} + +func (d *decoder) scalar(n *Node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.indicatedString() { + tag = strTag + resolved = n.Value + } else { + tag, resolved = resolve(n.Tag, n.Value) + if tag == binaryTag { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + return d.null(out) + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == binaryTag { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.Value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == binaryTag { + out.SetString(resolved.(string)) + return true + } + out.SetString(n.Value) + return true + case reflect.Interface: + out.Set(reflect.ValueOf(resolved)) + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + // This used to work in v2, but it's very unfriendly. + isDuration := out.Type() == durationType + + switch resolved := resolved.(type) { + case int: + if !isDuration && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !isDuration && !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + case string: + // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). + // It only works if explicitly attempting to unmarshal into a typed bool value. + switch resolved { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": + out.SetBool(true) + return true + case "n", "N", "no", "No", "NO", "off", "Off", "OFF": + out.SetBool(false) + return true + } + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + panic("yaml internal error: please report the issue") + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, seqTag, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.Content[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + if d.uniqueKeys { + nerrs := len(d.terrors) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + for j := i + 2; j < l; j += 2 { + nj := n.Content[j] + if ni.Kind == nj.Kind && ni.Value == nj.Value { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) + } + } + } + if len(d.terrors) > nerrs { + return false + } + } + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Map: + // okay + case reflect.Interface: + iface := out + if isStringMap(n) { + out = reflect.MakeMap(d.stringMapType) + } else { + out = reflect.MakeMap(d.generalMapType) + } + iface.Set(out) + default: + d.terror(n, mapTag, out) + return false + } + + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + stringMapType := d.stringMapType + generalMapType := d.generalMapType + if outt.Elem() == ifaceType { + if outt.Key().Kind() == reflect.String { + d.stringMapType = outt + } else if outt.Key() == ifaceType { + d.generalMapType = outt + } + } + + mergedFields := d.mergedFields + d.mergedFields = nil + + var mergeNode *Node + + mapIsNew := false + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + mapIsNew = true + } + for i := 0; i < l; i += 2 { + if isMerge(n.Content[i]) { + mergeNode = n.Content[i+1] + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.Content[i], k) { + if mergedFields != nil { + ki := k.Interface() + if d.getPossiblyUnhashableKey(mergedFields, ki) { + continue + } + d.setPossiblyUnhashableKey(mergedFields, ki, true) + } + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) { + out.SetMapIndex(k, e) + } + } + } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + + d.stringMapType = stringMapType + d.generalMapType = generalMapType + return true +} + +func isStringMap(n *Node) bool { + if n.Kind != MappingNode { + return false + } + l := len(n.Content) + for i := 0; i < l; i += 2 { + shortTag := n.Content[i].ShortTag() + if shortTag != strTag && shortTag != mergeTag { + return false + } + } + return true +} + +func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + elemType = inlineMap.Type().Elem() + } + + for _, index := range sinfo.InlineUnmarshalers { + field := d.fieldByIndex(n, out, index) + d.prepare(n, field) + } + + mergedFields := d.mergedFields + d.mergedFields = nil + var mergeNode *Node + var doneFields []bool + if d.uniqueKeys { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + name := settableValueOf("") + l := len(n.Content) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + if isMerge(ni) { + mergeNode = n.Content[i+1] + continue + } + if !d.unmarshal(ni, name) { + continue + } + sname := name.String() + if mergedFields != nil { + if mergedFields[sname] { + continue + } + mergedFields[sname] = true + } + if info, ok := sinfo.FieldsMap[sname]; ok { + if d.uniqueKeys { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = d.fieldByIndex(n, out, info.Inline) + } + d.unmarshal(n.Content[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.Content[i+1], value) + inlineMap.SetMapIndex(name, value) + } else if d.knownFields { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) + } + } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) setPossiblyUnhashableKey(m map[interface{}]bool, key interface{}, value bool) { + defer func() { + if err := recover(); err != nil { + failf("%v", err) + } + }() + m[key] = value +} + +func (d *decoder) getPossiblyUnhashableKey(m map[interface{}]bool, key interface{}) bool { + defer func() { + if err := recover(); err != nil { + failf("%v", err) + } + }() + return m[key] +} + +func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { + mergedFields := d.mergedFields + if mergedFields == nil { + d.mergedFields = make(map[interface{}]bool) + for i := 0; i < len(parent.Content); i += 2 { + k := reflect.New(ifaceType).Elem() + if d.unmarshal(parent.Content[i], k) { + d.setPossiblyUnhashableKey(d.mergedFields, k.Interface(), true) + } + } + } + + switch merge.Kind { + case MappingNode: + d.unmarshal(merge, out) + case AliasNode: + if merge.Alias != nil && merge.Alias.Kind != MappingNode { + failWantMap() + } + d.unmarshal(merge, out) + case SequenceNode: + for i := 0; i < len(merge.Content); i++ { + ni := merge.Content[i] + if ni.Kind == AliasNode { + if ni.Alias != nil && ni.Alias.Kind != MappingNode { + failWantMap() + } + } else if ni.Kind != MappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } + + d.mergedFields = mergedFields +} + +func isMerge(n *Node) bool { + return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) +} diff --git a/vendor/go.yaml.in/yaml/v3/emitterc.go b/vendor/go.yaml.in/yaml/v3/emitterc.go new file mode 100644 index 000000000..ab4e03ba7 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/emitterc.go @@ -0,0 +1,2054 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and below and drop from everywhere else (see commented lines). + emitter.indention = true + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + if emitter.column == 0 { + emitter.space_above = true + } + emitter.column = 0 + emitter.line++ + // [Go] Do this here and above and drop from everywhere else (see commented lines). + emitter.indention = true + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent_compact(emitter *yaml_emitter_t, flow, indentless bool, compact_seq bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + // [Go] This was changed so that indentations are more regular. + if emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { + // The first indent inside a sequence will just skip the "- " indicator. + emitter.indent += 2 + } else { + // Everything else aligns to the chosen indentation. + emitter.indent = emitter.best_indent * ((emitter.indent + emitter.best_indent) / emitter.best_indent) + if compact_seq { + // The value compact_seq passed in is almost always set to `false` when this function is called, + // except when we are dealing with sequence nodes. So this gets triggered to subtract 2 only when we + // are increasing the indent to account for sequence nodes, which will be correct because we need to + // subtract 2 to account for the - at the beginning of the sequence node. + emitter.indent = emitter.indent - 2 + } + } + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) + + case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) + + case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + emitter.space_above = true + emitter.foot_indent = -1 + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical || true { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if len(emitter.head_comment) > 0 { + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !put_break(emitter) { + return false + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// yaml_emitter_increase_indent preserves the original signature and delegates to +// yaml_emitter_increase_indent_compact without compact-sequence indentation +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + return yaml_emitter_increase_indent_compact(emitter, flow, indentless, false) +} + +// yaml_emitter_process_line_comment preserves the original signature and delegates to +// yaml_emitter_process_line_comment_linebreak passing false for linebreak +func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { + return yaml_emitter_process_line_comment_linebreak(emitter, false) +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + // [Go] Force document foot separation. + emitter.foot_indent = 0 + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.foot_indent = -1 + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + if emitter.canonical && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.column == 0 || emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + // emitter.mapping context tells us if we are currently in a mapping context. + // emiiter.column tells us which column we are in in the yaml output. 0 is the first char of the column. + // emitter.indentation tells us if the last character was an indentation character. + // emitter.compact_sequence_indent tells us if '- ' is considered part of the indentation for sequence elements. + // So, `seq` means that we are in a mapping context, and we are either at the first char of the column or + // the last character was not an indentation character, and we consider '- ' part of the indentation + // for sequence elements. + seq := emitter.mapping_context && (emitter.column == 0 || !emitter.indention) && + emitter.compact_sequence_indent + if !yaml_emitter_increase_indent_compact(emitter, false, false, seq) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if len(emitter.line_comment) > 0 { + // [Go] A line comment was provided for the key. That's unusual as the + // scanner associates line comments with the value. Either way, + // save the line comment and render it appropriately later. + emitter.key_line_comment = emitter.line_comment + emitter.line_comment = nil + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + if len(emitter.key_line_comment) > 0 { + // [Go] Line comments are generally associated with the value, but when there's + // no value on the same line as a mapping key they end up attached to the + // key itself. + if event.typ == yaml_SCALAR_EVENT { + if len(emitter.line_comment) == 0 { + // A scalar is coming and it has no line comments by itself yet, + // so just let it handle the line comment as usual. If it has a + // line comment, we can't have both so the one from the key is lost. + emitter.line_comment = emitter.key_line_comment + emitter.key_line_comment = nil + } + } else if event.sequence_style() != yaml_FLOW_SEQUENCE_STYLE && (event.typ == yaml_MAPPING_START_EVENT || event.typ == yaml_SEQUENCE_START_EVENT) { + // An indented block follows, so write the comment right now. + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + if !yaml_emitter_process_line_comment(emitter) { + return false + } + emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true +} + +func yaml_emitter_silent_nil_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + return event.typ == yaml_SCALAR_EVENT && event.implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0 +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Write a head comment. +func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { + if len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { + return false + } + emitter.tail_comment = emitter.tail_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + } + + if len(emitter.head_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.head_comment) { + return false + } + emitter.head_comment = emitter.head_comment[:0] + return true +} + +// Write an line comment. +func yaml_emitter_process_line_comment_linebreak(emitter *yaml_emitter_t, linebreak bool) bool { + if len(emitter.line_comment) == 0 { + // The next 3 lines are needed to resolve an issue with leading newlines + // See https://github.com/go-yaml/yaml/issues/755 + // When linebreak is set to true, put_break will be called and will add + // the needed newline. + if linebreak && !put_break(emitter) { + return false + } + return true + } + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !yaml_emitter_write_comment(emitter, emitter.line_comment) { + return false + } + emitter.line_comment = emitter.line_comment[:0] + return true +} + +// Write a foot comment. +func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { + if len(emitter.foot_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { + return false + } + emitter.foot_comment = emitter.foot_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + return true +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + tab_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if value[i] == '\t' { + tab_characters = true + } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || tab_characters || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + if len(event.head_comment) > 0 { + emitter.head_comment = event.head_comment + } + if len(event.line_comment) > 0 { + emitter.line_comment = event.line_comment + } + if len(event.foot_comment) > 0 { + emitter.foot_comment = event.foot_comment + } + if len(event.tail_comment) > 0 { + emitter.tail_comment = event.tail_comment + } + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + if emitter.foot_indent == indent { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + //emitter.indention = true + emitter.space_above = false + emitter.foot_indent = -1 + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if len(value) > 0 && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + if len(value) > 0 { + emitter.whitespace = false + } + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment_linebreak(emitter, true) { + return false + } + //emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !yaml_emitter_process_line_comment_linebreak(emitter, true) { + return false + } + + //emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + //emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} + +func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { + breaks := false + pound := false + for i := 0; i < len(comment); { + if is_break(comment, i) { + if !write_break(emitter, comment, &i) { + return false + } + //emitter.indention = true + breaks = true + pound = false + } else { + if breaks && !yaml_emitter_write_indent(emitter) { + return false + } + if !pound { + if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { + return false + } + pound = true + } + if !write(emitter, comment, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + if !breaks && !put_break(emitter) { + return false + } + + emitter.whitespace = true + //emitter.indention = true + return true +} diff --git a/vendor/go.yaml.in/yaml/v3/encode.go b/vendor/go.yaml.in/yaml/v3/encode.go new file mode 100644 index 000000000..de9e72a3e --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/encode.go @@ -0,0 +1,577 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + indent int + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + if e.indent == 0 { + e.indent = 4 + } + e.emitter.best_indent = e.indent + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + var node *Node + if in.IsValid() { + node, _ = in.Interface().(*Node) + } + if node != nil && node.Kind == DocumentNode { + e.nodev(in) + } else { + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() + } +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + tag = shortTag(tag) + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch value := iface.(type) { + case *Node: + e.nodev(in) + return + case Node: + if !in.CanAddr() { + var n = reflect.New(in.Type()).Elem() + n.Set(in) + in = n + } + e.nodev(in.Addr()) + return + case time.Time: + e.timev(tag, in) + return + case *time.Time: + e.timev(tag, in.Elem()) + return + case time.Duration: + e.stringv(tag, reflect.ValueOf(value.String())) + return + case Marshaler: + v, err := value.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + e.marshal(tag, reflect.ValueOf(v)) + return + case encoding.TextMarshaler: + text, err := value.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + e.marshal(tag, in.Elem()) + case reflect.Struct: + e.structv(tag, in) + case reflect.Slice, reflect.Array: + e.slicev(tag, in) + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + e.intv(tag, in) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return reflect.Value{} + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = e.fieldByIndex(in, info.Inline) + if !value.IsValid() { + continue + } + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +// isOldBool returns whether s is bool notation as defined in YAML 1.1. +// +// We continue to force strings that YAML 1.1 would interpret as booleans to be +// rendered as quotes strings so that the marshalled output valid for YAML 1.1 +// parsing. +func isOldBool(s string) (result bool) { + switch s { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", + "n", "N", "no", "No", "NO", "off", "Off", "OFF": + return true + default: + return false + } +} + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + if e.flow { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } else { + style = yaml_LITERAL_SCALAR_STYLE + } + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style, nil, nil, nil, nil) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { + // TODO Kill this function. Replace all initialize calls by their underlining Go literals. + implicit := tag == "" + if !implicit { + tag = longTag(tag) + } + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.event.head_comment = head + e.event.line_comment = line + e.event.foot_comment = foot + e.event.tail_comment = tail + e.emit() +} + +func (e *encoder) nodev(in reflect.Value) { + e.node(in.Interface().(*Node), "") +} + +func (e *encoder) node(node *Node, tail string) { + // Zero nodes behave as nil. + if node.Kind == 0 && node.IsZero() { + e.nilv() + return + } + + // If the tag was not explicitly requested, and dropping it won't change the + // implicit tag of the value, don't include it in the presentation. + var tag = node.Tag + var stag = shortTag(tag) + var forceQuoting bool + if tag != "" && node.Style&TaggedStyle == 0 { + if node.Kind == ScalarNode { + if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { + tag = "" + } else { + rtag, _ := resolve("", node.Value) + if rtag == stag { + tag = "" + } else if stag == strTag { + tag = "" + forceQuoting = true + } + } + } else { + var rtag string + switch node.Kind { + case MappingNode: + rtag = mapTag + case SequenceNode: + rtag = seqTag + } + if rtag == stag { + tag = "" + } + } + } + + switch node.Kind { + case DocumentNode: + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + yaml_document_end_event_initialize(&e.event, true) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case SequenceNode: + style := yaml_BLOCK_SEQUENCE_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case MappingNode: + style := yaml_BLOCK_MAPPING_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style) + e.event.tail_comment = []byte(tail) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + + // The tail logic below moves the foot comment of prior keys to the following key, + // since the value for each key may be a nested structure and the foot needs to be + // processed only the entirety of the value is streamed. The last tail is processed + // with the mapping end event. + var tail string + for i := 0; i+1 < len(node.Content); i += 2 { + k := node.Content[i] + foot := k.FootComment + if foot != "" { + kopy := *k + kopy.FootComment = "" + k = &kopy + } + e.node(k, tail) + tail = foot + + v := node.Content[i+1] + e.node(v, "") + } + + yaml_mapping_end_event_initialize(&e.event) + e.event.tail_comment = []byte(tail) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case AliasNode: + yaml_alias_event_initialize(&e.event, []byte(node.Value)) + e.event.head_comment = []byte(node.HeadComment) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case ScalarNode: + value := node.Value + if !utf8.ValidString(value) { + if stag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if stag != "" { + failf("cannot marshal invalid UTF-8 data as %s", stag) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + value = encodeBase64(value) + } + + style := yaml_PLAIN_SCALAR_STYLE + switch { + case node.Style&DoubleQuotedStyle != 0: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + case node.Style&SingleQuotedStyle != 0: + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + case node.Style&LiteralStyle != 0: + style = yaml_LITERAL_SCALAR_STYLE + case node.Style&FoldedStyle != 0: + style = yaml_FOLDED_SCALAR_STYLE + case strings.Contains(value, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case forceQuoting: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) + default: + failf("cannot encode node with unknown kind %d", node.Kind) + } +} diff --git a/vendor/go.yaml.in/yaml/v3/parserc.go b/vendor/go.yaml.in/yaml/v3/parserc.go new file mode 100644 index 000000000..25fe82363 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/parserc.go @@ -0,0 +1,1274 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + token := &parser.tokens[parser.tokens_head] + yaml_parser_unfold_comments(parser, token) + return token + } + return nil +} + +// yaml_parser_unfold_comments walks through the comments queue and joins all +// comments behind the position of the provided token into the respective +// top-level comment slices in the parser. +func yaml_parser_unfold_comments(parser *yaml_parser_t, token *yaml_token_t) { + for parser.comments_head < len(parser.comments) && token.start_mark.index >= parser.comments[parser.comments_head].token_mark.index { + comment := &parser.comments[parser.comments_head] + if len(comment.head) > 0 { + if token.typ == yaml_BLOCK_END_TOKEN { + // No heads on ends, so keep comment.head for a follow up token. + break + } + if len(parser.head_comment) > 0 { + parser.head_comment = append(parser.head_comment, '\n') + } + parser.head_comment = append(parser.head_comment, comment.head...) + } + if len(comment.foot) > 0 { + if len(parser.foot_comment) > 0 { + parser.foot_comment = append(parser.foot_comment, '\n') + } + parser.foot_comment = append(parser.foot_comment, comment.foot...) + } + if len(comment.line) > 0 { + if len(parser.line_comment) > 0 { + parser.line_comment = append(parser.line_comment, '\n') + } + parser.line_comment = append(parser.line_comment, comment.line...) + } + *comment = yaml_comment_t{} + parser.comments_head++ + } +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// +// * +// +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + var head_comment []byte + if len(parser.head_comment) > 0 { + // [Go] Scan the header comment backwards, and if an empty line is found, break + // the header so the part before the last empty line goes into the + // document header, while the bottom of it goes into a follow up event. + for i := len(parser.head_comment) - 1; i > 0; i-- { + if parser.head_comment[i] == '\n' { + if i == len(parser.head_comment)-1 { + head_comment = parser.head_comment[:i] + parser.head_comment = parser.head_comment[i+1:] + break + } else if parser.head_comment[i-1] == '\n' { + head_comment = parser.head_comment[:i-1] + parser.head_comment = parser.head_comment[i+1:] + break + } + } + } + } + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + + head_comment: head_comment, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +// *********** +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// +// ************* +// +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + yaml_parser_set_event_comments(parser, event) + if len(event.head_comment) > 0 && len(event.foot_comment) == 0 { + event.foot_comment = event.head_comment + event.head_comment = nil + } + return true +} + +func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) { + event.head_comment = parser.head_comment + event.line_comment = parser.line_comment + event.foot_comment = parser.foot_comment + parser.head_comment = nil + parser.line_comment = nil + parser.foot_comment = nil + parser.tail_comment = nil + parser.stem_comment = nil +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// +// block_node ::= ALIAS +// +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// +// flow_node ::= ALIAS +// +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// +// ************************* +// +// block_content ::= block_collection | flow_collection | SCALAR +// +// ****** +// +// flow_content ::= flow_collection | SCALAR +// +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + yaml_parser_set_event_comments(parser, event) + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + yaml_parser_set_event_comments(parser, event) + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + if parser.stem_comment != nil { + event.head_comment = parser.stem_comment + parser.stem_comment = nil + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + if parser.stem_comment != nil { + event.head_comment = parser.stem_comment + parser.stem_comment = nil + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// +// ******************** *********** * ********* +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + prior_head_len := len(parser.head_comment) + skip_token(parser) + yaml_parser_split_stem_comment(parser, prior_head_len) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + prior_head_len := len(parser.head_comment) + skip_token(parser) + yaml_parser_split_stem_comment(parser, prior_head_len) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Split stem comment from head comment. +// +// When a sequence or map is found under a sequence entry, the former head comment +// is assigned to the underlying sequence or map as a whole, not the individual +// sequence or map entry as would be expected otherwise. To handle this case the +// previous head comment is moved aside as the stem comment. +func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { + if stem_len == 0 { + return + } + + token := peek_token(parser) + if token == nil || token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { + return + } + + parser.stem_comment = parser.head_comment[:stem_len] + if len(parser.head_comment) == stem_len { + parser.head_comment = nil + } else { + // Copy suffix to prevent very strange bugs if someone ever appends + // further bytes to the prefix in the stem_comment slice above. + parser.head_comment = append([]byte(nil), parser.head_comment[stem_len+1:]...) + } +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + // [Go] A tail comment was left from the prior mapping value processed. Emit an event + // as it needs to be processed with that value and not the following key. + if len(parser.tail_comment) > 0 { + *event = yaml_event_t{ + typ: yaml_TAIL_COMMENT_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + foot_comment: parser.tail_comment, + } + parser.tail_comment = nil + return true + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// +// * +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + if token == nil { + return false + } + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + + skip_token(parser) + return true +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// +// *** * +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// +// ***** * +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// +// * +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// - *** * +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + yaml_parser_set_event_comments(parser, event) + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// - ***** * +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/go.yaml.in/yaml/v3/readerc.go b/vendor/go.yaml.in/yaml/v3/readerc.go new file mode 100644 index 000000000..56af24536 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/readerc.go @@ -0,0 +1,434 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/go.yaml.in/yaml/v3/resolve.go b/vendor/go.yaml.in/yaml/v3/resolve.go new file mode 100644 index 000000000..64ae88805 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/resolve.go @@ -0,0 +1,326 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, boolTag, []string{"true", "True", "TRUE"}}, + {false, boolTag, []string{"false", "False", "FALSE"}}, + {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", mergeTag, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const ( + nullTag = "!!null" + boolTag = "!!bool" + strTag = "!!str" + intTag = "!!int" + floatTag = "!!float" + timestampTag = "!!timestamp" + seqTag = "!!seq" + mapTag = "!!map" + binaryTag = "!!binary" + mergeTag = "!!merge" +) + +var longTags = make(map[string]string) +var shortTags = make(map[string]string) + +func init() { + for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { + ltag := longTag(stag) + longTags[stag] = ltag + shortTags[ltag] = stag + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + if strings.HasPrefix(tag, longTagPrefix) { + if stag, ok := shortTags[tag]; ok { + return stag + } + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + if ltag, ok := longTags[tag]; ok { + return ltag + } + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + tag = shortTag(tag) + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, strTag, binaryTag: + return + case floatTag: + if rtag == intTag { + switch v := out.(type) { + case int64: + rtag = floatTag + out = float64(v) + return + case int: + rtag = floatTag + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != strTag && tag != binaryTag { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return floatTag, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == timestampTag { + t, ok := parseTimestamp(in) + if ok { + return timestampTag, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return intTag, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return floatTag, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + // Octals as introduced in version 1.2 of the spec. + // Octals from the 1.1 spec, spelled as 0777, are still + // decoded by default in v3 as well for compatibility. + // May be dropped in v4 depending on how usage evolves. + if strings.HasPrefix(plain, "0o") { + intv, err := strconv.ParseInt(plain[2:], 8, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 8, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0o") { + intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + default: + panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") + } + } + return strTag, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/go.yaml.in/yaml/v3/scannerc.go b/vendor/go.yaml.in/yaml/v3/scannerc.go new file mode 100644 index 000000000..30b1f0892 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/scannerc.go @@ -0,0 +1,3040 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + parser.newlines++ + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + parser.newlines++ + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.newlines++ + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + // [Go] The comment parsing logic requires a lookahead of two tokens + // so that foot comments may be parsed in time of associating them + // with the tokens that are parsed before them, and also for line + // comments to be transformed into head comments in some edge cases. + if parser.tokens_head < len(parser.tokens)-2 { + // If a potential simple key is at the head position, we need to fetch + // the next token to disambiguate it. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + scan_mark := parser.mark + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // [Go] While unrolling indents, transform the head comments of prior + // indentation levels observed after scan_start into foot comments at + // the respective indexes. + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + comment_mark := parser.mark + if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { + // Associate any following comments with the prior token. + comment_mark = parser.tokens[len(parser.tokens)-1].start_mark + } + defer func() { + if !ok { + return + } + if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].typ == yaml_BLOCK_ENTRY_TOKEN { + // Sequence indicators alone have no line comments. It becomes + // a head comment for whatever follows. + return + } + if !yaml_parser_scan_line_comment(parser, comment_mark) { + ok = false + return + } + }() + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] TODO Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + } + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true +} + +// max_flow_level limits the flow_level +const max_flow_level = 10000 + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) + + // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true +} + +// max_indents limits the indents stack size +const max_indents = 10000 + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + block_mark := scan_mark + block_mark.index-- + + // Loop through the indentation levels in the stack. + for parser.indent > column { + + // [Go] Reposition the end token before potential following + // foot comments of parent blocks. For that, search + // backwards for recent comments that were at the same + // indent as the block that is ending now. + stop_index := block_mark.index + for i := len(parser.comments) - 1; i >= 0; i-- { + comment := &parser.comments[i] + + if comment.end_mark.index < stop_index { + // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. + // If requested indent column is < 0, then the document is over and everything else + // is a foot anyway. + break + } + if comment.start_mark.column == parser.indent+1 { + // This is a good match. But maybe there's a former comment + // at that same indent level, so keep searching. + block_mark = comment.start_mark + } + + // While the end of the former comment matches with + // the start of the following one, we know there's + // nothing in between and scanning is still safe. + stop_index = comment.scan_mark.index + } + + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: block_mark, + end_mark: block_mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + parser.simple_keys_by_tok = make(map[int]int) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + scan_mark := parser.mark + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if we just had a line comment under a sequence entry that + // looks more like a header to the following content. Similar to this: + // + // - # The comment + // - Some data + // + // If so, transform the line comment to a head comment and reposition. + if len(parser.comments) > 0 && len(parser.tokens) > 1 { + tokenA := parser.tokens[len(parser.tokens)-2] + tokenB := parser.tokens[len(parser.tokens)-1] + comment := &parser.comments[len(parser.comments)-1] + if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { + // If it was in the prior line, reposition so it becomes a + // header of the follow up token. Otherwise, keep it in place + // so it becomes a header of the former. + comment.head = comment.line + comment.line = nil + if comment.start_mark.line == parser.mark.line-1 { + comment.token_mark = parser.mark + } + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_comments(parser, scan_mark) { + return false + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + // [Go] Discard this inline comment for the time being. + //if !yaml_parser_scan_line_comment(parser, start_mark) { + // return false + //} + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] TODO Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + if !yaml_parser_scan_line_comment(parser, start_mark) { + return false + } + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} + +func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { + if parser.newlines > 0 { + return true + } + + var start_mark yaml_mark_t + var text []byte + + for peek := 0; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + if parser.buffer[parser.buffer_pos+peek] == '#' { + seen := parser.mark.index + peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + if len(text) == 0 { + start_mark = parser.mark + } + text = read(parser, text) + } else { + skip(parser) + } + } + } + break + } + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + token_mark: token_mark, + start_mark: start_mark, + line: text, + }) + } + return true +} + +func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { + token := parser.tokens[len(parser.tokens)-1] + + if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { + token = parser.tokens[len(parser.tokens)-2] + } + + var token_mark = token.start_mark + var start_mark yaml_mark_t + var next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } + + var recent_empty = false + var first_empty = parser.newlines <= 1 + + var line = parser.mark.line + var column = parser.mark.column + + var text []byte + + // The foot line is the place where a comment must start to + // still be considered as a foot of the prior content. + // If there's some content in the currently parsed line, then + // the foot is the line below it. + var foot_line = -1 + if scan_mark.line > 0 { + foot_line = parser.mark.line - parser.newlines + 1 + if parser.newlines == 0 && parser.mark.column > 1 { + foot_line++ + } + } + + var peek = 0 + for ; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + column++ + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + c := parser.buffer[parser.buffer_pos+peek] + var close_flow = parser.flow_level > 0 && (c == ']' || c == '}') + if close_flow || is_breakz(parser.buffer, parser.buffer_pos+peek) { + // Got line break or terminator. + if close_flow || !recent_empty { + if close_flow || first_empty && (start_mark.line == foot_line && token.typ != yaml_VALUE_TOKEN || start_mark.column-1 < next_indent) { + // This is the first empty line and there were no empty lines before, + // so this initial part of the comment is a foot of the prior token + // instead of being a head for the following one. Split it up. + // Alternatively, this might also be the last comment inside a flow + // scope, so it must be a footer. + if len(text) > 0 { + if start_mark.column-1 < next_indent { + // If dedented it's unrelated to the prior token. + token_mark = start_mark + } + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + } else { + if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { + text = append(text, '\n') + } + } + } + if !is_break(parser.buffer, parser.buffer_pos+peek) { + break + } + first_empty = false + recent_empty = true + column = 0 + line++ + continue + } + + if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.column) { + // The comment at the different indentation is a foot of the + // preceding data rather than a head of the upcoming one. + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + + if parser.buffer[parser.buffer_pos+peek] != '#' { + break + } + + if len(text) == 0 { + start_mark = yaml_mark_t{parser.mark.index + peek, line, column} + } else { + text = append(text, '\n') + } + + recent_empty = false + + // Consume until after the consumed comment line. + seen := parser.mark.index + peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else if parser.mark.index >= seen { + text = read(parser, text) + } else { + skip(parser) + } + } + + peek = 0 + column = 0 + line = parser.mark.line + next_indent = parser.indent + if next_indent < 0 { + next_indent = 0 + } + } + + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: start_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, + head: text, + }) + } + return true +} diff --git a/vendor/go.yaml.in/yaml/v3/sorter.go b/vendor/go.yaml.in/yaml/v3/sorter.go new file mode 100644 index 000000000..9210ece7e --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/sorter.go @@ -0,0 +1,134 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + digits := false + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + digits = unicode.IsDigit(ar[i]) + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + if digits { + return al + } else { + return bl + } + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/go.yaml.in/yaml/v3/writerc.go b/vendor/go.yaml.in/yaml/v3/writerc.go new file mode 100644 index 000000000..266d0b092 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/writerc.go @@ -0,0 +1,48 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/go.yaml.in/yaml/v3/yaml.go b/vendor/go.yaml.in/yaml/v3/yaml.go new file mode 100644 index 000000000..0b101cd20 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/yaml.go @@ -0,0 +1,703 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/yaml/go-yaml +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" + "unicode/utf8" +) + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. +type Unmarshaler interface { + UnmarshalYAML(value *Node) error +} + +type obsoleteUnmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// A Decoder reads and decodes YAML values from an input stream. +type Decoder struct { + parser *parser + knownFields bool +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// KnownFields ensures that the keys in decoded mappings to +// exist as fields in the struct being decoded into. +func (dec *Decoder) KnownFields(enable bool) { + dec.knownFields = enable +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder() + d.knownFields = dec.knownFields + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Decode decodes the node and stores its data into the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (n *Node) Decode(v interface{}) (err error) { + d := newDecoder() + defer handleErr(&err) + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(n, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder() + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Encode encodes value v and stores its representation in n. +// +// See the documentation for Marshal for details about the +// conversion of Go values into YAML. +func (n *Node) Encode(v interface{}) (err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(v)) + e.finish() + p := newParser(e.out) + p.textless = true + defer p.destroy() + doc := p.parse() + *n = *doc.Content[0] + return nil +} + +// SetIndent changes the used indentation used when encoding. +func (e *Encoder) SetIndent(spaces int) { + if spaces < 0 { + panic("yaml: cannot indent to a negative number of spaces") + } + e.encoder.indent = spaces +} + +// CompactSeqIndent makes it so that '- ' is considered part of the indentation. +func (e *Encoder) CompactSeqIndent() { + e.encoder.emitter.compact_sequence_indent = true +} + +// DefaultSeqIndent makes it so that '- ' is not considered part of the indentation. +func (e *Encoder) DefaultSeqIndent() { + e.encoder.emitter.compact_sequence_indent = false +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +type Kind uint32 + +const ( + DocumentNode Kind = 1 << iota + SequenceNode + MappingNode + ScalarNode + AliasNode +) + +type Style uint32 + +const ( + TaggedStyle Style = 1 << iota + DoubleQuotedStyle + SingleQuotedStyle + LiteralStyle + FoldedStyle + FlowStyle +) + +// Node represents an element in the YAML document hierarchy. While documents +// are typically encoded and decoded into higher level types, such as structs +// and maps, Node is an intermediate representation that allows detailed +// control over the content being decoded or encoded. +// +// It's worth noting that although Node offers access into details such as +// line numbers, colums, and comments, the content when re-encoded will not +// have its original textual representation preserved. An effort is made to +// render the data plesantly, and to preserve comments near the data they +// describe, though. +// +// Values that make use of the Node type interact with the yaml package in the +// same way any other type would do, by encoding and decoding yaml data +// directly or indirectly into them. +// +// For example: +// +// var person struct { +// Name string +// Address yaml.Node +// } +// err := yaml.Unmarshal(data, &person) +// +// Or by itself: +// +// var person Node +// err := yaml.Unmarshal(data, &person) +type Node struct { + // Kind defines whether the node is a document, a mapping, a sequence, + // a scalar value, or an alias to another node. The specific data type of + // scalar nodes may be obtained via the ShortTag and LongTag methods. + Kind Kind + + // Style allows customizing the apperance of the node in the tree. + Style Style + + // Tag holds the YAML tag defining the data type for the value. + // When decoding, this field will always be set to the resolved tag, + // even when it wasn't explicitly provided in the YAML content. + // When encoding, if this field is unset the value type will be + // implied from the node properties, and if it is set, it will only + // be serialized into the representation if TaggedStyle is used or + // the implicit tag diverges from the provided one. + Tag string + + // Value holds the unescaped and unquoted represenation of the value. + Value string + + // Anchor holds the anchor name for this node, which allows aliases to point to it. + Anchor string + + // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. + Alias *Node + + // Content holds contained nodes for documents, mappings, and sequences. + Content []*Node + + // HeadComment holds any comments in the lines preceding the node and + // not separated by an empty line. + HeadComment string + + // LineComment holds any comments at the end of the line where the node is in. + LineComment string + + // FootComment holds any comments following the node and before empty lines. + FootComment string + + // Line and Column hold the node position in the decoded YAML text. + // These fields are not respected when encoding the node. + Line int + Column int +} + +// IsZero returns whether the node has all of its fields unset. +func (n *Node) IsZero() bool { + return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil && + n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 +} + +// LongTag returns the long form of the tag that indicates the data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) LongTag() string { + return longTag(n.ShortTag()) +} + +// ShortTag returns the short form of the YAML tag that indicates data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) ShortTag() string { + if n.indicatedString() { + return strTag + } + if n.Tag == "" || n.Tag == "!" { + switch n.Kind { + case MappingNode: + return mapTag + case SequenceNode: + return seqTag + case AliasNode: + if n.Alias != nil { + return n.Alias.ShortTag() + } + case ScalarNode: + tag, _ := resolve("", n.Value) + return tag + case 0: + // Special case to make the zero value convenient. + if n.IsZero() { + return nullTag + } + } + return "" + } + return shortTag(n.Tag) +} + +func (n *Node) indicatedString() bool { + return n.Kind == ScalarNode && + (shortTag(n.Tag) == strTag || + (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) +} + +// SetString is a convenience function that sets the node to a string value +// and defines its style in a pleasant way depending on its content. +func (n *Node) SetString(s string) { + n.Kind = ScalarNode + if utf8.ValidString(s) { + n.Value = s + n.Tag = strTag + } else { + n.Value = encodeBase64(s) + n.Tag = binaryTag + } + if strings.Contains(n.Value, "\n") { + n.Style = LiteralStyle + } +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int + + // InlineUnmarshalers holds indexes to inlined fields that + // contain unmarshaler values. + InlineUnmarshalers [][]int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex +var unmarshalerType reflect.Type + +func init() { + var v Unmarshaler + unmarshalerType = reflect.ValueOf(&v).Elem().Type() +} + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + inlineUnmarshalers := [][]int(nil) + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct, reflect.Ptr: + ftype := field.Type + for ftype.Kind() == reflect.Ptr { + ftype = ftype.Elem() + } + if ftype.Kind() != reflect.Struct { + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + if reflect.PtrTo(ftype).Implements(unmarshalerType) { + inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) + } else { + sinfo, err := getStructInfo(ftype) + if err != nil { + return nil, err + } + for _, index := range sinfo.InlineUnmarshalers { + inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + } + default: + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + InlineUnmarshalers: inlineUnmarshalers, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} diff --git a/vendor/go.yaml.in/yaml/v3/yamlh.go b/vendor/go.yaml.in/yaml/v3/yamlh.go new file mode 100644 index 000000000..f59aa40f6 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/yamlh.go @@ -0,0 +1,811 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 + + yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. + yaml_TAIL_COMMENT_EVENT +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", + yaml_TAIL_COMMENT_EVENT: "tail comment", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// +// yaml_parser_set_input(). +// +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + newlines int // The number of line breaks since last non-break/non-blank character + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Comments + + head_comment []byte // The current head comments + line_comment []byte // The current line comments + foot_comment []byte // The current foot comments + tail_comment []byte // Foot comment that happens at the end of a block. + stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) + + comments []yaml_comment_t // The folded comments for all parsed tokens + comments_head int + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +type yaml_comment_t struct { + scan_mark yaml_mark_t // Position where scanning for comments started + token_mark yaml_mark_t // Position after which tokens will be associated with this comment + start_mark yaml_mark_t // Position of '#' comment mark + end_mark yaml_mark_t // Position where comment terminated + + head []byte + line []byte + foot []byte +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// +// yaml_emitter_set_output(). +// +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + compact_sequence_indent bool // Is '- ' is considered part of the indentation for sequence elements? + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + space_above bool // Is there's an empty line above? + foot_indent int // The indent used to write the foot comment above, or -1 if none. + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + + key_line_comment []byte + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/go.yaml.in/yaml/v3/yamlprivateh.go b/vendor/go.yaml.in/yaml/v3/yamlprivateh.go new file mode 100644 index 000000000..dea1ba961 --- /dev/null +++ b/vendor/go.yaml.in/yaml/v3/yamlprivateh.go @@ -0,0 +1,198 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( + // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( + // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( + // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +} diff --git a/vendor/golang.org/x/mod/LICENSE b/vendor/golang.org/x/mod/LICENSE new file mode 100644 index 000000000..2a7cf70da --- /dev/null +++ b/vendor/golang.org/x/mod/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/mod/PATENTS b/vendor/golang.org/x/mod/PATENTS new file mode 100644 index 000000000..733099041 --- /dev/null +++ b/vendor/golang.org/x/mod/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go b/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go new file mode 100644 index 000000000..150f887e7 --- /dev/null +++ b/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go @@ -0,0 +1,78 @@ +// Copyright 2018 The Go 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 lazyregexp is a thin wrapper over regexp, allowing the use of global +// regexp variables without forcing them to be compiled at init. +package lazyregexp + +import ( + "os" + "regexp" + "strings" + "sync" +) + +// Regexp is a wrapper around [regexp.Regexp], where the underlying regexp will be +// compiled the first time it is needed. +type Regexp struct { + str string + once sync.Once + rx *regexp.Regexp +} + +func (r *Regexp) re() *regexp.Regexp { + r.once.Do(r.build) + return r.rx +} + +func (r *Regexp) build() { + r.rx = regexp.MustCompile(r.str) + r.str = "" +} + +func (r *Regexp) FindSubmatch(s []byte) [][]byte { + return r.re().FindSubmatch(s) +} + +func (r *Regexp) FindStringSubmatch(s string) []string { + return r.re().FindStringSubmatch(s) +} + +func (r *Regexp) FindStringSubmatchIndex(s string) []int { + return r.re().FindStringSubmatchIndex(s) +} + +func (r *Regexp) ReplaceAllString(src, repl string) string { + return r.re().ReplaceAllString(src, repl) +} + +func (r *Regexp) FindString(s string) string { + return r.re().FindString(s) +} + +func (r *Regexp) FindAllString(s string, n int) []string { + return r.re().FindAllString(s, n) +} + +func (r *Regexp) MatchString(s string) bool { + return r.re().MatchString(s) +} + +func (r *Regexp) SubexpNames() []string { + return r.re().SubexpNames() +} + +var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") + +// New creates a new lazy regexp, delaying the compiling work until it is first +// needed. If the code is being run as part of tests, the regexp compiling will +// happen immediately. +func New(str string) *Regexp { + lr := &Regexp{str: str} + if inTest { + // In tests, always compile the regexps early. + lr.re() + } + return lr +} diff --git a/vendor/golang.org/x/mod/module/module.go b/vendor/golang.org/x/mod/module/module.go new file mode 100644 index 000000000..2a364b229 --- /dev/null +++ b/vendor/golang.org/x/mod/module/module.go @@ -0,0 +1,841 @@ +// Copyright 2018 The Go 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 module defines the module.Version type along with support code. +// +// The [module.Version] type is a simple Path, Version pair: +// +// type Version struct { +// Path string +// Version string +// } +// +// There are no restrictions imposed directly by use of this structure, +// but additional checking functions, most notably [Check], verify that +// a particular path, version pair is valid. +// +// # Escaped Paths +// +// Module paths appear as substrings of file system paths +// (in the download cache) and of web server URLs in the proxy protocol. +// In general we cannot rely on file systems to be case-sensitive, +// nor can we rely on web servers, since they read from file systems. +// That is, we cannot rely on the file system to keep rsc.io/QUOTE +// and rsc.io/quote separate. Windows and macOS don't. +// Instead, we must never require two different casings of a file path. +// Because we want the download cache to match the proxy protocol, +// and because we want the proxy protocol to be possible to serve +// from a tree of static files (which might be stored on a case-insensitive +// file system), the proxy protocol must never require two different casings +// of a URL path either. +// +// One possibility would be to make the escaped form be the lowercase +// hexadecimal encoding of the actual path bytes. This would avoid ever +// needing different casings of a file path, but it would be fairly illegible +// to most programmers when those paths appeared in the file system +// (including in file paths in compiler errors and stack traces) +// in web server logs, and so on. Instead, we want a safe escaped form that +// leaves most paths unaltered. +// +// The safe escaped form is to replace every uppercase letter +// with an exclamation mark followed by the letter's lowercase equivalent. +// +// For example, +// +// github.com/Azure/azure-sdk-for-go -> github.com/!azure/azure-sdk-for-go. +// github.com/GoogleCloudPlatform/cloudsql-proxy -> github.com/!google!cloud!platform/cloudsql-proxy +// github.com/Sirupsen/logrus -> github.com/!sirupsen/logrus. +// +// Import paths that avoid upper-case letters are left unchanged. +// Note that because import paths are ASCII-only and avoid various +// problematic punctuation (like : < and >), the escaped form is also ASCII-only +// and avoids the same problematic punctuation. +// +// Import paths have never allowed exclamation marks, so there is no +// need to define how to escape a literal !. +// +// # Unicode Restrictions +// +// Today, paths are disallowed from using Unicode. +// +// Although paths are currently disallowed from using Unicode, +// we would like at some point to allow Unicode letters as well, to assume that +// file systems and URLs are Unicode-safe (storing UTF-8), and apply +// the !-for-uppercase convention for escaping them in the file system. +// But there are at least two subtle considerations. +// +// First, note that not all case-fold equivalent distinct runes +// form an upper/lower pair. +// For example, U+004B ('K'), U+006B ('k'), and U+212A ('K' for Kelvin) +// are three distinct runes that case-fold to each other. +// When we do add Unicode letters, we must not assume that upper/lower +// are the only case-equivalent pairs. +// Perhaps the Kelvin symbol would be disallowed entirely, for example. +// Or perhaps it would escape as "!!k", or perhaps as "(212A)". +// +// Second, it would be nice to allow Unicode marks as well as letters, +// but marks include combining marks, and then we must deal not +// only with case folding but also normalization: both U+00E9 ('é') +// and U+0065 U+0301 ('e' followed by combining acute accent) +// look the same on the page and are treated by some file systems +// as the same path. If we do allow Unicode marks in paths, there +// must be some kind of normalization to allow only one canonical +// encoding of any character used in an import path. +package module + +// IMPORTANT NOTE +// +// This file essentially defines the set of valid import paths for the go command. +// There are many subtle considerations, including Unicode ambiguity, +// security, network, and file system representations. +// +// This file also defines the set of valid module path and version combinations, +// another topic with many subtle considerations. +// +// Changes to the semantics in this file require approval from rsc. + +import ( + "errors" + "fmt" + "path" + "sort" + "strings" + "unicode" + "unicode/utf8" + + "golang.org/x/mod/semver" +) + +// A Version (for clients, a module.Version) is defined by a module path and version pair. +// These are stored in their plain (unescaped) form. +type Version struct { + // Path is a module path, like "golang.org/x/text" or "rsc.io/quote/v2". + Path string + + // Version is usually a semantic version in canonical form. + // There are three exceptions to this general rule. + // First, the top-level target of a build has no specific version + // and uses Version = "". + // Second, during MVS calculations the version "none" is used + // to represent the decision to take no version of a given module. + // Third, filesystem paths found in "replace" directives are + // represented by a path with an empty version. + Version string `json:",omitempty"` +} + +// String returns a representation of the Version suitable for logging +// (Path@Version, or just Path if Version is empty). +func (m Version) String() string { + if m.Version == "" { + return m.Path + } + return m.Path + "@" + m.Version +} + +// A ModuleError indicates an error specific to a module. +type ModuleError struct { + Path string + Version string + Err error +} + +// VersionError returns a [ModuleError] derived from a [Version] and error, +// or err itself if it is already such an error. +func VersionError(v Version, err error) error { + var mErr *ModuleError + if errors.As(err, &mErr) && mErr.Path == v.Path && mErr.Version == v.Version { + return err + } + return &ModuleError{ + Path: v.Path, + Version: v.Version, + Err: err, + } +} + +func (e *ModuleError) Error() string { + if v, ok := e.Err.(*InvalidVersionError); ok { + return fmt.Sprintf("%s@%s: invalid %s: %v", e.Path, v.Version, v.noun(), v.Err) + } + if e.Version != "" { + return fmt.Sprintf("%s@%s: %v", e.Path, e.Version, e.Err) + } + return fmt.Sprintf("module %s: %v", e.Path, e.Err) +} + +func (e *ModuleError) Unwrap() error { return e.Err } + +// An InvalidVersionError indicates an error specific to a version, with the +// module path unknown or specified externally. +// +// A [ModuleError] may wrap an InvalidVersionError, but an InvalidVersionError +// must not wrap a ModuleError. +type InvalidVersionError struct { + Version string + Pseudo bool + Err error +} + +// noun returns either "version" or "pseudo-version", depending on whether +// e.Version is a pseudo-version. +func (e *InvalidVersionError) noun() string { + if e.Pseudo { + return "pseudo-version" + } + return "version" +} + +func (e *InvalidVersionError) Error() string { + return fmt.Sprintf("%s %q invalid: %s", e.noun(), e.Version, e.Err) +} + +func (e *InvalidVersionError) Unwrap() error { return e.Err } + +// An InvalidPathError indicates a module, import, or file path doesn't +// satisfy all naming constraints. See [CheckPath], [CheckImportPath], +// and [CheckFilePath] for specific restrictions. +type InvalidPathError struct { + Kind string // "module", "import", or "file" + Path string + Err error +} + +func (e *InvalidPathError) Error() string { + return fmt.Sprintf("malformed %s path %q: %v", e.Kind, e.Path, e.Err) +} + +func (e *InvalidPathError) Unwrap() error { return e.Err } + +// Check checks that a given module path, version pair is valid. +// In addition to the path being a valid module path +// and the version being a valid semantic version, +// the two must correspond. +// For example, the path "yaml/v2" only corresponds to +// semantic versions beginning with "v2.". +func Check(path, version string) error { + if err := CheckPath(path); err != nil { + return err + } + if !semver.IsValid(version) { + return &ModuleError{ + Path: path, + Err: &InvalidVersionError{Version: version, Err: errors.New("not a semantic version")}, + } + } + _, pathMajor, _ := SplitPathVersion(path) + if err := CheckPathMajor(version, pathMajor); err != nil { + return &ModuleError{Path: path, Err: err} + } + return nil +} + +// firstPathOK reports whether r can appear in the first element of a module path. +// The first element of the path must be an LDH domain name, at least for now. +// To avoid case ambiguity, the domain name must be entirely lower case. +func firstPathOK(r rune) bool { + return r == '-' || r == '.' || + '0' <= r && r <= '9' || + 'a' <= r && r <= 'z' +} + +// modPathOK reports whether r can appear in a module path element. +// Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: - . _ and ~. +// +// This matches what "go get" has historically recognized in import paths, +// and avoids confusing sequences like '%20' or '+' that would change meaning +// if used in a URL. +// +// TODO(rsc): We would like to allow Unicode letters, but that requires additional +// care in the safe encoding (see "escaped paths" above). +func modPathOK(r rune) bool { + if r < utf8.RuneSelf { + return r == '-' || r == '.' || r == '_' || r == '~' || + '0' <= r && r <= '9' || + 'A' <= r && r <= 'Z' || + 'a' <= r && r <= 'z' + } + return false +} + +// importPathOK reports whether r can appear in a package import path element. +// +// Import paths are intermediate between module paths and file paths: we allow +// disallow characters that would be confusing or ambiguous as arguments to +// 'go get' (such as '@' and ' ' ), but allow certain characters that are +// otherwise-unambiguous on the command line and historically used for some +// binary names (such as '++' as a suffix for compiler binaries and wrappers). +func importPathOK(r rune) bool { + return modPathOK(r) || r == '+' +} + +// fileNameOK reports whether r can appear in a file name. +// For now we allow all Unicode letters but otherwise limit to pathOK plus a few more punctuation characters. +// If we expand the set of allowed characters here, we have to +// work harder at detecting potential case-folding and normalization collisions. +// See note about "escaped paths" above. +func fileNameOK(r rune) bool { + if r < utf8.RuneSelf { + // Entire set of ASCII punctuation, from which we remove characters: + // ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ + // We disallow some shell special characters: " ' * < > ? ` | + // (Note that some of those are disallowed by the Windows file system as well.) + // We also disallow path separators / : and \ (fileNameOK is only called on path element characters). + // We allow spaces (U+0020) in file names. + const allowed = "!#$%&()+,-.=@[]^_{}~ " + if '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' { + return true + } + return strings.ContainsRune(allowed, r) + } + // It may be OK to add more ASCII punctuation here, but only carefully. + // For example Windows disallows < > \, and macOS disallows :, so we must not allow those. + return unicode.IsLetter(r) +} + +// CheckPath checks that a module path is valid. +// A valid module path is a valid import path, as checked by [CheckImportPath], +// with three additional constraints. +// First, the leading path element (up to the first slash, if any), +// by convention a domain name, must contain only lower-case ASCII letters, +// ASCII digits, dots (U+002E), and dashes (U+002D); +// it must contain at least one dot and cannot start with a dash. +// Second, for a final path element of the form /vN, where N looks numeric +// (ASCII digits and dots) must not begin with a leading zero, must not be /v1, +// and must not contain any dots. For paths beginning with "gopkg.in/", +// this second requirement is replaced by a requirement that the path +// follow the gopkg.in server's conventions. +// Third, no path element may begin with a dot. +func CheckPath(path string) (err error) { + defer func() { + if err != nil { + err = &InvalidPathError{Kind: "module", Path: path, Err: err} + } + }() + + if err := checkPath(path, modulePath); err != nil { + return err + } + i := strings.Index(path, "/") + if i < 0 { + i = len(path) + } + if i == 0 { + return fmt.Errorf("leading slash") + } + if !strings.Contains(path[:i], ".") { + return fmt.Errorf("missing dot in first path element") + } + if path[0] == '-' { + return fmt.Errorf("leading dash in first path element") + } + for _, r := range path[:i] { + if !firstPathOK(r) { + return fmt.Errorf("invalid char %q in first path element", r) + } + } + if _, _, ok := SplitPathVersion(path); !ok { + return fmt.Errorf("invalid version") + } + return nil +} + +// CheckImportPath checks that an import path is valid. +// +// A valid import path consists of one or more valid path elements +// separated by slashes (U+002F). (It must not begin with nor end in a slash.) +// +// A valid path element is a non-empty string made up of +// ASCII letters, ASCII digits, and limited ASCII punctuation: - . _ and ~. +// It must not end with a dot (U+002E), nor contain two dots in a row. +// +// The element prefix up to the first dot must not be a reserved file name +// on Windows, regardless of case (CON, com1, NuL, and so on). The element +// must not have a suffix of a tilde followed by one or more ASCII digits +// (to exclude paths elements that look like Windows short-names). +// +// CheckImportPath may be less restrictive in the future, but see the +// top-level package documentation for additional information about +// subtleties of Unicode. +func CheckImportPath(path string) error { + if err := checkPath(path, importPath); err != nil { + return &InvalidPathError{Kind: "import", Path: path, Err: err} + } + return nil +} + +// pathKind indicates what kind of path we're checking. Module paths, +// import paths, and file paths have different restrictions. +type pathKind int + +const ( + modulePath pathKind = iota + importPath + filePath +) + +// checkPath checks that a general path is valid. kind indicates what +// specific constraints should be applied. +// +// checkPath returns an error describing why the path is not valid. +// Because these checks apply to module, import, and file paths, +// and because other checks may be applied, the caller is expected to wrap +// this error with [InvalidPathError]. +func checkPath(path string, kind pathKind) error { + if !utf8.ValidString(path) { + return fmt.Errorf("invalid UTF-8") + } + if path == "" { + return fmt.Errorf("empty string") + } + if path[0] == '-' && kind != filePath { + return fmt.Errorf("leading dash") + } + if strings.Contains(path, "//") { + return fmt.Errorf("double slash") + } + if path[len(path)-1] == '/' { + return fmt.Errorf("trailing slash") + } + elemStart := 0 + for i, r := range path { + if r == '/' { + if err := checkElem(path[elemStart:i], kind); err != nil { + return err + } + elemStart = i + 1 + } + } + if err := checkElem(path[elemStart:], kind); err != nil { + return err + } + return nil +} + +// checkElem checks whether an individual path element is valid. +func checkElem(elem string, kind pathKind) error { + if elem == "" { + return fmt.Errorf("empty path element") + } + if strings.Count(elem, ".") == len(elem) { + return fmt.Errorf("invalid path element %q", elem) + } + if elem[0] == '.' && kind == modulePath { + return fmt.Errorf("leading dot in path element") + } + if elem[len(elem)-1] == '.' { + return fmt.Errorf("trailing dot in path element") + } + for _, r := range elem { + ok := false + switch kind { + case modulePath: + ok = modPathOK(r) + case importPath: + ok = importPathOK(r) + case filePath: + ok = fileNameOK(r) + default: + panic(fmt.Sprintf("internal error: invalid kind %v", kind)) + } + if !ok { + return fmt.Errorf("invalid char %q", r) + } + } + + // Windows disallows a bunch of path elements, sadly. + // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file + short := elem + if i := strings.Index(short, "."); i >= 0 { + short = short[:i] + } + for _, bad := range badWindowsNames { + if strings.EqualFold(bad, short) { + return fmt.Errorf("%q disallowed as path element component on Windows", short) + } + } + + if kind == filePath { + // don't check for Windows short-names in file names. They're + // only an issue for import paths. + return nil + } + + // Reject path components that look like Windows short-names. + // Those usually end in a tilde followed by one or more ASCII digits. + if tilde := strings.LastIndexByte(short, '~'); tilde >= 0 && tilde < len(short)-1 { + suffix := short[tilde+1:] + suffixIsDigits := true + for _, r := range suffix { + if r < '0' || r > '9' { + suffixIsDigits = false + break + } + } + if suffixIsDigits { + return fmt.Errorf("trailing tilde and digits in path element") + } + } + + return nil +} + +// CheckFilePath checks that a slash-separated file path is valid. +// The definition of a valid file path is the same as the definition +// of a valid import path except that the set of allowed characters is larger: +// all Unicode letters, ASCII digits, the ASCII space character (U+0020), +// and the ASCII punctuation characters +// “!#$%&()+,-.=@[]^_{}~”. +// (The excluded punctuation characters, " * < > ? ` ' | / \ and :, +// have special meanings in certain shells or operating systems.) +// +// CheckFilePath may be less restrictive in the future, but see the +// top-level package documentation for additional information about +// subtleties of Unicode. +func CheckFilePath(path string) error { + if err := checkPath(path, filePath); err != nil { + return &InvalidPathError{Kind: "file", Path: path, Err: err} + } + return nil +} + +// badWindowsNames are the reserved file path elements on Windows. +// See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file +var badWindowsNames = []string{ + "CON", + "PRN", + "AUX", + "NUL", + "COM1", + "COM2", + "COM3", + "COM4", + "COM5", + "COM6", + "COM7", + "COM8", + "COM9", + "LPT1", + "LPT2", + "LPT3", + "LPT4", + "LPT5", + "LPT6", + "LPT7", + "LPT8", + "LPT9", +} + +// SplitPathVersion returns prefix and major version such that prefix+pathMajor == path +// and version is either empty or "/vN" for N >= 2. +// As a special case, gopkg.in paths are recognized directly; +// they require ".vN" instead of "/vN", and for all N, not just N >= 2. +// SplitPathVersion returns with ok = false when presented with +// a path whose last path element does not satisfy the constraints +// applied by [CheckPath], such as "example.com/pkg/v1" or "example.com/pkg/v1.2". +func SplitPathVersion(path string) (prefix, pathMajor string, ok bool) { + if strings.HasPrefix(path, "gopkg.in/") { + return splitGopkgIn(path) + } + + i := len(path) + dot := false + for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') { + if path[i-1] == '.' { + dot = true + } + i-- + } + if i <= 1 || i == len(path) || path[i-1] != 'v' || path[i-2] != '/' { + return path, "", true + } + prefix, pathMajor = path[:i-2], path[i-2:] + if dot || len(pathMajor) <= 2 || pathMajor[2] == '0' || pathMajor == "/v1" { + return path, "", false + } + return prefix, pathMajor, true +} + +// splitGopkgIn is like SplitPathVersion but only for gopkg.in paths. +func splitGopkgIn(path string) (prefix, pathMajor string, ok bool) { + if !strings.HasPrefix(path, "gopkg.in/") { + return path, "", false + } + i := len(path) + if strings.HasSuffix(path, "-unstable") { + i -= len("-unstable") + } + for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9') { + i-- + } + if i <= 1 || path[i-1] != 'v' || path[i-2] != '.' { + // All gopkg.in paths must end in vN for some N. + return path, "", false + } + prefix, pathMajor = path[:i-2], path[i-2:] + if len(pathMajor) <= 2 || pathMajor[2] == '0' && pathMajor != ".v0" { + return path, "", false + } + return prefix, pathMajor, true +} + +// MatchPathMajor reports whether the semantic version v +// matches the path major version pathMajor. +// +// MatchPathMajor returns true if and only if [CheckPathMajor] returns nil. +func MatchPathMajor(v, pathMajor string) bool { + return CheckPathMajor(v, pathMajor) == nil +} + +// CheckPathMajor returns a non-nil error if the semantic version v +// does not match the path major version pathMajor. +func CheckPathMajor(v, pathMajor string) error { + // TODO(jayconrod): return errors or panic for invalid inputs. This function + // (and others) was covered by integration tests for cmd/go, and surrounding + // code protected against invalid inputs like non-canonical versions. + if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") { + pathMajor = strings.TrimSuffix(pathMajor, "-unstable") + } + if strings.HasPrefix(v, "v0.0.0-") && pathMajor == ".v1" { + // Allow old bug in pseudo-versions that generated v0.0.0- pseudoversion for gopkg .v1. + // For example, gopkg.in/yaml.v2@v2.2.1's go.mod requires gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405. + return nil + } + m := semver.Major(v) + if pathMajor == "" { + if m == "v0" || m == "v1" || semver.Build(v) == "+incompatible" { + return nil + } + pathMajor = "v0 or v1" + } else if pathMajor[0] == '/' || pathMajor[0] == '.' { + if m == pathMajor[1:] { + return nil + } + pathMajor = pathMajor[1:] + } + return &InvalidVersionError{ + Version: v, + Err: fmt.Errorf("should be %s, not %s", pathMajor, semver.Major(v)), + } +} + +// PathMajorPrefix returns the major-version tag prefix implied by pathMajor. +// An empty PathMajorPrefix allows either v0 or v1. +// +// Note that [MatchPathMajor] may accept some versions that do not actually begin +// with this prefix: namely, it accepts a 'v0.0.0-' prefix for a '.v1' +// pathMajor, even though that pathMajor implies 'v1' tagging. +func PathMajorPrefix(pathMajor string) string { + if pathMajor == "" { + return "" + } + if pathMajor[0] != '/' && pathMajor[0] != '.' { + panic("pathMajor suffix " + pathMajor + " passed to PathMajorPrefix lacks separator") + } + if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") { + pathMajor = strings.TrimSuffix(pathMajor, "-unstable") + } + m := pathMajor[1:] + if m != semver.Major(m) { + panic("pathMajor suffix " + pathMajor + "passed to PathMajorPrefix is not a valid major version") + } + return m +} + +// CanonicalVersion returns the canonical form of the version string v. +// It is the same as [semver.Canonical] except that it preserves the special build suffix "+incompatible". +func CanonicalVersion(v string) string { + cv := semver.Canonical(v) + if semver.Build(v) == "+incompatible" { + cv += "+incompatible" + } + return cv +} + +// Sort sorts the list by Path, breaking ties by comparing [Version] fields. +// The Version fields are interpreted as semantic versions (using [semver.Compare]) +// optionally followed by a tie-breaking suffix introduced by a slash character, +// like in "v0.0.1/go.mod". +func Sort(list []Version) { + sort.Slice(list, func(i, j int) bool { + mi := list[i] + mj := list[j] + if mi.Path != mj.Path { + return mi.Path < mj.Path + } + // To help go.sum formatting, allow version/file. + // Compare semver prefix by semver rules, + // file by string order. + vi := mi.Version + vj := mj.Version + var fi, fj string + if k := strings.Index(vi, "/"); k >= 0 { + vi, fi = vi[:k], vi[k:] + } + if k := strings.Index(vj, "/"); k >= 0 { + vj, fj = vj[:k], vj[k:] + } + if vi != vj { + return semver.Compare(vi, vj) < 0 + } + return fi < fj + }) +} + +// EscapePath returns the escaped form of the given module path. +// It fails if the module path is invalid. +func EscapePath(path string) (escaped string, err error) { + if err := CheckPath(path); err != nil { + return "", err + } + + return escapeString(path) +} + +// EscapeVersion returns the escaped form of the given module version. +// Versions are allowed to be in non-semver form but must be valid file names +// and not contain exclamation marks. +func EscapeVersion(v string) (escaped string, err error) { + if err := checkElem(v, filePath); err != nil || strings.Contains(v, "!") { + return "", &InvalidVersionError{ + Version: v, + Err: fmt.Errorf("disallowed version string"), + } + } + return escapeString(v) +} + +func escapeString(s string) (escaped string, err error) { + haveUpper := false + for _, r := range s { + if r == '!' || r >= utf8.RuneSelf { + // This should be disallowed by CheckPath, but diagnose anyway. + // The correctness of the escaping loop below depends on it. + return "", fmt.Errorf("internal error: inconsistency in EscapePath") + } + if 'A' <= r && r <= 'Z' { + haveUpper = true + } + } + + if !haveUpper { + return s, nil + } + + var buf []byte + for _, r := range s { + if 'A' <= r && r <= 'Z' { + buf = append(buf, '!', byte(r+'a'-'A')) + } else { + buf = append(buf, byte(r)) + } + } + return string(buf), nil +} + +// UnescapePath returns the module path for the given escaped path. +// It fails if the escaped path is invalid or describes an invalid path. +func UnescapePath(escaped string) (path string, err error) { + path, ok := unescapeString(escaped) + if !ok { + return "", fmt.Errorf("invalid escaped module path %q", escaped) + } + if err := CheckPath(path); err != nil { + return "", fmt.Errorf("invalid escaped module path %q: %v", escaped, err) + } + return path, nil +} + +// UnescapeVersion returns the version string for the given escaped version. +// It fails if the escaped form is invalid or describes an invalid version. +// Versions are allowed to be in non-semver form but must be valid file names +// and not contain exclamation marks. +func UnescapeVersion(escaped string) (v string, err error) { + v, ok := unescapeString(escaped) + if !ok { + return "", fmt.Errorf("invalid escaped version %q", escaped) + } + if err := checkElem(v, filePath); err != nil { + return "", fmt.Errorf("invalid escaped version %q: %v", v, err) + } + return v, nil +} + +func unescapeString(escaped string) (string, bool) { + var buf []byte + + bang := false + for _, r := range escaped { + if r >= utf8.RuneSelf { + return "", false + } + if bang { + bang = false + if r < 'a' || 'z' < r { + return "", false + } + buf = append(buf, byte(r+'A'-'a')) + continue + } + if r == '!' { + bang = true + continue + } + if 'A' <= r && r <= 'Z' { + return "", false + } + buf = append(buf, byte(r)) + } + if bang { + return "", false + } + return string(buf), true +} + +// MatchPrefixPatterns reports whether any path prefix of target matches one of +// the glob patterns (as defined by [path.Match]) in the comma-separated globs +// list. This implements the algorithm used when matching a module path to the +// GOPRIVATE environment variable, as described by 'go help module-private'. +// +// It ignores any empty or malformed patterns in the list. +// Trailing slashes on patterns are ignored. +func MatchPrefixPatterns(globs, target string) bool { + for globs != "" { + // Extract next non-empty glob in comma-separated list. + var glob string + if i := strings.Index(globs, ","); i >= 0 { + glob, globs = globs[:i], globs[i+1:] + } else { + glob, globs = globs, "" + } + glob = strings.TrimSuffix(glob, "/") + if glob == "" { + continue + } + + // A glob with N+1 path elements (N slashes) needs to be matched + // against the first N+1 path elements of target, + // which end just before the N+1'th slash. + n := strings.Count(glob, "/") + prefix := target + // Walk target, counting slashes, truncating at the N+1'th slash. + for i := 0; i < len(target); i++ { + if target[i] == '/' { + if n == 0 { + prefix = target[:i] + break + } + n-- + } + } + if n > 0 { + // Not enough prefix elements. + continue + } + matched, _ := path.Match(glob, prefix) + if matched { + return true + } + } + return false +} diff --git a/vendor/golang.org/x/mod/module/pseudo.go b/vendor/golang.org/x/mod/module/pseudo.go new file mode 100644 index 000000000..9cf19d325 --- /dev/null +++ b/vendor/golang.org/x/mod/module/pseudo.go @@ -0,0 +1,250 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Pseudo-versions +// +// Code authors are expected to tag the revisions they want users to use, +// including prereleases. However, not all authors tag versions at all, +// and not all commits a user might want to try will have tags. +// A pseudo-version is a version with a special form that allows us to +// address an untagged commit and order that version with respect to +// other versions we might encounter. +// +// A pseudo-version takes one of the general forms: +// +// (1) vX.0.0-yyyymmddhhmmss-abcdef123456 +// (2) vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456 +// (3) vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456+incompatible +// (4) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456 +// (5) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456+incompatible +// +// If there is no recently tagged version with the right major version vX, +// then form (1) is used, creating a space of pseudo-versions at the bottom +// of the vX version range, less than any tagged version, including the unlikely v0.0.0. +// +// If the most recent tagged version before the target commit is vX.Y.Z or vX.Y.Z+incompatible, +// then the pseudo-version uses form (2) or (3), making it a prerelease for the next +// possible semantic version after vX.Y.Z. The leading 0 segment in the prerelease string +// ensures that the pseudo-version compares less than possible future explicit prereleases +// like vX.Y.(Z+1)-rc1 or vX.Y.(Z+1)-1. +// +// If the most recent tagged version before the target commit is vX.Y.Z-pre or vX.Y.Z-pre+incompatible, +// then the pseudo-version uses form (4) or (5), making it a slightly later prerelease. + +package module + +import ( + "errors" + "fmt" + "strings" + "time" + + "golang.org/x/mod/internal/lazyregexp" + "golang.org/x/mod/semver" +) + +var pseudoVersionRE = lazyregexp.New(`^v[0-9]+\.(0\.0-|\d+\.\d+-([^+]*\.)?0\.)\d{14}-[A-Za-z0-9]+(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`) + +const PseudoVersionTimestampFormat = "20060102150405" + +// PseudoVersion returns a pseudo-version for the given major version ("v1") +// preexisting older tagged version ("" or "v1.2.3" or "v1.2.3-pre"), revision time, +// and revision identifier (usually a 12-byte commit hash prefix). +func PseudoVersion(major, older string, t time.Time, rev string) string { + if major == "" { + major = "v0" + } + segment := fmt.Sprintf("%s-%s", t.UTC().Format(PseudoVersionTimestampFormat), rev) + build := semver.Build(older) + older = semver.Canonical(older) + if older == "" { + return major + ".0.0-" + segment // form (1) + } + if semver.Prerelease(older) != "" { + return older + ".0." + segment + build // form (4), (5) + } + + // Form (2), (3). + // Extract patch from vMAJOR.MINOR.PATCH + i := strings.LastIndex(older, ".") + 1 + v, patch := older[:i], older[i:] + + // Reassemble. + return v + incDecimal(patch) + "-0." + segment + build +} + +// ZeroPseudoVersion returns a pseudo-version with a zero timestamp and +// revision, which may be used as a placeholder. +func ZeroPseudoVersion(major string) string { + return PseudoVersion(major, "", time.Time{}, "000000000000") +} + +// incDecimal returns the decimal string incremented by 1. +func incDecimal(decimal string) string { + // Scan right to left turning 9s to 0s until you find a digit to increment. + digits := []byte(decimal) + i := len(digits) - 1 + for ; i >= 0 && digits[i] == '9'; i-- { + digits[i] = '0' + } + if i >= 0 { + digits[i]++ + } else { + // digits is all zeros + digits[0] = '1' + digits = append(digits, '0') + } + return string(digits) +} + +// decDecimal returns the decimal string decremented by 1, or the empty string +// if the decimal is all zeroes. +func decDecimal(decimal string) string { + // Scan right to left turning 0s to 9s until you find a digit to decrement. + digits := []byte(decimal) + i := len(digits) - 1 + for ; i >= 0 && digits[i] == '0'; i-- { + digits[i] = '9' + } + if i < 0 { + // decimal is all zeros + return "" + } + if i == 0 && digits[i] == '1' && len(digits) > 1 { + digits = digits[1:] + } else { + digits[i]-- + } + return string(digits) +} + +// IsPseudoVersion reports whether v is a pseudo-version. +func IsPseudoVersion(v string) bool { + return strings.Count(v, "-") >= 2 && semver.IsValid(v) && pseudoVersionRE.MatchString(v) +} + +// IsZeroPseudoVersion returns whether v is a pseudo-version with a zero base, +// timestamp, and revision, as returned by [ZeroPseudoVersion]. +func IsZeroPseudoVersion(v string) bool { + return v == ZeroPseudoVersion(semver.Major(v)) +} + +// PseudoVersionTime returns the time stamp of the pseudo-version v. +// It returns an error if v is not a pseudo-version or if the time stamp +// embedded in the pseudo-version is not a valid time. +func PseudoVersionTime(v string) (time.Time, error) { + _, timestamp, _, _, err := parsePseudoVersion(v) + if err != nil { + return time.Time{}, err + } + t, err := time.Parse("20060102150405", timestamp) + if err != nil { + return time.Time{}, &InvalidVersionError{ + Version: v, + Pseudo: true, + Err: fmt.Errorf("malformed time %q", timestamp), + } + } + return t, nil +} + +// PseudoVersionRev returns the revision identifier of the pseudo-version v. +// It returns an error if v is not a pseudo-version. +func PseudoVersionRev(v string) (rev string, err error) { + _, _, rev, _, err = parsePseudoVersion(v) + return +} + +// PseudoVersionBase returns the canonical parent version, if any, upon which +// the pseudo-version v is based. +// +// If v has no parent version (that is, if it is "vX.0.0-[…]"), +// PseudoVersionBase returns the empty string and a nil error. +func PseudoVersionBase(v string) (string, error) { + base, _, _, build, err := parsePseudoVersion(v) + if err != nil { + return "", err + } + + switch pre := semver.Prerelease(base); pre { + case "": + // vX.0.0-yyyymmddhhmmss-abcdef123456 → "" + if build != "" { + // Pseudo-versions of the form vX.0.0-yyyymmddhhmmss-abcdef123456+incompatible + // are nonsensical: the "vX.0.0-" prefix implies that there is no parent tag, + // but the "+incompatible" suffix implies that the major version of + // the parent tag is not compatible with the module's import path. + // + // There are a few such entries in the index generated by proxy.golang.org, + // but we believe those entries were generated by the proxy itself. + return "", &InvalidVersionError{ + Version: v, + Pseudo: true, + Err: fmt.Errorf("lacks base version, but has build metadata %q", build), + } + } + return "", nil + + case "-0": + // vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456 → vX.Y.Z + // vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456+incompatible → vX.Y.Z+incompatible + base = strings.TrimSuffix(base, pre) + i := strings.LastIndexByte(base, '.') + if i < 0 { + panic("base from parsePseudoVersion missing patch number: " + base) + } + patch := decDecimal(base[i+1:]) + if patch == "" { + // vX.0.0-0 is invalid, but has been observed in the wild in the index + // generated by requests to proxy.golang.org. + // + // NOTE(bcmills): I cannot find a historical bug that accounts for + // pseudo-versions of this form, nor have I seen such versions in any + // actual go.mod files. If we find actual examples of this form and a + // reasonable theory of how they came into existence, it seems fine to + // treat them as equivalent to vX.0.0 (especially since the invalid + // pseudo-versions have lower precedence than the real ones). For now, we + // reject them. + return "", &InvalidVersionError{ + Version: v, + Pseudo: true, + Err: fmt.Errorf("version before %s would have negative patch number", base), + } + } + return base[:i+1] + patch + build, nil + + default: + // vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456 → vX.Y.Z-pre + // vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456+incompatible → vX.Y.Z-pre+incompatible + if !strings.HasSuffix(base, ".0") { + panic(`base from parsePseudoVersion missing ".0" before date: ` + base) + } + return strings.TrimSuffix(base, ".0") + build, nil + } +} + +var errPseudoSyntax = errors.New("syntax error") + +func parsePseudoVersion(v string) (base, timestamp, rev, build string, err error) { + if !IsPseudoVersion(v) { + return "", "", "", "", &InvalidVersionError{ + Version: v, + Pseudo: true, + Err: errPseudoSyntax, + } + } + build = semver.Build(v) + v = strings.TrimSuffix(v, build) + j := strings.LastIndex(v, "-") + v, rev = v[:j], v[j+1:] + i := strings.LastIndex(v, "-") + if j := strings.LastIndex(v, "."); j > i { + base = v[:j] // "vX.Y.Z-pre.0" or "vX.Y.(Z+1)-0" + timestamp = v[j+1:] + } else { + base = v[:i] // "vX.0.0" + timestamp = v[i+1:] + } + return base, timestamp, rev, build, nil +} diff --git a/vendor/golang.org/x/mod/semver/semver.go b/vendor/golang.org/x/mod/semver/semver.go new file mode 100644 index 000000000..9a2dfd33a --- /dev/null +++ b/vendor/golang.org/x/mod/semver/semver.go @@ -0,0 +1,401 @@ +// Copyright 2018 The Go 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 semver implements comparison of semantic version strings. +// In this package, semantic version strings must begin with a leading "v", +// as in "v1.0.0". +// +// The general form of a semantic version string accepted by this package is +// +// vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]] +// +// where square brackets indicate optional parts of the syntax; +// MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros; +// PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers +// using only alphanumeric characters and hyphens; and +// all-numeric PRERELEASE identifiers must not have leading zeros. +// +// This package follows Semantic Versioning 2.0.0 (see semver.org) +// with two exceptions. First, it requires the "v" prefix. Second, it recognizes +// vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes) +// as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0. +package semver + +import "sort" + +// parsed returns the parsed form of a semantic version string. +type parsed struct { + major string + minor string + patch string + short string + prerelease string + build string +} + +// IsValid reports whether v is a valid semantic version string. +func IsValid(v string) bool { + _, ok := parse(v) + return ok +} + +// Canonical returns the canonical formatting of the semantic version v. +// It fills in any missing .MINOR or .PATCH and discards build metadata. +// Two semantic versions compare equal only if their canonical formattings +// are identical strings. +// The canonical invalid semantic version is the empty string. +func Canonical(v string) string { + p, ok := parse(v) + if !ok { + return "" + } + if p.build != "" { + return v[:len(v)-len(p.build)] + } + if p.short != "" { + return v + p.short + } + return v +} + +// Major returns the major version prefix of the semantic version v. +// For example, Major("v2.1.0") == "v2". +// If v is an invalid semantic version string, Major returns the empty string. +func Major(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return v[:1+len(pv.major)] +} + +// MajorMinor returns the major.minor version prefix of the semantic version v. +// For example, MajorMinor("v2.1.0") == "v2.1". +// If v is an invalid semantic version string, MajorMinor returns the empty string. +func MajorMinor(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + i := 1 + len(pv.major) + if j := i + 1 + len(pv.minor); j <= len(v) && v[i] == '.' && v[i+1:j] == pv.minor { + return v[:j] + } + return v[:i] + "." + pv.minor +} + +// Prerelease returns the prerelease suffix of the semantic version v. +// For example, Prerelease("v2.1.0-pre+meta") == "-pre". +// If v is an invalid semantic version string, Prerelease returns the empty string. +func Prerelease(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return pv.prerelease +} + +// Build returns the build suffix of the semantic version v. +// For example, Build("v2.1.0+meta") == "+meta". +// If v is an invalid semantic version string, Build returns the empty string. +func Build(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return pv.build +} + +// Compare returns an integer comparing two versions according to +// semantic version precedence. +// The result will be 0 if v == w, -1 if v < w, or +1 if v > w. +// +// An invalid semantic version string is considered less than a valid one. +// All invalid semantic version strings compare equal to each other. +func Compare(v, w string) int { + pv, ok1 := parse(v) + pw, ok2 := parse(w) + if !ok1 && !ok2 { + return 0 + } + if !ok1 { + return -1 + } + if !ok2 { + return +1 + } + if c := compareInt(pv.major, pw.major); c != 0 { + return c + } + if c := compareInt(pv.minor, pw.minor); c != 0 { + return c + } + if c := compareInt(pv.patch, pw.patch); c != 0 { + return c + } + return comparePrerelease(pv.prerelease, pw.prerelease) +} + +// Max canonicalizes its arguments and then returns the version string +// that compares greater. +// +// Deprecated: use [Compare] instead. In most cases, returning a canonicalized +// version is not expected or desired. +func Max(v, w string) string { + v = Canonical(v) + w = Canonical(w) + if Compare(v, w) > 0 { + return v + } + return w +} + +// ByVersion implements [sort.Interface] for sorting semantic version strings. +type ByVersion []string + +func (vs ByVersion) Len() int { return len(vs) } +func (vs ByVersion) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } +func (vs ByVersion) Less(i, j int) bool { + cmp := Compare(vs[i], vs[j]) + if cmp != 0 { + return cmp < 0 + } + return vs[i] < vs[j] +} + +// Sort sorts a list of semantic version strings using [ByVersion]. +func Sort(list []string) { + sort.Sort(ByVersion(list)) +} + +func parse(v string) (p parsed, ok bool) { + if v == "" || v[0] != 'v' { + return + } + p.major, v, ok = parseInt(v[1:]) + if !ok { + return + } + if v == "" { + p.minor = "0" + p.patch = "0" + p.short = ".0.0" + return + } + if v[0] != '.' { + ok = false + return + } + p.minor, v, ok = parseInt(v[1:]) + if !ok { + return + } + if v == "" { + p.patch = "0" + p.short = ".0" + return + } + if v[0] != '.' { + ok = false + return + } + p.patch, v, ok = parseInt(v[1:]) + if !ok { + return + } + if len(v) > 0 && v[0] == '-' { + p.prerelease, v, ok = parsePrerelease(v) + if !ok { + return + } + } + if len(v) > 0 && v[0] == '+' { + p.build, v, ok = parseBuild(v) + if !ok { + return + } + } + if v != "" { + ok = false + return + } + ok = true + return +} + +func parseInt(v string) (t, rest string, ok bool) { + if v == "" { + return + } + if v[0] < '0' || '9' < v[0] { + return + } + i := 1 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + if v[0] == '0' && i != 1 { + return + } + return v[:i], v[i:], true +} + +func parsePrerelease(v string) (t, rest string, ok bool) { + // "A pre-release version MAY be denoted by appending a hyphen and + // a series of dot separated identifiers immediately following the patch version. + // Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. + // Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes." + if v == "" || v[0] != '-' { + return + } + i := 1 + start := 1 + for i < len(v) && v[i] != '+' { + if !isIdentChar(v[i]) && v[i] != '.' { + return + } + if v[i] == '.' { + if start == i || isBadNum(v[start:i]) { + return + } + start = i + 1 + } + i++ + } + if start == i || isBadNum(v[start:i]) { + return + } + return v[:i], v[i:], true +} + +func parseBuild(v string) (t, rest string, ok bool) { + if v == "" || v[0] != '+' { + return + } + i := 1 + start := 1 + for i < len(v) { + if !isIdentChar(v[i]) && v[i] != '.' { + return + } + if v[i] == '.' { + if start == i { + return + } + start = i + 1 + } + i++ + } + if start == i { + return + } + return v[:i], v[i:], true +} + +func isIdentChar(c byte) bool { + return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '-' +} + +func isBadNum(v string) bool { + i := 0 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + return i == len(v) && i > 1 && v[0] == '0' +} + +func isNum(v string) bool { + i := 0 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + return i == len(v) +} + +func compareInt(x, y string) int { + if x == y { + return 0 + } + if len(x) < len(y) { + return -1 + } + if len(x) > len(y) { + return +1 + } + if x < y { + return -1 + } else { + return +1 + } +} + +func comparePrerelease(x, y string) int { + // "When major, minor, and patch are equal, a pre-release version has + // lower precedence than a normal version. + // Example: 1.0.0-alpha < 1.0.0. + // Precedence for two pre-release versions with the same major, minor, + // and patch version MUST be determined by comparing each dot separated + // identifier from left to right until a difference is found as follows: + // identifiers consisting of only digits are compared numerically and + // identifiers with letters or hyphens are compared lexically in ASCII + // sort order. Numeric identifiers always have lower precedence than + // non-numeric identifiers. A larger set of pre-release fields has a + // higher precedence than a smaller set, if all of the preceding + // identifiers are equal. + // Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < + // 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0." + if x == y { + return 0 + } + if x == "" { + return +1 + } + if y == "" { + return -1 + } + for x != "" && y != "" { + x = x[1:] // skip - or . + y = y[1:] // skip - or . + var dx, dy string + dx, x = nextIdent(x) + dy, y = nextIdent(y) + if dx != dy { + ix := isNum(dx) + iy := isNum(dy) + if ix != iy { + if ix { + return -1 + } else { + return +1 + } + } + if ix { + if len(dx) < len(dy) { + return -1 + } + if len(dx) > len(dy) { + return +1 + } + } + if dx < dy { + return -1 + } else { + return +1 + } + } + } + if x == "" { + return -1 + } else { + return +1 + } +} + +func nextIdent(x string) (dx, rest string) { + i := 0 + for i < len(x) && x[i] != '.' { + i++ + } + return x[:i], x[i:] +} diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go deleted file mode 100644 index db1c95fab..000000000 --- a/vendor/golang.org/x/net/context/context.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2014 The Go 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 context defines the Context type, which carries deadlines, -// cancellation signals, and other request-scoped values across API boundaries -// and between processes. -// As of Go 1.7 this package is available in the standard library under the -// name [context], and migrating to it can be done automatically with [go fix]. -// -// Incoming requests to a server should create a [Context], and outgoing -// calls to servers should accept a Context. The chain of function -// calls between them must propagate the Context, optionally replacing -// it with a derived Context created using [WithCancel], [WithDeadline], -// [WithTimeout], or [WithValue]. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. This is discussed further in -// https://go.dev/blog/context-and-structs. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See https://go.dev/blog/context for example code for a server that uses -// Contexts. -// -// [go fix]: https://go.dev/cmd/go#hdr-Update_packages_to_use_new_APIs -package context - -import ( - "context" // standard library's context, as of Go 1.7 - "time" -) - -// A Context carries a deadline, a cancellation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context = context.Context - -// Canceled is the error returned by [Context.Err] when the context is canceled -// for some reason other than its deadline passing. -var Canceled = context.Canceled - -// DeadlineExceeded is the error returned by [Context.Err] when the context is canceled -// due to its deadline passing. -var DeadlineExceeded = context.DeadlineExceeded - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). -func TODO() Context { - return todo -} - -var ( - background = context.Background() - todo = context.TODO() -) - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// A CancelFunc may be called by multiple goroutines simultaneously. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc = context.CancelFunc - -// WithCancel returns a derived context that points to the parent context -// but has a new Done channel. The returned context's Done channel is closed -// when the returned cancel function is called or when the parent context's -// Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this [Context] complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - return context.WithCancel(parent) -} - -// WithDeadline returns a derived context that points to the parent context -// but has the deadline adjusted to be no later than d. If the parent's -// deadline is already earlier than d, WithDeadline(parent, d) is semantically -// equivalent to parent. The returned [Context.Done] channel is closed when -// the deadline expires, when the returned cancel function is called, -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this [Context] complete. -func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { - return context.WithDeadline(parent, d) -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this [Context] complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return context.WithTimeout(parent, timeout) -} - -// WithValue returns a derived context that points to the parent Context. -// In the derived context, the value associated with key is val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The provided key must be comparable and should not be of type -// string or any other built-in type to avoid collisions between -// packages using context. Users of WithValue should define their own -// types for keys. To avoid allocating when assigning to an -// interface{}, context keys often have concrete type -// struct{}. Alternatively, exported context key variables' static -// type should be a pointer or interface. -func WithValue(parent Context, key, val interface{}) Context { - return context.WithValue(parent, key, val) -} diff --git a/vendor/golang.org/x/sync/errgroup/errgroup.go b/vendor/golang.org/x/sync/errgroup/errgroup.go index a4ea5d14f..f8c3c0926 100644 --- a/vendor/golang.org/x/sync/errgroup/errgroup.go +++ b/vendor/golang.org/x/sync/errgroup/errgroup.go @@ -18,7 +18,7 @@ import ( type token struct{} // A Group is a collection of goroutines working on subtasks that are part of -// the same overall task. +// the same overall task. A Group should not be reused for different tasks. // // A zero Group is valid, has no limit on the number of active goroutines, // and does not cancel on error. @@ -61,6 +61,7 @@ func (g *Group) Wait() error { } // Go calls the given function in a new goroutine. +// The first call to Go must happen before a Wait. // It blocks until the new goroutine can be added without the number of // active goroutines in the group exceeding the configured limit. // diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 099867dee..798f61ad3 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -602,7 +602,150 @@ func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocI return } -//sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) +// sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) +const minIovec = 8 + +func Readv(fd int, iovs [][]byte) (n int, err error) { + if !darwinKernelVersionMin(11, 0, 0) { + return 0, ENOSYS + } + + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + n, err = readv(fd, iovecs) + readvRacedetect(iovecs, n, err) + return n, err +} + +func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) { + if !darwinKernelVersionMin(11, 0, 0) { + return 0, ENOSYS + } + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + n, err = preadv(fd, iovecs, offset) + readvRacedetect(iovecs, n, err) + return n, err +} + +func Writev(fd int, iovs [][]byte) (n int, err error) { + if !darwinKernelVersionMin(11, 0, 0) { + return 0, ENOSYS + } + + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = writev(fd, iovecs) + writevRacedetect(iovecs, n) + return n, err +} + +func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) { + if !darwinKernelVersionMin(11, 0, 0) { + return 0, ENOSYS + } + + iovecs := make([]Iovec, 0, minIovec) + iovecs = appendBytes(iovecs, iovs) + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = pwritev(fd, iovecs, offset) + writevRacedetect(iovecs, n) + return n, err +} + +func appendBytes(vecs []Iovec, bs [][]byte) []Iovec { + for _, b := range bs { + var v Iovec + v.SetLen(len(b)) + if len(b) > 0 { + v.Base = &b[0] + } else { + v.Base = (*byte)(unsafe.Pointer(&_zero)) + } + vecs = append(vecs, v) + } + return vecs +} + +func writevRacedetect(iovecs []Iovec, n int) { + if !raceenabled { + return + } + for i := 0; n > 0 && i < len(iovecs); i++ { + m := int(iovecs[i].Len) + if m > n { + m = n + } + n -= m + if m > 0 { + raceReadRange(unsafe.Pointer(iovecs[i].Base), m) + } + } +} + +func readvRacedetect(iovecs []Iovec, n int, err error) { + if !raceenabled { + return + } + for i := 0; n > 0 && i < len(iovecs); i++ { + m := int(iovecs[i].Len) + if m > n { + m = n + } + n -= m + if m > 0 { + raceWriteRange(unsafe.Pointer(iovecs[i].Base), m) + } + } + if err == nil { + raceAcquire(unsafe.Pointer(&ioSync)) + } +} + +func darwinMajorMinPatch() (maj, min, patch int, err error) { + var un Utsname + err = Uname(&un) + if err != nil { + return + } + + var mmp [3]int + c := 0 +Loop: + for _, b := range un.Release[:] { + switch { + case b >= '0' && b <= '9': + mmp[c] = 10*mmp[c] + int(b-'0') + case b == '.': + c++ + if c > 2 { + return 0, 0, 0, ENOTSUP + } + case b == 0: + break Loop + default: + return 0, 0, 0, ENOTSUP + } + } + if c != 2 { + return 0, 0, 0, ENOTSUP + } + return mmp[0], mmp[1], mmp[2], nil +} + +func darwinKernelVersionMin(maj, min, patch int) bool { + actualMaj, actualMin, actualPatch, err := darwinMajorMinPatch() + if err != nil { + return false + } + return actualMaj > maj || actualMaj == maj && (actualMin > min || actualMin == min && actualPatch >= patch) +} + //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) @@ -705,3 +848,7 @@ func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocI //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) +//sys readv(fd int, iovecs []Iovec) (n int, err error) +//sys preadv(fd int, iovecs []Iovec, offset int64) (n int, err error) +//sys writev(fd int, iovecs []Iovec) (n int, err error) +//sys pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 230a94549..4958a6570 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -13,6 +13,7 @@ package unix import ( "encoding/binary" + "slices" "strconv" "syscall" "time" @@ -417,7 +418,7 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { return nil, 0, EINVAL } sa.raw.Family = AF_UNIX - for i := 0; i < n; i++ { + for i := range n { sa.raw.Path[i] = int8(name[i]) } // length is family (uint16), name, NUL. @@ -507,7 +508,7 @@ func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) { psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm)) psm[0] = byte(sa.PSM) psm[1] = byte(sa.PSM >> 8) - for i := 0; i < len(sa.Addr); i++ { + for i := range len(sa.Addr) { sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i] } cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid)) @@ -589,11 +590,11 @@ func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Family = AF_CAN sa.raw.Ifindex = int32(sa.Ifindex) rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) - for i := 0; i < 4; i++ { + for i := range 4 { sa.raw.Addr[i] = rx[i] } tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) - for i := 0; i < 4; i++ { + for i := range 4 { sa.raw.Addr[i+4] = tx[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil @@ -618,11 +619,11 @@ func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Family = AF_CAN sa.raw.Ifindex = int32(sa.Ifindex) n := (*[8]byte)(unsafe.Pointer(&sa.Name)) - for i := 0; i < 8; i++ { + for i := range 8 { sa.raw.Addr[i] = n[i] } p := (*[4]byte)(unsafe.Pointer(&sa.PGN)) - for i := 0; i < 4; i++ { + for i := range 4 { sa.raw.Addr[i+8] = p[i] } sa.raw.Addr[12] = sa.Addr @@ -911,7 +912,7 @@ func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) { // These are EBCDIC encoded by the kernel, but we still need to pad them // with blanks. Initializing with blanks allows the caller to feed in either // a padded or an unpadded string. - for i := 0; i < 8; i++ { + for i := range 8 { sa.raw.Nodeid[i] = ' ' sa.raw.User_id[i] = ' ' sa.raw.Name[i] = ' ' @@ -1148,7 +1149,7 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { var user [8]byte var name [8]byte - for i := 0; i < 8; i++ { + for i := range 8 { user[i] = byte(pp.User_id[i]) name[i] = byte(pp.Name[i]) } @@ -1173,11 +1174,11 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { Ifindex: int(pp.Ifindex), } name := (*[8]byte)(unsafe.Pointer(&sa.Name)) - for i := 0; i < 8; i++ { + for i := range 8 { name[i] = pp.Addr[i] } pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN)) - for i := 0; i < 4; i++ { + for i := range 4 { pgn[i] = pp.Addr[i+8] } addr := (*[1]byte)(unsafe.Pointer(&sa.Addr)) @@ -1188,11 +1189,11 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { Ifindex: int(pp.Ifindex), } rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) - for i := 0; i < 4; i++ { + for i := range 4 { rx[i] = pp.Addr[i] } tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) - for i := 0; i < 4; i++ { + for i := range 4 { tx[i] = pp.Addr[i+4] } return sa, nil @@ -2216,10 +2217,7 @@ func readvRacedetect(iovecs []Iovec, n int, err error) { return } for i := 0; n > 0 && i < len(iovecs); i++ { - m := int(iovecs[i].Len) - if m > n { - m = n - } + m := min(int(iovecs[i].Len), n) n -= m if m > 0 { raceWriteRange(unsafe.Pointer(iovecs[i].Base), m) @@ -2270,10 +2268,7 @@ func writevRacedetect(iovecs []Iovec, n int) { return } for i := 0; n > 0 && i < len(iovecs); i++ { - m := int(iovecs[i].Len) - if m > n { - m = n - } + m := min(int(iovecs[i].Len), n) n -= m if m > 0 { raceReadRange(unsafe.Pointer(iovecs[i].Base), m) @@ -2320,12 +2315,7 @@ func isGroupMember(gid int) bool { return false } - for _, g := range groups { - if g == gid { - return true - } - } - return false + return slices.Contains(groups, gid) } func isCapDacOverrideSet() bool { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 24b346e1a..813c05b66 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -2512,6 +2512,90 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readv(fd int, iovecs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_readv_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readv readv "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func preadv(fd int, iovecs []Iovec, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_preadv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_preadv_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_preadv preadv "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writev(fd int, iovecs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_writev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_writev_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_writev writev "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwritev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pwritev_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pwritev pwritev "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(libc_fstat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s index ebd213100..fda328582 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s @@ -738,6 +738,26 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_readv_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readv(SB) +GLOBL ·libc_readv_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readv_trampoline_addr(SB)/8, $libc_readv_trampoline<>(SB) + +TEXT libc_preadv_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_preadv(SB) +GLOBL ·libc_preadv_trampoline_addr(SB), RODATA, $8 +DATA ·libc_preadv_trampoline_addr(SB)/8, $libc_preadv_trampoline<>(SB) + +TEXT libc_writev_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_writev(SB) +GLOBL ·libc_writev_trampoline_addr(SB), RODATA, $8 +DATA ·libc_writev_trampoline_addr(SB)/8, $libc_writev_trampoline<>(SB) + +TEXT libc_pwritev_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pwritev(SB) +GLOBL ·libc_pwritev_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pwritev_trampoline_addr(SB)/8, $libc_pwritev_trampoline<>(SB) + TEXT libc_fstat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstat64(SB) GLOBL ·libc_fstat64_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index 824b9c2d5..e6f58f3c6 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -2512,6 +2512,90 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readv(fd int, iovecs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_readv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_readv_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readv readv "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func preadv(fd int, iovecs []Iovec, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_preadv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_preadv_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_preadv preadv "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writev(fd int, iovecs []Iovec) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall(libc_writev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_writev_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_writev writev "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(iovecs) > 0 { + _p0 = unsafe.Pointer(&iovecs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := syscall_syscall6(libc_pwritev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pwritev_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pwritev pwritev "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s index 4f178a229..7f8998b90 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s @@ -738,6 +738,26 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_readv_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readv(SB) +GLOBL ·libc_readv_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readv_trampoline_addr(SB)/8, $libc_readv_trampoline<>(SB) + +TEXT libc_preadv_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_preadv(SB) +GLOBL ·libc_preadv_trampoline_addr(SB), RODATA, $8 +DATA ·libc_preadv_trampoline_addr(SB)/8, $libc_preadv_trampoline<>(SB) + +TEXT libc_writev_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_writev(SB) +GLOBL ·libc_writev_trampoline_addr(SB), RODATA, $8 +DATA ·libc_writev_trampoline_addr(SB)/8, $libc_writev_trampoline<>(SB) + +TEXT libc_pwritev_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pwritev(SB) +GLOBL ·libc_pwritev_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pwritev_trampoline_addr(SB)/8, $libc_pwritev_trampoline<>(SB) + TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstat(SB) GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8 diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 9d138de5f..ad67df2fd 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -1074,6 +1074,7 @@ const ( IP_ADD_MEMBERSHIP = 0xc IP_DROP_MEMBERSHIP = 0xd IP_PKTINFO = 0x13 + IP_MTU_DISCOVER = 0x47 IPV6_V6ONLY = 0x1b IPV6_UNICAST_HOPS = 0x4 @@ -1083,6 +1084,7 @@ const ( IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_PKTINFO = 0x13 + IPV6_MTU_DISCOVER = 0x47 MSG_OOB = 0x1 MSG_PEEK = 0x2 @@ -1132,6 +1134,15 @@ const ( WSASYS_STATUS_LEN = 128 ) +// enum PMTUD_STATE from ws2ipdef.h +const ( + IP_PMTUDISC_NOT_SET = 0 + IP_PMTUDISC_DO = 1 + IP_PMTUDISC_DONT = 2 + IP_PMTUDISC_PROBE = 3 + IP_PMTUDISC_MAX = 4 +) + type WSABuf struct { Len uint32 Buf *byte @@ -1146,6 +1157,22 @@ type WSAMsg struct { Flags uint32 } +type WSACMSGHDR struct { + Len uintptr + Level int32 + Type int32 +} + +type IN_PKTINFO struct { + Addr [4]byte + Ifindex uint32 +} + +type IN6_PKTINFO struct { + Addr [16]byte + Ifindex uint32 +} + // Flags for WSASocket const ( WSA_FLAG_OVERLAPPED = 0x01 diff --git a/vendor/golang.org/x/term/terminal.go b/vendor/golang.org/x/term/terminal.go index f636667fb..14f89470a 100644 --- a/vendor/golang.org/x/term/terminal.go +++ b/vendor/golang.org/x/term/terminal.go @@ -44,6 +44,8 @@ type Terminal struct { // bytes, as an index into |line|). If it returns ok=false, the key // press is processed normally. Otherwise it returns a replacement line // and the new cursor position. + // + // This will be disabled during ReadPassword. AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool) // Escape contains a pointer to the escape codes for this terminal. @@ -692,6 +694,8 @@ func (t *Terminal) Write(buf []byte) (n int, err error) { // ReadPassword temporarily changes the prompt and reads a password, without // echo, from the terminal. +// +// The AutoCompleteCallback is disabled during this call. func (t *Terminal) ReadPassword(prompt string) (line string, err error) { t.lock.Lock() defer t.lock.Unlock() @@ -699,6 +703,11 @@ func (t *Terminal) ReadPassword(prompt string) (line string, err error) { oldPrompt := t.prompt t.prompt = []rune(prompt) t.echo = false + oldAutoCompleteCallback := t.AutoCompleteCallback + t.AutoCompleteCallback = nil + defer func() { + t.AutoCompleteCallback = oldAutoCompleteCallback + }() line, err = t.readLine() diff --git a/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go b/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go new file mode 100644 index 000000000..6e34df461 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go @@ -0,0 +1,654 @@ +// Copyright 2013 The Go 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 astutil + +// This file defines utilities for working with source positions. + +import ( + "fmt" + "go/ast" + "go/token" + "sort" +) + +// PathEnclosingInterval returns the node that encloses the source +// interval [start, end), and all its ancestors up to the AST root. +// +// The definition of "enclosing" used by this function considers +// additional whitespace abutting a node to be enclosed by it. +// In this example: +// +// z := x + y // add them +// <-A-> +// <----B-----> +// +// the ast.BinaryExpr(+) node is considered to enclose interval B +// even though its [Pos()..End()) is actually only interval A. +// This behaviour makes user interfaces more tolerant of imperfect +// input. +// +// This function treats tokens as nodes, though they are not included +// in the result. e.g. PathEnclosingInterval("+") returns the +// enclosing ast.BinaryExpr("x + y"). +// +// If start==end, the 1-char interval following start is used instead. +// +// The 'exact' result is true if the interval contains only path[0] +// and perhaps some adjacent whitespace. It is false if the interval +// overlaps multiple children of path[0], or if it contains only +// interior whitespace of path[0]. +// In this example: +// +// z := x + y // add them +// <--C--> <---E--> +// ^ +// D +// +// intervals C, D and E are inexact. C is contained by the +// z-assignment statement, because it spans three of its children (:=, +// x, +). So too is the 1-char interval D, because it contains only +// interior whitespace of the assignment. E is considered interior +// whitespace of the BlockStmt containing the assignment. +// +// The resulting path is never empty; it always contains at least the +// 'root' *ast.File. Ideally PathEnclosingInterval would reject +// intervals that lie wholly or partially outside the range of the +// file, but unfortunately ast.File records only the token.Pos of +// the 'package' keyword, but not of the start of the file itself. +func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Node, exact bool) { + // fmt.Printf("EnclosingInterval %d %d\n", start, end) // debugging + + // Precondition: node.[Pos..End) and adjoining whitespace contain [start, end). + var visit func(node ast.Node) bool + visit = func(node ast.Node) bool { + path = append(path, node) + + nodePos := node.Pos() + nodeEnd := node.End() + + // fmt.Printf("visit(%T, %d, %d)\n", node, nodePos, nodeEnd) // debugging + + // Intersect [start, end) with interval of node. + if start < nodePos { + start = nodePos + } + if end > nodeEnd { + end = nodeEnd + } + + // Find sole child that contains [start, end). + children := childrenOf(node) + l := len(children) + for i, child := range children { + // [childPos, childEnd) is unaugmented interval of child. + childPos := child.Pos() + childEnd := child.End() + + // [augPos, augEnd) is whitespace-augmented interval of child. + augPos := childPos + augEnd := childEnd + if i > 0 { + augPos = children[i-1].End() // start of preceding whitespace + } + if i < l-1 { + nextChildPos := children[i+1].Pos() + // Does [start, end) lie between child and next child? + if start >= augEnd && end <= nextChildPos { + return false // inexact match + } + augEnd = nextChildPos // end of following whitespace + } + + // fmt.Printf("\tchild %d: [%d..%d)\tcontains interval [%d..%d)?\n", + // i, augPos, augEnd, start, end) // debugging + + // Does augmented child strictly contain [start, end)? + if augPos <= start && end <= augEnd { + if is[tokenNode](child) { + return true + } + + // childrenOf elides the FuncType node beneath FuncDecl. + // Add it back here for TypeParams, Params, Results, + // all FieldLists). But we don't add it back for the "func" token + // even though it is is the tree at FuncDecl.Type.Func. + if decl, ok := node.(*ast.FuncDecl); ok { + if fields, ok := child.(*ast.FieldList); ok && fields != decl.Recv { + path = append(path, decl.Type) + } + } + + return visit(child) + } + + // Does [start, end) overlap multiple children? + // i.e. left-augmented child contains start + // but LR-augmented child does not contain end. + if start < childEnd && end > augEnd { + break + } + } + + // No single child contained [start, end), + // so node is the result. Is it exact? + + // (It's tempting to put this condition before the + // child loop, but it gives the wrong result in the + // case where a node (e.g. ExprStmt) and its sole + // child have equal intervals.) + if start == nodePos && end == nodeEnd { + return true // exact match + } + + return false // inexact: overlaps multiple children + } + + // Ensure [start,end) is nondecreasing. + if start > end { + start, end = end, start + } + + if start < root.End() && end > root.Pos() { + if start == end { + end = start + 1 // empty interval => interval of size 1 + } + exact = visit(root) + + // Reverse the path: + for i, l := 0, len(path); i < l/2; i++ { + path[i], path[l-1-i] = path[l-1-i], path[i] + } + } else { + // Selection lies within whitespace preceding the + // first (or following the last) declaration in the file. + // The result nonetheless always includes the ast.File. + path = append(path, root) + } + + return +} + +// tokenNode is a dummy implementation of ast.Node for a single token. +// They are used transiently by PathEnclosingInterval but never escape +// this package. +type tokenNode struct { + pos token.Pos + end token.Pos +} + +func (n tokenNode) Pos() token.Pos { + return n.pos +} + +func (n tokenNode) End() token.Pos { + return n.end +} + +func tok(pos token.Pos, len int) ast.Node { + return tokenNode{pos, pos + token.Pos(len)} +} + +// childrenOf returns the direct non-nil children of ast.Node n. +// It may include fake ast.Node implementations for bare tokens. +// it is not safe to call (e.g.) ast.Walk on such nodes. +func childrenOf(n ast.Node) []ast.Node { + var children []ast.Node + + // First add nodes for all true subtrees. + ast.Inspect(n, func(node ast.Node) bool { + if node == n { // push n + return true // recur + } + if node != nil { // push child + children = append(children, node) + } + return false // no recursion + }) + + // Then add fake Nodes for bare tokens. + switch n := n.(type) { + case *ast.ArrayType: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Elt.End(), len("]"))) + + case *ast.AssignStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) + + case *ast.BasicLit: + children = append(children, + tok(n.ValuePos, len(n.Value))) + + case *ast.BinaryExpr: + children = append(children, tok(n.OpPos, len(n.Op.String()))) + + case *ast.BlockStmt: + children = append(children, + tok(n.Lbrace, len("{")), + tok(n.Rbrace, len("}"))) + + case *ast.BranchStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) + + case *ast.CallExpr: + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + if n.Ellipsis != 0 { + children = append(children, tok(n.Ellipsis, len("..."))) + } + + case *ast.CaseClause: + if n.List == nil { + children = append(children, + tok(n.Case, len("default"))) + } else { + children = append(children, + tok(n.Case, len("case"))) + } + children = append(children, tok(n.Colon, len(":"))) + + case *ast.ChanType: + switch n.Dir { + case ast.RECV: + children = append(children, tok(n.Begin, len("<-chan"))) + case ast.SEND: + children = append(children, tok(n.Begin, len("chan<-"))) + case ast.RECV | ast.SEND: + children = append(children, tok(n.Begin, len("chan"))) + } + + case *ast.CommClause: + if n.Comm == nil { + children = append(children, + tok(n.Case, len("default"))) + } else { + children = append(children, + tok(n.Case, len("case"))) + } + children = append(children, tok(n.Colon, len(":"))) + + case *ast.Comment: + // nop + + case *ast.CommentGroup: + // nop + + case *ast.CompositeLit: + children = append(children, + tok(n.Lbrace, len("{")), + tok(n.Rbrace, len("{"))) + + case *ast.DeclStmt: + // nop + + case *ast.DeferStmt: + children = append(children, + tok(n.Defer, len("defer"))) + + case *ast.Ellipsis: + children = append(children, + tok(n.Ellipsis, len("..."))) + + case *ast.EmptyStmt: + // nop + + case *ast.ExprStmt: + // nop + + case *ast.Field: + // TODO(adonovan): Field.{Doc,Comment,Tag}? + + case *ast.FieldList: + children = append(children, + tok(n.Opening, len("(")), // or len("[") + tok(n.Closing, len(")"))) // or len("]") + + case *ast.File: + // TODO test: Doc + children = append(children, + tok(n.Package, len("package"))) + + case *ast.ForStmt: + children = append(children, + tok(n.For, len("for"))) + + case *ast.FuncDecl: + // TODO(adonovan): FuncDecl.Comment? + + // Uniquely, FuncDecl breaks the invariant that + // preorder traversal yields tokens in lexical order: + // in fact, FuncDecl.Recv precedes FuncDecl.Type.Func. + // + // As a workaround, we inline the case for FuncType + // here and order things correctly. + // We also need to insert the elided FuncType just + // before the 'visit' recursion. + // + children = nil // discard ast.Walk(FuncDecl) info subtrees + children = append(children, tok(n.Type.Func, len("func"))) + if n.Recv != nil { + children = append(children, n.Recv) + } + children = append(children, n.Name) + if tparams := n.Type.TypeParams; tparams != nil { + children = append(children, tparams) + } + if n.Type.Params != nil { + children = append(children, n.Type.Params) + } + if n.Type.Results != nil { + children = append(children, n.Type.Results) + } + if n.Body != nil { + children = append(children, n.Body) + } + + case *ast.FuncLit: + // nop + + case *ast.FuncType: + if n.Func != 0 { + children = append(children, + tok(n.Func, len("func"))) + } + + case *ast.GenDecl: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) + if n.Lparen != 0 { + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + } + + case *ast.GoStmt: + children = append(children, + tok(n.Go, len("go"))) + + case *ast.Ident: + children = append(children, + tok(n.NamePos, len(n.Name))) + + case *ast.IfStmt: + children = append(children, + tok(n.If, len("if"))) + + case *ast.ImportSpec: + // TODO(adonovan): ImportSpec.{Doc,EndPos}? + + case *ast.IncDecStmt: + children = append(children, + tok(n.TokPos, len(n.Tok.String()))) + + case *ast.IndexExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) + + case *ast.IndexListExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) + + case *ast.InterfaceType: + children = append(children, + tok(n.Interface, len("interface"))) + + case *ast.KeyValueExpr: + children = append(children, + tok(n.Colon, len(":"))) + + case *ast.LabeledStmt: + children = append(children, + tok(n.Colon, len(":"))) + + case *ast.MapType: + children = append(children, + tok(n.Map, len("map"))) + + case *ast.ParenExpr: + children = append(children, + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + + case *ast.RangeStmt: + children = append(children, + tok(n.For, len("for")), + tok(n.TokPos, len(n.Tok.String()))) + + case *ast.ReturnStmt: + children = append(children, + tok(n.Return, len("return"))) + + case *ast.SelectStmt: + children = append(children, + tok(n.Select, len("select"))) + + case *ast.SelectorExpr: + // nop + + case *ast.SendStmt: + children = append(children, + tok(n.Arrow, len("<-"))) + + case *ast.SliceExpr: + children = append(children, + tok(n.Lbrack, len("[")), + tok(n.Rbrack, len("]"))) + + case *ast.StarExpr: + children = append(children, tok(n.Star, len("*"))) + + case *ast.StructType: + children = append(children, tok(n.Struct, len("struct"))) + + case *ast.SwitchStmt: + children = append(children, tok(n.Switch, len("switch"))) + + case *ast.TypeAssertExpr: + children = append(children, + tok(n.Lparen-1, len(".")), + tok(n.Lparen, len("(")), + tok(n.Rparen, len(")"))) + + case *ast.TypeSpec: + // TODO(adonovan): TypeSpec.{Doc,Comment}? + + case *ast.TypeSwitchStmt: + children = append(children, tok(n.Switch, len("switch"))) + + case *ast.UnaryExpr: + children = append(children, tok(n.OpPos, len(n.Op.String()))) + + case *ast.ValueSpec: + // TODO(adonovan): ValueSpec.{Doc,Comment}? + + case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt: + // nop + } + + // TODO(adonovan): opt: merge the logic of ast.Inspect() into + // the switch above so we can make interleaved callbacks for + // both Nodes and Tokens in the right order and avoid the need + // to sort. + sort.Sort(byPos(children)) + + return children +} + +type byPos []ast.Node + +func (sl byPos) Len() int { + return len(sl) +} +func (sl byPos) Less(i, j int) bool { + return sl[i].Pos() < sl[j].Pos() +} +func (sl byPos) Swap(i, j int) { + sl[i], sl[j] = sl[j], sl[i] +} + +// NodeDescription returns a description of the concrete type of n suitable +// for a user interface. +// +// TODO(adonovan): in some cases (e.g. Field, FieldList, Ident, +// StarExpr) we could be much more specific given the path to the AST +// root. Perhaps we should do that. +func NodeDescription(n ast.Node) string { + switch n := n.(type) { + case *ast.ArrayType: + return "array type" + case *ast.AssignStmt: + return "assignment" + case *ast.BadDecl: + return "bad declaration" + case *ast.BadExpr: + return "bad expression" + case *ast.BadStmt: + return "bad statement" + case *ast.BasicLit: + return "basic literal" + case *ast.BinaryExpr: + return fmt.Sprintf("binary %s operation", n.Op) + case *ast.BlockStmt: + return "block" + case *ast.BranchStmt: + switch n.Tok { + case token.BREAK: + return "break statement" + case token.CONTINUE: + return "continue statement" + case token.GOTO: + return "goto statement" + case token.FALLTHROUGH: + return "fall-through statement" + } + case *ast.CallExpr: + if len(n.Args) == 1 && !n.Ellipsis.IsValid() { + return "function call (or conversion)" + } + return "function call" + case *ast.CaseClause: + return "case clause" + case *ast.ChanType: + return "channel type" + case *ast.CommClause: + return "communication clause" + case *ast.Comment: + return "comment" + case *ast.CommentGroup: + return "comment group" + case *ast.CompositeLit: + return "composite literal" + case *ast.DeclStmt: + return NodeDescription(n.Decl) + " statement" + case *ast.DeferStmt: + return "defer statement" + case *ast.Ellipsis: + return "ellipsis" + case *ast.EmptyStmt: + return "empty statement" + case *ast.ExprStmt: + return "expression statement" + case *ast.Field: + // Can be any of these: + // struct {x, y int} -- struct field(s) + // struct {T} -- anon struct field + // interface {I} -- interface embedding + // interface {f()} -- interface method + // func (A) func(B) C -- receiver, param(s), result(s) + return "field/method/parameter" + case *ast.FieldList: + return "field/method/parameter list" + case *ast.File: + return "source file" + case *ast.ForStmt: + return "for loop" + case *ast.FuncDecl: + return "function declaration" + case *ast.FuncLit: + return "function literal" + case *ast.FuncType: + return "function type" + case *ast.GenDecl: + switch n.Tok { + case token.IMPORT: + return "import declaration" + case token.CONST: + return "constant declaration" + case token.TYPE: + return "type declaration" + case token.VAR: + return "variable declaration" + } + case *ast.GoStmt: + return "go statement" + case *ast.Ident: + return "identifier" + case *ast.IfStmt: + return "if statement" + case *ast.ImportSpec: + return "import specification" + case *ast.IncDecStmt: + if n.Tok == token.INC { + return "increment statement" + } + return "decrement statement" + case *ast.IndexExpr: + return "index expression" + case *ast.IndexListExpr: + return "index list expression" + case *ast.InterfaceType: + return "interface type" + case *ast.KeyValueExpr: + return "key/value association" + case *ast.LabeledStmt: + return "statement label" + case *ast.MapType: + return "map type" + case *ast.Package: + return "package" + case *ast.ParenExpr: + return "parenthesized " + NodeDescription(n.X) + case *ast.RangeStmt: + return "range loop" + case *ast.ReturnStmt: + return "return statement" + case *ast.SelectStmt: + return "select statement" + case *ast.SelectorExpr: + return "selector" + case *ast.SendStmt: + return "channel send" + case *ast.SliceExpr: + return "slice expression" + case *ast.StarExpr: + return "*-operation" // load/store expr or pointer type + case *ast.StructType: + return "struct type" + case *ast.SwitchStmt: + return "switch statement" + case *ast.TypeAssertExpr: + return "type assertion" + case *ast.TypeSpec: + return "type specification" + case *ast.TypeSwitchStmt: + return "type switch" + case *ast.UnaryExpr: + return fmt.Sprintf("unary %s operation", n.Op) + case *ast.ValueSpec: + return "value specification" + + } + panic(fmt.Sprintf("unexpected node type: %T", n)) +} + +func is[T any](x any) bool { + _, ok := x.(T) + return ok +} diff --git a/vendor/golang.org/x/tools/go/ast/astutil/imports.go b/vendor/golang.org/x/tools/go/ast/astutil/imports.go new file mode 100644 index 000000000..5e5601aa4 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/astutil/imports.go @@ -0,0 +1,491 @@ +// Copyright 2013 The Go 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 astutil contains common utilities for working with the Go AST. +package astutil // import "golang.org/x/tools/go/ast/astutil" + +import ( + "fmt" + "go/ast" + "go/token" + "slices" + "strconv" + "strings" +) + +// AddImport adds the import path to the file f, if absent. +func AddImport(fset *token.FileSet, f *ast.File, path string) (added bool) { + return AddNamedImport(fset, f, "", path) +} + +// AddNamedImport adds the import with the given name and path to the file f, if absent. +// If name is not empty, it is used to rename the import. +// +// For example, calling +// +// AddNamedImport(fset, f, "pathpkg", "path") +// +// adds +// +// import pathpkg "path" +func AddNamedImport(fset *token.FileSet, f *ast.File, name, path string) (added bool) { + if imports(f, name, path) { + return false + } + + newImport := &ast.ImportSpec{ + Path: &ast.BasicLit{ + Kind: token.STRING, + Value: strconv.Quote(path), + }, + } + if name != "" { + newImport.Name = &ast.Ident{Name: name} + } + + // Find an import decl to add to. + // The goal is to find an existing import + // whose import path has the longest shared + // prefix with path. + var ( + bestMatch = -1 // length of longest shared prefix + lastImport = -1 // index in f.Decls of the file's final import decl + impDecl *ast.GenDecl // import decl containing the best match + impIndex = -1 // spec index in impDecl containing the best match + + isThirdPartyPath = isThirdParty(path) + ) + for i, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if ok && gen.Tok == token.IMPORT { + lastImport = i + // Do not add to import "C", to avoid disrupting the + // association with its doc comment, breaking cgo. + if declImports(gen, "C") { + continue + } + + // Match an empty import decl if that's all that is available. + if len(gen.Specs) == 0 && bestMatch == -1 { + impDecl = gen + } + + // Compute longest shared prefix with imports in this group and find best + // matched import spec. + // 1. Always prefer import spec with longest shared prefix. + // 2. While match length is 0, + // - for stdlib package: prefer first import spec. + // - for third party package: prefer first third party import spec. + // We cannot use last import spec as best match for third party package + // because grouped imports are usually placed last by goimports -local + // flag. + // See issue #19190. + seenAnyThirdParty := false + for j, spec := range gen.Specs { + impspec := spec.(*ast.ImportSpec) + p := importPath(impspec) + n := matchLen(p, path) + if n > bestMatch || (bestMatch == 0 && !seenAnyThirdParty && isThirdPartyPath) { + bestMatch = n + impDecl = gen + impIndex = j + } + seenAnyThirdParty = seenAnyThirdParty || isThirdParty(p) + } + } + } + + // If no import decl found, add one after the last import. + if impDecl == nil { + impDecl = &ast.GenDecl{ + Tok: token.IMPORT, + } + if lastImport >= 0 { + impDecl.TokPos = f.Decls[lastImport].End() + } else { + // There are no existing imports. + // Our new import, preceded by a blank line, goes after the package declaration + // and after the comment, if any, that starts on the same line as the + // package declaration. + impDecl.TokPos = f.Package + + file := fset.File(f.Package) + pkgLine := file.Line(f.Package) + for _, c := range f.Comments { + if file.Line(c.Pos()) > pkgLine { + break + } + // +2 for a blank line + impDecl.TokPos = c.End() + 2 + } + } + f.Decls = append(f.Decls, nil) + copy(f.Decls[lastImport+2:], f.Decls[lastImport+1:]) + f.Decls[lastImport+1] = impDecl + } + + // Insert new import at insertAt. + insertAt := 0 + if impIndex >= 0 { + // insert after the found import + insertAt = impIndex + 1 + } + impDecl.Specs = append(impDecl.Specs, nil) + copy(impDecl.Specs[insertAt+1:], impDecl.Specs[insertAt:]) + impDecl.Specs[insertAt] = newImport + pos := impDecl.Pos() + if insertAt > 0 { + // If there is a comment after an existing import, preserve the comment + // position by adding the new import after the comment. + if spec, ok := impDecl.Specs[insertAt-1].(*ast.ImportSpec); ok && spec.Comment != nil { + pos = spec.Comment.End() + } else { + // Assign same position as the previous import, + // so that the sorter sees it as being in the same block. + pos = impDecl.Specs[insertAt-1].Pos() + } + } + if newImport.Name != nil { + newImport.Name.NamePos = pos + } + newImport.Path.ValuePos = pos + newImport.EndPos = pos + + // Clean up parens. impDecl contains at least one spec. + if len(impDecl.Specs) == 1 { + // Remove unneeded parens. + impDecl.Lparen = token.NoPos + } else if !impDecl.Lparen.IsValid() { + // impDecl needs parens added. + impDecl.Lparen = impDecl.Specs[0].Pos() + } + + f.Imports = append(f.Imports, newImport) + + if len(f.Decls) <= 1 { + return true + } + + // Merge all the import declarations into the first one. + var first *ast.GenDecl + for i := 0; i < len(f.Decls); i++ { + decl := f.Decls[i] + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { + continue + } + if first == nil { + first = gen + continue // Don't touch the first one. + } + // We now know there is more than one package in this import + // declaration. Ensure that it ends up parenthesized. + first.Lparen = first.Pos() + // Move the imports of the other import declaration to the first one. + for _, spec := range gen.Specs { + spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() + first.Specs = append(first.Specs, spec) + } + f.Decls = slices.Delete(f.Decls, i, i+1) + i-- + } + + return true +} + +func isThirdParty(importPath string) bool { + // Third party package import path usually contains "." (".com", ".org", ...) + // This logic is taken from golang.org/x/tools/imports package. + return strings.Contains(importPath, ".") +} + +// DeleteImport deletes the import path from the file f, if present. +// If there are duplicate import declarations, all matching ones are deleted. +func DeleteImport(fset *token.FileSet, f *ast.File, path string) (deleted bool) { + return DeleteNamedImport(fset, f, "", path) +} + +// DeleteNamedImport deletes the import with the given name and path from the file f, if present. +// If there are duplicate import declarations, all matching ones are deleted. +func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (deleted bool) { + var delspecs []*ast.ImportSpec + var delcomments []*ast.CommentGroup + + // Find the import nodes that import path, if any. + for i := 0; i < len(f.Decls); i++ { + decl := f.Decls[i] + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT { + continue + } + for j := 0; j < len(gen.Specs); j++ { + spec := gen.Specs[j] + impspec := spec.(*ast.ImportSpec) + if importName(impspec) != name || importPath(impspec) != path { + continue + } + + // We found an import spec that imports path. + // Delete it. + delspecs = append(delspecs, impspec) + deleted = true + copy(gen.Specs[j:], gen.Specs[j+1:]) + gen.Specs = gen.Specs[:len(gen.Specs)-1] + + // If this was the last import spec in this decl, + // delete the decl, too. + if len(gen.Specs) == 0 { + copy(f.Decls[i:], f.Decls[i+1:]) + f.Decls = f.Decls[:len(f.Decls)-1] + i-- + break + } else if len(gen.Specs) == 1 { + if impspec.Doc != nil { + delcomments = append(delcomments, impspec.Doc) + } + if impspec.Comment != nil { + delcomments = append(delcomments, impspec.Comment) + } + for _, cg := range f.Comments { + // Found comment on the same line as the import spec. + if cg.End() < impspec.Pos() && fset.Position(cg.End()).Line == fset.Position(impspec.Pos()).Line { + delcomments = append(delcomments, cg) + break + } + } + + spec := gen.Specs[0].(*ast.ImportSpec) + + // Move the documentation right after the import decl. + if spec.Doc != nil { + for fset.Position(gen.TokPos).Line+1 < fset.Position(spec.Doc.Pos()).Line { + fset.File(gen.TokPos).MergeLine(fset.Position(gen.TokPos).Line) + } + } + for _, cg := range f.Comments { + if cg.End() < spec.Pos() && fset.Position(cg.End()).Line == fset.Position(spec.Pos()).Line { + for fset.Position(gen.TokPos).Line+1 < fset.Position(spec.Pos()).Line { + fset.File(gen.TokPos).MergeLine(fset.Position(gen.TokPos).Line) + } + break + } + } + } + if j > 0 { + lastImpspec := gen.Specs[j-1].(*ast.ImportSpec) + lastLine := fset.PositionFor(lastImpspec.Path.ValuePos, false).Line + line := fset.PositionFor(impspec.Path.ValuePos, false).Line + + // We deleted an entry but now there may be + // a blank line-sized hole where the import was. + if line-lastLine > 1 || !gen.Rparen.IsValid() { + // There was a blank line immediately preceding the deleted import, + // so there's no need to close the hole. The right parenthesis is + // invalid after AddImport to an import statement without parenthesis. + // Do nothing. + } else if line != fset.File(gen.Rparen).LineCount() { + // There was no blank line. Close the hole. + fset.File(gen.Rparen).MergeLine(line) + } + } + j-- + } + } + + // Delete imports from f.Imports. + for i := 0; i < len(f.Imports); i++ { + imp := f.Imports[i] + for j, del := range delspecs { + if imp == del { + copy(f.Imports[i:], f.Imports[i+1:]) + f.Imports = f.Imports[:len(f.Imports)-1] + copy(delspecs[j:], delspecs[j+1:]) + delspecs = delspecs[:len(delspecs)-1] + i-- + break + } + } + } + + // Delete comments from f.Comments. + for i := 0; i < len(f.Comments); i++ { + cg := f.Comments[i] + for j, del := range delcomments { + if cg == del { + copy(f.Comments[i:], f.Comments[i+1:]) + f.Comments = f.Comments[:len(f.Comments)-1] + copy(delcomments[j:], delcomments[j+1:]) + delcomments = delcomments[:len(delcomments)-1] + i-- + break + } + } + } + + if len(delspecs) > 0 { + panic(fmt.Sprintf("deleted specs from Decls but not Imports: %v", delspecs)) + } + + return +} + +// RewriteImport rewrites any import of path oldPath to path newPath. +func RewriteImport(fset *token.FileSet, f *ast.File, oldPath, newPath string) (rewrote bool) { + for _, imp := range f.Imports { + if importPath(imp) == oldPath { + rewrote = true + // record old End, because the default is to compute + // it using the length of imp.Path.Value. + imp.EndPos = imp.End() + imp.Path.Value = strconv.Quote(newPath) + } + } + return +} + +// UsesImport reports whether a given import is used. +// The provided File must have been parsed with syntactic object resolution +// (not using go/parser.SkipObjectResolution). +func UsesImport(f *ast.File, path string) (used bool) { + if f.Scope == nil { + panic("file f was not parsed with syntactic object resolution") + } + spec := importSpec(f, path) + if spec == nil { + return + } + + name := spec.Name.String() + switch name { + case "": + // If the package name is not explicitly specified, + // make an educated guess. This is not guaranteed to be correct. + lastSlash := strings.LastIndex(path, "/") + if lastSlash == -1 { + name = path + } else { + name = path[lastSlash+1:] + } + case "_", ".": + // Not sure if this import is used - err on the side of caution. + return true + } + + ast.Walk(visitFn(func(n ast.Node) { + sel, ok := n.(*ast.SelectorExpr) + if ok && isTopName(sel.X, name) { + used = true + } + }), f) + + return +} + +type visitFn func(node ast.Node) + +func (fn visitFn) Visit(node ast.Node) ast.Visitor { + fn(node) + return fn +} + +// imports reports whether f has an import with the specified name and path. +func imports(f *ast.File, name, path string) bool { + for _, s := range f.Imports { + if importName(s) == name && importPath(s) == path { + return true + } + } + return false +} + +// importSpec returns the import spec if f imports path, +// or nil otherwise. +func importSpec(f *ast.File, path string) *ast.ImportSpec { + for _, s := range f.Imports { + if importPath(s) == path { + return s + } + } + return nil +} + +// importName returns the name of s, +// or "" if the import is not named. +func importName(s *ast.ImportSpec) string { + if s.Name == nil { + return "" + } + return s.Name.Name +} + +// importPath returns the unquoted import path of s, +// or "" if the path is not properly quoted. +func importPath(s *ast.ImportSpec) string { + t, err := strconv.Unquote(s.Path.Value) + if err != nil { + return "" + } + return t +} + +// declImports reports whether gen contains an import of path. +func declImports(gen *ast.GenDecl, path string) bool { + if gen.Tok != token.IMPORT { + return false + } + for _, spec := range gen.Specs { + impspec := spec.(*ast.ImportSpec) + if importPath(impspec) == path { + return true + } + } + return false +} + +// matchLen returns the length of the longest path segment prefix shared by x and y. +func matchLen(x, y string) int { + n := 0 + for i := 0; i < len(x) && i < len(y) && x[i] == y[i]; i++ { + if x[i] == '/' { + n++ + } + } + return n +} + +// isTopName returns true if n is a top-level unresolved identifier with the given name. +func isTopName(n ast.Expr, name string) bool { + id, ok := n.(*ast.Ident) + return ok && id.Name == name && id.Obj == nil +} + +// Imports returns the file imports grouped by paragraph. +func Imports(fset *token.FileSet, f *ast.File) [][]*ast.ImportSpec { + var groups [][]*ast.ImportSpec + + for _, decl := range f.Decls { + genDecl, ok := decl.(*ast.GenDecl) + if !ok || genDecl.Tok != token.IMPORT { + break + } + + group := []*ast.ImportSpec{} + + var lastLine int + for _, spec := range genDecl.Specs { + importSpec := spec.(*ast.ImportSpec) + pos := importSpec.Path.ValuePos + line := fset.Position(pos).Line + if lastLine > 0 && pos > 0 && line-lastLine > 1 { + groups = append(groups, group) + group = []*ast.ImportSpec{} + } + group = append(group, importSpec) + lastLine = line + } + groups = append(groups, group) + } + + return groups +} diff --git a/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go b/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go new file mode 100644 index 000000000..5c8dbbb7a --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go @@ -0,0 +1,486 @@ +// Copyright 2017 The Go 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 astutil + +import ( + "fmt" + "go/ast" + "reflect" + "sort" +) + +// An ApplyFunc is invoked by Apply for each node n, even if n is nil, +// before and/or after the node's children, using a Cursor describing +// the current node and providing operations on it. +// +// The return value of ApplyFunc controls the syntax tree traversal. +// See Apply for details. +type ApplyFunc func(*Cursor) bool + +// Apply traverses a syntax tree recursively, starting with root, +// and calling pre and post for each node as described below. +// Apply returns the syntax tree, possibly modified. +// +// If pre is not nil, it is called for each node before the node's +// children are traversed (pre-order). If pre returns false, no +// children are traversed, and post is not called for that node. +// +// If post is not nil, and a prior call of pre didn't return false, +// post is called for each node after its children are traversed +// (post-order). If post returns false, traversal is terminated and +// Apply returns immediately. +// +// Only fields that refer to AST nodes are considered children; +// i.e., token.Pos, Scopes, Objects, and fields of basic types +// (strings, etc.) are ignored. +// +// Children are traversed in the order in which they appear in the +// respective node's struct definition. A package's files are +// traversed in the filenames' alphabetical order. +func Apply(root ast.Node, pre, post ApplyFunc) (result ast.Node) { + parent := &struct{ ast.Node }{root} + defer func() { + if r := recover(); r != nil && r != abort { + panic(r) + } + result = parent.Node + }() + a := &application{pre: pre, post: post} + a.apply(parent, "Node", nil, root) + return +} + +var abort = new(int) // singleton, to signal termination of Apply + +// A Cursor describes a node encountered during Apply. +// Information about the node and its parent is available +// from the Node, Parent, Name, and Index methods. +// +// If p is a variable of type and value of the current parent node +// c.Parent(), and f is the field identifier with name c.Name(), +// the following invariants hold: +// +// p.f == c.Node() if c.Index() < 0 +// p.f[c.Index()] == c.Node() if c.Index() >= 0 +// +// The methods Replace, Delete, InsertBefore, and InsertAfter +// can be used to change the AST without disrupting Apply. +type Cursor struct { + parent ast.Node + name string + iter *iterator // valid if non-nil + node ast.Node +} + +// Node returns the current Node. +func (c *Cursor) Node() ast.Node { return c.node } + +// Parent returns the parent of the current Node. +func (c *Cursor) Parent() ast.Node { return c.parent } + +// Name returns the name of the parent Node field that contains the current Node. +// If the parent is a *ast.Package and the current Node is a *ast.File, Name returns +// the filename for the current Node. +func (c *Cursor) Name() string { return c.name } + +// Index reports the index >= 0 of the current Node in the slice of Nodes that +// contains it, or a value < 0 if the current Node is not part of a slice. +// The index of the current node changes if InsertBefore is called while +// processing the current node. +func (c *Cursor) Index() int { + if c.iter != nil { + return c.iter.index + } + return -1 +} + +// field returns the current node's parent field value. +func (c *Cursor) field() reflect.Value { + return reflect.Indirect(reflect.ValueOf(c.parent)).FieldByName(c.name) +} + +// Replace replaces the current Node with n. +// The replacement node is not walked by Apply. +func (c *Cursor) Replace(n ast.Node) { + if _, ok := c.node.(*ast.File); ok { + file, ok := n.(*ast.File) + if !ok { + panic("attempt to replace *ast.File with non-*ast.File") + } + c.parent.(*ast.Package).Files[c.name] = file + return + } + + v := c.field() + if i := c.Index(); i >= 0 { + v = v.Index(i) + } + v.Set(reflect.ValueOf(n)) +} + +// Delete deletes the current Node from its containing slice. +// If the current Node is not part of a slice, Delete panics. +// As a special case, if the current node is a package file, +// Delete removes it from the package's Files map. +func (c *Cursor) Delete() { + if _, ok := c.node.(*ast.File); ok { + delete(c.parent.(*ast.Package).Files, c.name) + return + } + + i := c.Index() + if i < 0 { + panic("Delete node not contained in slice") + } + v := c.field() + l := v.Len() + reflect.Copy(v.Slice(i, l), v.Slice(i+1, l)) + v.Index(l - 1).Set(reflect.Zero(v.Type().Elem())) + v.SetLen(l - 1) + c.iter.step-- +} + +// InsertAfter inserts n after the current Node in its containing slice. +// If the current Node is not part of a slice, InsertAfter panics. +// Apply does not walk n. +func (c *Cursor) InsertAfter(n ast.Node) { + i := c.Index() + if i < 0 { + panic("InsertAfter node not contained in slice") + } + v := c.field() + v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) + l := v.Len() + reflect.Copy(v.Slice(i+2, l), v.Slice(i+1, l)) + v.Index(i + 1).Set(reflect.ValueOf(n)) + c.iter.step++ +} + +// InsertBefore inserts n before the current Node in its containing slice. +// If the current Node is not part of a slice, InsertBefore panics. +// Apply will not walk n. +func (c *Cursor) InsertBefore(n ast.Node) { + i := c.Index() + if i < 0 { + panic("InsertBefore node not contained in slice") + } + v := c.field() + v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) + l := v.Len() + reflect.Copy(v.Slice(i+1, l), v.Slice(i, l)) + v.Index(i).Set(reflect.ValueOf(n)) + c.iter.index++ +} + +// application carries all the shared data so we can pass it around cheaply. +type application struct { + pre, post ApplyFunc + cursor Cursor + iter iterator +} + +func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast.Node) { + // convert typed nil into untyped nil + if v := reflect.ValueOf(n); v.Kind() == reflect.Pointer && v.IsNil() { + n = nil + } + + // avoid heap-allocating a new cursor for each apply call; reuse a.cursor instead + saved := a.cursor + a.cursor.parent = parent + a.cursor.name = name + a.cursor.iter = iter + a.cursor.node = n + + if a.pre != nil && !a.pre(&a.cursor) { + a.cursor = saved + return + } + + // walk children + // (the order of the cases matches the order of the corresponding node types in go/ast) + switch n := n.(type) { + case nil: + // nothing to do + + // Comments and fields + case *ast.Comment: + // nothing to do + + case *ast.CommentGroup: + if n != nil { + a.applyList(n, "List") + } + + case *ast.Field: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Names") + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Tag", nil, n.Tag) + a.apply(n, "Comment", nil, n.Comment) + + case *ast.FieldList: + a.applyList(n, "List") + + // Expressions + case *ast.BadExpr, *ast.Ident, *ast.BasicLit: + // nothing to do + + case *ast.Ellipsis: + a.apply(n, "Elt", nil, n.Elt) + + case *ast.FuncLit: + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Body", nil, n.Body) + + case *ast.CompositeLit: + a.apply(n, "Type", nil, n.Type) + a.applyList(n, "Elts") + + case *ast.ParenExpr: + a.apply(n, "X", nil, n.X) + + case *ast.SelectorExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Sel", nil, n.Sel) + + case *ast.IndexExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Index", nil, n.Index) + + case *ast.IndexListExpr: + a.apply(n, "X", nil, n.X) + a.applyList(n, "Indices") + + case *ast.SliceExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Low", nil, n.Low) + a.apply(n, "High", nil, n.High) + a.apply(n, "Max", nil, n.Max) + + case *ast.TypeAssertExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Type", nil, n.Type) + + case *ast.CallExpr: + a.apply(n, "Fun", nil, n.Fun) + a.applyList(n, "Args") + + case *ast.StarExpr: + a.apply(n, "X", nil, n.X) + + case *ast.UnaryExpr: + a.apply(n, "X", nil, n.X) + + case *ast.BinaryExpr: + a.apply(n, "X", nil, n.X) + a.apply(n, "Y", nil, n.Y) + + case *ast.KeyValueExpr: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) + + // Types + case *ast.ArrayType: + a.apply(n, "Len", nil, n.Len) + a.apply(n, "Elt", nil, n.Elt) + + case *ast.StructType: + a.apply(n, "Fields", nil, n.Fields) + + case *ast.FuncType: + if tparams := n.TypeParams; tparams != nil { + a.apply(n, "TypeParams", nil, tparams) + } + a.apply(n, "Params", nil, n.Params) + a.apply(n, "Results", nil, n.Results) + + case *ast.InterfaceType: + a.apply(n, "Methods", nil, n.Methods) + + case *ast.MapType: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) + + case *ast.ChanType: + a.apply(n, "Value", nil, n.Value) + + // Statements + case *ast.BadStmt: + // nothing to do + + case *ast.DeclStmt: + a.apply(n, "Decl", nil, n.Decl) + + case *ast.EmptyStmt: + // nothing to do + + case *ast.LabeledStmt: + a.apply(n, "Label", nil, n.Label) + a.apply(n, "Stmt", nil, n.Stmt) + + case *ast.ExprStmt: + a.apply(n, "X", nil, n.X) + + case *ast.SendStmt: + a.apply(n, "Chan", nil, n.Chan) + a.apply(n, "Value", nil, n.Value) + + case *ast.IncDecStmt: + a.apply(n, "X", nil, n.X) + + case *ast.AssignStmt: + a.applyList(n, "Lhs") + a.applyList(n, "Rhs") + + case *ast.GoStmt: + a.apply(n, "Call", nil, n.Call) + + case *ast.DeferStmt: + a.apply(n, "Call", nil, n.Call) + + case *ast.ReturnStmt: + a.applyList(n, "Results") + + case *ast.BranchStmt: + a.apply(n, "Label", nil, n.Label) + + case *ast.BlockStmt: + a.applyList(n, "List") + + case *ast.IfStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Cond", nil, n.Cond) + a.apply(n, "Body", nil, n.Body) + a.apply(n, "Else", nil, n.Else) + + case *ast.CaseClause: + a.applyList(n, "List") + a.applyList(n, "Body") + + case *ast.SwitchStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Tag", nil, n.Tag) + a.apply(n, "Body", nil, n.Body) + + case *ast.TypeSwitchStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Assign", nil, n.Assign) + a.apply(n, "Body", nil, n.Body) + + case *ast.CommClause: + a.apply(n, "Comm", nil, n.Comm) + a.applyList(n, "Body") + + case *ast.SelectStmt: + a.apply(n, "Body", nil, n.Body) + + case *ast.ForStmt: + a.apply(n, "Init", nil, n.Init) + a.apply(n, "Cond", nil, n.Cond) + a.apply(n, "Post", nil, n.Post) + a.apply(n, "Body", nil, n.Body) + + case *ast.RangeStmt: + a.apply(n, "Key", nil, n.Key) + a.apply(n, "Value", nil, n.Value) + a.apply(n, "X", nil, n.X) + a.apply(n, "Body", nil, n.Body) + + // Declarations + case *ast.ImportSpec: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + a.apply(n, "Path", nil, n.Path) + a.apply(n, "Comment", nil, n.Comment) + + case *ast.ValueSpec: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Names") + a.apply(n, "Type", nil, n.Type) + a.applyList(n, "Values") + a.apply(n, "Comment", nil, n.Comment) + + case *ast.TypeSpec: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + if tparams := n.TypeParams; tparams != nil { + a.apply(n, "TypeParams", nil, tparams) + } + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Comment", nil, n.Comment) + + case *ast.BadDecl: + // nothing to do + + case *ast.GenDecl: + a.apply(n, "Doc", nil, n.Doc) + a.applyList(n, "Specs") + + case *ast.FuncDecl: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Recv", nil, n.Recv) + a.apply(n, "Name", nil, n.Name) + a.apply(n, "Type", nil, n.Type) + a.apply(n, "Body", nil, n.Body) + + // Files and packages + case *ast.File: + a.apply(n, "Doc", nil, n.Doc) + a.apply(n, "Name", nil, n.Name) + a.applyList(n, "Decls") + // Don't walk n.Comments; they have either been walked already if + // they are Doc comments, or they can be easily walked explicitly. + + case *ast.Package: + // collect and sort names for reproducible behavior + var names []string + for name := range n.Files { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + a.apply(n, name, nil, n.Files[name]) + } + + default: + panic(fmt.Sprintf("Apply: unexpected node type %T", n)) + } + + if a.post != nil && !a.post(&a.cursor) { + panic(abort) + } + + a.cursor = saved +} + +// An iterator controls iteration over a slice of nodes. +type iterator struct { + index, step int +} + +func (a *application) applyList(parent ast.Node, name string) { + // avoid heap-allocating a new iterator for each applyList call; reuse a.iter instead + saved := a.iter + a.iter.index = 0 + for { + // must reload parent.name each time, since cursor modifications might change it + v := reflect.Indirect(reflect.ValueOf(parent)).FieldByName(name) + if a.iter.index >= v.Len() { + break + } + + // element x may be nil in a bad AST - be cautious + var x ast.Node + if e := v.Index(a.iter.index); e.IsValid() { + x = e.Interface().(ast.Node) + } + + a.iter.step = 1 + a.apply(parent, name, &a.iter, x) + a.iter.index += a.iter.step + } + a.iter = saved +} diff --git a/vendor/golang.org/x/tools/go/ast/astutil/util.go b/vendor/golang.org/x/tools/go/ast/astutil/util.go new file mode 100644 index 000000000..c820b2084 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/astutil/util.go @@ -0,0 +1,13 @@ +// Copyright 2015 The Go 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 astutil + +import "go/ast" + +// Unparen returns e with any enclosing parentheses stripped. +// Deprecated: use [ast.Unparen]. +// +//go:fix inline +func Unparen(e ast.Expr) ast.Expr { return ast.Unparen(e) } diff --git a/vendor/golang.org/x/tools/go/ast/inspector/inspector.go b/vendor/golang.org/x/tools/go/ast/inspector/inspector.go index 0e0ba4c03..1da4a361f 100644 --- a/vendor/golang.org/x/tools/go/ast/inspector/inspector.go +++ b/vendor/golang.org/x/tools/go/ast/inspector/inspector.go @@ -10,6 +10,7 @@ // builds a list of push/pop events and their node type. Subsequent // method calls that request a traversal scan this list, rather than walk // the AST, and perform type filtering using efficient bit sets. +// This representation is sometimes called a "balanced parenthesis tree." // // Experiments suggest the inspector's traversals are about 2.5x faster // than ast.Inspect, but it may take around 5 traversals for this @@ -36,6 +37,9 @@ package inspector import ( "go/ast" + _ "unsafe" + + "golang.org/x/tools/internal/astutil/edge" ) // An Inspector provides methods for inspecting @@ -44,6 +48,25 @@ type Inspector struct { events []event } +//go:linkname events +func events(in *Inspector) []event { return in.events } + +//go:linkname packEdgeKindAndIndex +func packEdgeKindAndIndex(ek edge.Kind, index int) int32 { + return int32(uint32(index+1)<<7 | uint32(ek)) +} + +// unpackEdgeKindAndIndex unpacks the edge kind and edge index (within +// an []ast.Node slice) from the parent field of a pop event. +// +//go:linkname unpackEdgeKindAndIndex +func unpackEdgeKindAndIndex(x int32) (edge.Kind, int) { + // The "parent" field of a pop node holds the + // edge Kind in the lower 7 bits and the index+1 + // in the upper 25. + return edge.Kind(x & 0x7f), int(x>>7) - 1 +} + // New returns an Inspector for the specified syntax trees. func New(files []*ast.File) *Inspector { return &Inspector{traverse(files)} @@ -52,9 +75,10 @@ func New(files []*ast.File) *Inspector { // An event represents a push or a pop // of an ast.Node during a traversal. type event struct { - node ast.Node - typ uint64 // typeOf(node) on push event, or union of typ strictly between push and pop events on pop events - index int // index of corresponding push or pop event + node ast.Node + typ uint64 // typeOf(node) on push event, or union of typ strictly between push and pop events on pop events + index int32 // index of corresponding push or pop event + parent int32 // index of parent's push node (push nodes only), or packed edge kind/index (pop nodes only) } // TODO: Experiment with storing only the second word of event.node (unsafe.Pointer). @@ -83,7 +107,7 @@ func (in *Inspector) Preorder(types []ast.Node, f func(ast.Node)) { // }) mask := maskOf(types) - for i := 0; i < len(in.events); { + for i := int32(0); i < int32(len(in.events)); { ev := in.events[i] if ev.index > i { // push @@ -113,7 +137,7 @@ func (in *Inspector) Preorder(types []ast.Node, f func(ast.Node)) { // matches an element of the types slice. func (in *Inspector) Nodes(types []ast.Node, f func(n ast.Node, push bool) (proceed bool)) { mask := maskOf(types) - for i := 0; i < len(in.events); { + for i := int32(0); i < int32(len(in.events)); { ev := in.events[i] if ev.index > i { // push @@ -147,7 +171,7 @@ func (in *Inspector) Nodes(types []ast.Node, f func(n ast.Node, push bool) (proc func (in *Inspector) WithStack(types []ast.Node, f func(n ast.Node, push bool, stack []ast.Node) (proceed bool)) { mask := maskOf(types) var stack []ast.Node - for i := 0; i < len(in.events); { + for i := int32(0); i < int32(len(in.events)); { ev := in.events[i] if ev.index > i { // push @@ -180,50 +204,83 @@ func (in *Inspector) WithStack(types []ast.Node, f func(n ast.Node, push bool, s // traverse builds the table of events representing a traversal. func traverse(files []*ast.File) []event { // Preallocate approximate number of events - // based on source file extent. + // based on source file extent of the declarations. + // (We use End-Pos not FileStart-FileEnd to neglect + // the effect of long doc comments.) // This makes traverse faster by 4x (!). var extent int for _, f := range files { extent += int(f.End() - f.Pos()) } // This estimate is based on the net/http package. - capacity := extent * 33 / 100 - if capacity > 1e6 { - capacity = 1e6 // impose some reasonable maximum + capacity := min(extent*33/100, 1e6) // impose some reasonable maximum (1M) + + v := &visitor{ + events: make([]event, 0, capacity), + stack: []item{{index: -1}}, // include an extra event so file nodes have a parent + } + for _, file := range files { + walk(v, edge.Invalid, -1, file) } - events := make([]event, 0, capacity) + return v.events +} - var stack []event - stack = append(stack, event{}) // include an extra event so file nodes have a parent - for _, f := range files { - ast.Inspect(f, func(n ast.Node) bool { - if n != nil { - // push - ev := event{ - node: n, - typ: 0, // temporarily used to accumulate type bits of subtree - index: len(events), // push event temporarily holds own index - } - stack = append(stack, ev) - events = append(events, ev) - } else { - // pop - top := len(stack) - 1 - ev := stack[top] - typ := typeOf(ev.node) - push := ev.index - parent := top - 1 - - events[push].typ = typ // set type of push - stack[parent].typ |= typ | ev.typ // parent's typ contains push and pop's typs. - events[push].index = len(events) // make push refer to pop - - stack = stack[:top] - events = append(events, ev) - } - return true - }) +type visitor struct { + events []event + stack []item +} + +type item struct { + index int32 // index of current node's push event + parentIndex int32 // index of parent node's push event + typAccum uint64 // accumulated type bits of current node's descendents + edgeKindAndIndex int32 // edge.Kind and index, bit packed +} + +func (v *visitor) push(ek edge.Kind, eindex int, node ast.Node) { + var ( + index = int32(len(v.events)) + parentIndex = v.stack[len(v.stack)-1].index + ) + v.events = append(v.events, event{ + node: node, + parent: parentIndex, + typ: typeOf(node), + index: 0, // (pop index is set later by visitor.pop) + }) + v.stack = append(v.stack, item{ + index: index, + parentIndex: parentIndex, + edgeKindAndIndex: packEdgeKindAndIndex(ek, eindex), + }) + + // 2B nodes ought to be enough for anyone! + if int32(len(v.events)) < 0 { + panic("event index exceeded int32") } - return events + // 32M elements in an []ast.Node ought to be enough for anyone! + if ek2, eindex2 := unpackEdgeKindAndIndex(packEdgeKindAndIndex(ek, eindex)); ek2 != ek || eindex2 != eindex { + panic("Node slice index exceeded uint25") + } +} + +func (v *visitor) pop(node ast.Node) { + top := len(v.stack) - 1 + current := v.stack[top] + + push := &v.events[current.index] + parent := &v.stack[top-1] + + push.index = int32(len(v.events)) // make push event refer to pop + parent.typAccum |= current.typAccum | push.typ // accumulate type bits into parent + + v.stack = v.stack[:top] + + v.events = append(v.events, event{ + node: node, + typ: current.typAccum, + index: current.index, + parent: current.edgeKindAndIndex, // see [unpackEdgeKindAndIndex] + }) } diff --git a/vendor/golang.org/x/tools/go/ast/inspector/iter.go b/vendor/golang.org/x/tools/go/ast/inspector/iter.go index b7e959114..c576dc70a 100644 --- a/vendor/golang.org/x/tools/go/ast/inspector/iter.go +++ b/vendor/golang.org/x/tools/go/ast/inspector/iter.go @@ -26,7 +26,7 @@ func (in *Inspector) PreorderSeq(types ...ast.Node) iter.Seq[ast.Node] { return func(yield func(ast.Node) bool) { mask := maskOf(types) - for i := 0; i < len(in.events); { + for i := int32(0); i < int32(len(in.events)); { ev := in.events[i] if ev.index > i { // push @@ -63,7 +63,7 @@ func All[N interface { mask := typeOf((N)(nil)) return func(yield func(N) bool) { - for i := 0; i < len(in.events); { + for i := int32(0); i < int32(len(in.events)); { ev := in.events[i] if ev.index > i { // push diff --git a/vendor/golang.org/x/tools/go/ast/inspector/typeof.go b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go index 2a872f89d..977844845 100644 --- a/vendor/golang.org/x/tools/go/ast/inspector/typeof.go +++ b/vendor/golang.org/x/tools/go/ast/inspector/typeof.go @@ -12,6 +12,8 @@ package inspector import ( "go/ast" "math" + + _ "unsafe" ) const ( @@ -215,8 +217,9 @@ func typeOf(n ast.Node) uint64 { return 0 } +//go:linkname maskOf func maskOf(nodes []ast.Node) uint64 { - if nodes == nil { + if len(nodes) == 0 { return math.MaxUint64 // match all node types } var mask uint64 diff --git a/vendor/golang.org/x/tools/go/ast/inspector/walk.go b/vendor/golang.org/x/tools/go/ast/inspector/walk.go new file mode 100644 index 000000000..5a42174a0 --- /dev/null +++ b/vendor/golang.org/x/tools/go/ast/inspector/walk.go @@ -0,0 +1,341 @@ +// Copyright 2025 The Go 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 inspector + +// This file is a fork of ast.Inspect to reduce unnecessary dynamic +// calls and to gather edge information. +// +// Consistency with the original is ensured by TestInspectAllNodes. + +import ( + "fmt" + "go/ast" + + "golang.org/x/tools/internal/astutil/edge" +) + +func walkList[N ast.Node](v *visitor, ek edge.Kind, list []N) { + for i, node := range list { + walk(v, ek, i, node) + } +} + +func walk(v *visitor, ek edge.Kind, index int, node ast.Node) { + v.push(ek, index, node) + + // walk children + // (the order of the cases matches the order + // of the corresponding node types in ast.go) + switch n := node.(type) { + // Comments and fields + case *ast.Comment: + // nothing to do + + case *ast.CommentGroup: + walkList(v, edge.CommentGroup_List, n.List) + + case *ast.Field: + if n.Doc != nil { + walk(v, edge.Field_Doc, -1, n.Doc) + } + walkList(v, edge.Field_Names, n.Names) + if n.Type != nil { + walk(v, edge.Field_Type, -1, n.Type) + } + if n.Tag != nil { + walk(v, edge.Field_Tag, -1, n.Tag) + } + if n.Comment != nil { + walk(v, edge.Field_Comment, -1, n.Comment) + } + + case *ast.FieldList: + walkList(v, edge.FieldList_List, n.List) + + // Expressions + case *ast.BadExpr, *ast.Ident, *ast.BasicLit: + // nothing to do + + case *ast.Ellipsis: + if n.Elt != nil { + walk(v, edge.Ellipsis_Elt, -1, n.Elt) + } + + case *ast.FuncLit: + walk(v, edge.FuncLit_Type, -1, n.Type) + walk(v, edge.FuncLit_Body, -1, n.Body) + + case *ast.CompositeLit: + if n.Type != nil { + walk(v, edge.CompositeLit_Type, -1, n.Type) + } + walkList(v, edge.CompositeLit_Elts, n.Elts) + + case *ast.ParenExpr: + walk(v, edge.ParenExpr_X, -1, n.X) + + case *ast.SelectorExpr: + walk(v, edge.SelectorExpr_X, -1, n.X) + walk(v, edge.SelectorExpr_Sel, -1, n.Sel) + + case *ast.IndexExpr: + walk(v, edge.IndexExpr_X, -1, n.X) + walk(v, edge.IndexExpr_Index, -1, n.Index) + + case *ast.IndexListExpr: + walk(v, edge.IndexListExpr_X, -1, n.X) + walkList(v, edge.IndexListExpr_Indices, n.Indices) + + case *ast.SliceExpr: + walk(v, edge.SliceExpr_X, -1, n.X) + if n.Low != nil { + walk(v, edge.SliceExpr_Low, -1, n.Low) + } + if n.High != nil { + walk(v, edge.SliceExpr_High, -1, n.High) + } + if n.Max != nil { + walk(v, edge.SliceExpr_Max, -1, n.Max) + } + + case *ast.TypeAssertExpr: + walk(v, edge.TypeAssertExpr_X, -1, n.X) + if n.Type != nil { + walk(v, edge.TypeAssertExpr_Type, -1, n.Type) + } + + case *ast.CallExpr: + walk(v, edge.CallExpr_Fun, -1, n.Fun) + walkList(v, edge.CallExpr_Args, n.Args) + + case *ast.StarExpr: + walk(v, edge.StarExpr_X, -1, n.X) + + case *ast.UnaryExpr: + walk(v, edge.UnaryExpr_X, -1, n.X) + + case *ast.BinaryExpr: + walk(v, edge.BinaryExpr_X, -1, n.X) + walk(v, edge.BinaryExpr_Y, -1, n.Y) + + case *ast.KeyValueExpr: + walk(v, edge.KeyValueExpr_Key, -1, n.Key) + walk(v, edge.KeyValueExpr_Value, -1, n.Value) + + // Types + case *ast.ArrayType: + if n.Len != nil { + walk(v, edge.ArrayType_Len, -1, n.Len) + } + walk(v, edge.ArrayType_Elt, -1, n.Elt) + + case *ast.StructType: + walk(v, edge.StructType_Fields, -1, n.Fields) + + case *ast.FuncType: + if n.TypeParams != nil { + walk(v, edge.FuncType_TypeParams, -1, n.TypeParams) + } + if n.Params != nil { + walk(v, edge.FuncType_Params, -1, n.Params) + } + if n.Results != nil { + walk(v, edge.FuncType_Results, -1, n.Results) + } + + case *ast.InterfaceType: + walk(v, edge.InterfaceType_Methods, -1, n.Methods) + + case *ast.MapType: + walk(v, edge.MapType_Key, -1, n.Key) + walk(v, edge.MapType_Value, -1, n.Value) + + case *ast.ChanType: + walk(v, edge.ChanType_Value, -1, n.Value) + + // Statements + case *ast.BadStmt: + // nothing to do + + case *ast.DeclStmt: + walk(v, edge.DeclStmt_Decl, -1, n.Decl) + + case *ast.EmptyStmt: + // nothing to do + + case *ast.LabeledStmt: + walk(v, edge.LabeledStmt_Label, -1, n.Label) + walk(v, edge.LabeledStmt_Stmt, -1, n.Stmt) + + case *ast.ExprStmt: + walk(v, edge.ExprStmt_X, -1, n.X) + + case *ast.SendStmt: + walk(v, edge.SendStmt_Chan, -1, n.Chan) + walk(v, edge.SendStmt_Value, -1, n.Value) + + case *ast.IncDecStmt: + walk(v, edge.IncDecStmt_X, -1, n.X) + + case *ast.AssignStmt: + walkList(v, edge.AssignStmt_Lhs, n.Lhs) + walkList(v, edge.AssignStmt_Rhs, n.Rhs) + + case *ast.GoStmt: + walk(v, edge.GoStmt_Call, -1, n.Call) + + case *ast.DeferStmt: + walk(v, edge.DeferStmt_Call, -1, n.Call) + + case *ast.ReturnStmt: + walkList(v, edge.ReturnStmt_Results, n.Results) + + case *ast.BranchStmt: + if n.Label != nil { + walk(v, edge.BranchStmt_Label, -1, n.Label) + } + + case *ast.BlockStmt: + walkList(v, edge.BlockStmt_List, n.List) + + case *ast.IfStmt: + if n.Init != nil { + walk(v, edge.IfStmt_Init, -1, n.Init) + } + walk(v, edge.IfStmt_Cond, -1, n.Cond) + walk(v, edge.IfStmt_Body, -1, n.Body) + if n.Else != nil { + walk(v, edge.IfStmt_Else, -1, n.Else) + } + + case *ast.CaseClause: + walkList(v, edge.CaseClause_List, n.List) + walkList(v, edge.CaseClause_Body, n.Body) + + case *ast.SwitchStmt: + if n.Init != nil { + walk(v, edge.SwitchStmt_Init, -1, n.Init) + } + if n.Tag != nil { + walk(v, edge.SwitchStmt_Tag, -1, n.Tag) + } + walk(v, edge.SwitchStmt_Body, -1, n.Body) + + case *ast.TypeSwitchStmt: + if n.Init != nil { + walk(v, edge.TypeSwitchStmt_Init, -1, n.Init) + } + walk(v, edge.TypeSwitchStmt_Assign, -1, n.Assign) + walk(v, edge.TypeSwitchStmt_Body, -1, n.Body) + + case *ast.CommClause: + if n.Comm != nil { + walk(v, edge.CommClause_Comm, -1, n.Comm) + } + walkList(v, edge.CommClause_Body, n.Body) + + case *ast.SelectStmt: + walk(v, edge.SelectStmt_Body, -1, n.Body) + + case *ast.ForStmt: + if n.Init != nil { + walk(v, edge.ForStmt_Init, -1, n.Init) + } + if n.Cond != nil { + walk(v, edge.ForStmt_Cond, -1, n.Cond) + } + if n.Post != nil { + walk(v, edge.ForStmt_Post, -1, n.Post) + } + walk(v, edge.ForStmt_Body, -1, n.Body) + + case *ast.RangeStmt: + if n.Key != nil { + walk(v, edge.RangeStmt_Key, -1, n.Key) + } + if n.Value != nil { + walk(v, edge.RangeStmt_Value, -1, n.Value) + } + walk(v, edge.RangeStmt_X, -1, n.X) + walk(v, edge.RangeStmt_Body, -1, n.Body) + + // Declarations + case *ast.ImportSpec: + if n.Doc != nil { + walk(v, edge.ImportSpec_Doc, -1, n.Doc) + } + if n.Name != nil { + walk(v, edge.ImportSpec_Name, -1, n.Name) + } + walk(v, edge.ImportSpec_Path, -1, n.Path) + if n.Comment != nil { + walk(v, edge.ImportSpec_Comment, -1, n.Comment) + } + + case *ast.ValueSpec: + if n.Doc != nil { + walk(v, edge.ValueSpec_Doc, -1, n.Doc) + } + walkList(v, edge.ValueSpec_Names, n.Names) + if n.Type != nil { + walk(v, edge.ValueSpec_Type, -1, n.Type) + } + walkList(v, edge.ValueSpec_Values, n.Values) + if n.Comment != nil { + walk(v, edge.ValueSpec_Comment, -1, n.Comment) + } + + case *ast.TypeSpec: + if n.Doc != nil { + walk(v, edge.TypeSpec_Doc, -1, n.Doc) + } + walk(v, edge.TypeSpec_Name, -1, n.Name) + if n.TypeParams != nil { + walk(v, edge.TypeSpec_TypeParams, -1, n.TypeParams) + } + walk(v, edge.TypeSpec_Type, -1, n.Type) + if n.Comment != nil { + walk(v, edge.TypeSpec_Comment, -1, n.Comment) + } + + case *ast.BadDecl: + // nothing to do + + case *ast.GenDecl: + if n.Doc != nil { + walk(v, edge.GenDecl_Doc, -1, n.Doc) + } + walkList(v, edge.GenDecl_Specs, n.Specs) + + case *ast.FuncDecl: + if n.Doc != nil { + walk(v, edge.FuncDecl_Doc, -1, n.Doc) + } + if n.Recv != nil { + walk(v, edge.FuncDecl_Recv, -1, n.Recv) + } + walk(v, edge.FuncDecl_Name, -1, n.Name) + walk(v, edge.FuncDecl_Type, -1, n.Type) + if n.Body != nil { + walk(v, edge.FuncDecl_Body, -1, n.Body) + } + + case *ast.File: + if n.Doc != nil { + walk(v, edge.File_Doc, -1, n.Doc) + } + walk(v, edge.File_Name, -1, n.Name) + walkList(v, edge.File_Decls, n.Decls) + // don't walk n.Comments - they have been + // visited already through the individual + // nodes + + default: + // (includes *ast.Package) + panic(fmt.Sprintf("Walk: unexpected node type %T", n)) + } + + v.pop(node) +} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go new file mode 100644 index 000000000..7b90bc923 --- /dev/null +++ b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -0,0 +1,236 @@ +// Copyright 2016 The Go 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 gcexportdata provides functions for reading and writing +// export data, which is a serialized description of the API of a Go +// package including the names, kinds, types, and locations of all +// exported declarations. +// +// The standard Go compiler (cmd/compile) writes an export data file +// for each package it compiles, which it later reads when compiling +// packages that import the earlier one. The compiler must thus +// contain logic to both write and read export data. +// (See the "Export" section in the cmd/compile/README file.) +// +// The [Read] function in this package can read files produced by the +// compiler, producing [go/types] data structures. As a matter of +// policy, Read supports export data files produced by only the last +// two Go releases plus tip; see https://go.dev/issue/68898. The +// export data files produced by the compiler contain additional +// details related to generics, inlining, and other optimizations that +// cannot be decoded by the [Read] function. +// +// In files written by the compiler, the export data is not at the +// start of the file. Before calling Read, use [NewReader] to locate +// the desired portion of the file. +// +// The [Write] function in this package encodes the exported API of a +// Go package ([types.Package]) as a file. Such files can be later +// decoded by Read, but cannot be consumed by the compiler. +// +// # Future changes +// +// Although Read supports the formats written by both Write and the +// compiler, the two are quite different, and there is an open +// proposal (https://go.dev/issue/69491) to separate these APIs. +// +// Under that proposal, this package would ultimately provide only the +// Read operation for compiler export data, which must be defined in +// this module (golang.org/x/tools), not in the standard library, to +// avoid version skew for developer tools that need to read compiler +// export data both before and after a Go release, such as from Go +// 1.23 to Go 1.24. Because this package lives in the tools module, +// clients can update their version of the module some time before the +// Go 1.24 release and rebuild and redeploy their tools, which will +// then be able to consume both Go 1.23 and Go 1.24 export data files, +// so they will work before and after the Go update. (See discussion +// at https://go.dev/issue/15651.) +// +// The operations to import and export [go/types] data structures +// would be defined in the go/types package as Import and Export. +// [Write] would (eventually) delegate to Export, +// and [Read], when it detects a file produced by Export, +// would delegate to Import. +// +// # Deprecations +// +// The [NewImporter] and [Find] functions are deprecated and should +// not be used in new code. The [WriteBundle] and [ReadBundle] +// functions are experimental, and there is an open proposal to +// deprecate them (https://go.dev/issue/69573). +package gcexportdata + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "go/token" + "go/types" + "io" + "os/exec" + + "golang.org/x/tools/internal/gcimporter" +) + +// Find returns the name of an object (.o) or archive (.a) file +// containing type information for the specified import path, +// using the go command. +// If no file was found, an empty filename is returned. +// +// A relative srcDir is interpreted relative to the current working directory. +// +// Find also returns the package's resolved (canonical) import path, +// reflecting the effects of srcDir and vendoring on importPath. +// +// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages, +// which is more efficient. +func Find(importPath, srcDir string) (filename, path string) { + cmd := exec.Command("go", "list", "-json", "-export", "--", importPath) + cmd.Dir = srcDir + out, err := cmd.Output() + if err != nil { + return "", "" + } + var data struct { + ImportPath string + Export string + } + json.Unmarshal(out, &data) + return data.Export, data.ImportPath +} + +// NewReader returns a reader for the export data section of an object +// (.o) or archive (.a) file read from r. The new reader may provide +// additional trailing data beyond the end of the export data. +func NewReader(r io.Reader) (io.Reader, error) { + buf := bufio.NewReader(r) + size, err := gcimporter.FindExportData(buf) + if err != nil { + return nil, err + } + + // We were given an archive and found the __.PKGDEF in it. + // This tells us the size of the export data, and we don't + // need to return the entire file. + return &io.LimitedReader{ + R: buf, + N: size, + }, nil +} + +// readAll works the same way as io.ReadAll, but avoids allocations and copies +// by preallocating a byte slice of the necessary size if the size is known up +// front. This is always possible when the input is an archive. In that case, +// NewReader will return the known size using an io.LimitedReader. +func readAll(r io.Reader) ([]byte, error) { + if lr, ok := r.(*io.LimitedReader); ok { + data := make([]byte, lr.N) + _, err := io.ReadFull(lr, data) + return data, err + } + return io.ReadAll(r) +} + +// Read reads export data from in, decodes it, and returns type +// information for the package. +// +// Read is capable of reading export data produced by [Write] at the +// same source code version, or by the last two Go releases (plus tip) +// of the standard Go compiler. Reading files from older compilers may +// produce an error. +// +// The package path (effectively its linker symbol prefix) is +// specified by path, since unlike the package name, this information +// may not be recorded in the export data. +// +// File position information is added to fset. +// +// Read may inspect and add to the imports map to ensure that references +// within the export data to other packages are consistent. The caller +// must ensure that imports[path] does not exist, or exists but is +// incomplete (see types.Package.Complete), and Read inserts the +// resulting package into this map entry. +// +// On return, the state of the reader is undefined. +func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, path string) (*types.Package, error) { + data, err := readAll(in) + if err != nil { + return nil, fmt.Errorf("reading export data for %q: %v", path, err) + } + + if bytes.HasPrefix(data, []byte("!")) { + return nil, fmt.Errorf("can't read export data for %q directly from an archive file (call gcexportdata.NewReader first to extract export data)", path) + } + + // The indexed export format starts with an 'i'; the older + // binary export format starts with a 'c', 'd', or 'v' + // (from "version"). Select appropriate importer. + if len(data) > 0 { + switch data[0] { + case 'v', 'c', 'd': + // binary, produced by cmd/compile till go1.10 + return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0]) + + case 'i': + // indexed, produced by cmd/compile till go1.19, + // and also by [Write]. + // + // If proposal #69491 is accepted, go/types + // serialization will be implemented by + // types.Export, to which Write would eventually + // delegate (explicitly dropping any pretence at + // inter-version Write-Read compatibility). + // This [Read] function would delegate to types.Import + // when it detects that the file was produced by Export. + _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) + return pkg, err + + case 'u': + // unified, produced by cmd/compile since go1.20 + _, pkg, err := gcimporter.UImportData(fset, imports, data[1:], path) + return pkg, err + + default: + l := min(len(data), 10) + return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), path) + } + } + return nil, fmt.Errorf("empty export data for %s", path) +} + +// Write writes encoded type information for the specified package to out. +// The FileSet provides file position information for named objects. +func Write(out io.Writer, fset *token.FileSet, pkg *types.Package) error { + if _, err := io.WriteString(out, "i"); err != nil { + return err + } + return gcimporter.IExportData(out, fset, pkg) +} + +// ReadBundle reads an export bundle from in, decodes it, and returns type +// information for the packages. +// File position information is added to fset. +// +// ReadBundle may inspect and add to the imports map to ensure that references +// within the export bundle to other packages are consistent. +// +// On return, the state of the reader is undefined. +// +// Experimental: This API is experimental and may change in the future. +func ReadBundle(in io.Reader, fset *token.FileSet, imports map[string]*types.Package) ([]*types.Package, error) { + data, err := readAll(in) + if err != nil { + return nil, fmt.Errorf("reading export bundle: %v", err) + } + return gcimporter.IImportBundle(fset, imports, data) +} + +// WriteBundle writes encoded type information for the specified packages to out. +// The FileSet provides file position information for named objects. +// +// Experimental: This API is experimental and may change in the future. +func WriteBundle(out io.Writer, fset *token.FileSet, pkgs []*types.Package) error { + return gcimporter.IExportBundle(out, fset, pkgs) +} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/importer.go b/vendor/golang.org/x/tools/go/gcexportdata/importer.go new file mode 100644 index 000000000..37a7247e2 --- /dev/null +++ b/vendor/golang.org/x/tools/go/gcexportdata/importer.go @@ -0,0 +1,75 @@ +// Copyright 2016 The Go 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 gcexportdata + +import ( + "fmt" + "go/token" + "go/types" + "os" +) + +// NewImporter returns a new instance of the types.Importer interface +// that reads type information from export data files written by gc. +// The Importer also satisfies types.ImporterFrom. +// +// Export data files are located using "go build" workspace conventions +// and the build.Default context. +// +// Use this importer instead of go/importer.For("gc", ...) to avoid the +// version-skew problems described in the documentation of this package, +// or to control the FileSet or access the imports map populated during +// package loading. +// +// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages, +// which is more efficient. +func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom { + return importer{fset, imports} +} + +type importer struct { + fset *token.FileSet + imports map[string]*types.Package +} + +func (imp importer) Import(importPath string) (*types.Package, error) { + return imp.ImportFrom(importPath, "", 0) +} + +func (imp importer) ImportFrom(importPath, srcDir string, mode types.ImportMode) (_ *types.Package, err error) { + filename, path := Find(importPath, srcDir) + if filename == "" { + if importPath == "unsafe" { + // Even for unsafe, call Find first in case + // the package was vendored. + return types.Unsafe, nil + } + return nil, fmt.Errorf("can't find import: %s", importPath) + } + + if pkg, ok := imp.imports[path]; ok && pkg.Complete() { + return pkg, nil // cache hit + } + + // open file + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + f.Close() + if err != nil { + // add file name to error + err = fmt.Errorf("reading export data: %s: %v", filename, err) + } + }() + + r, err := NewReader(f) + if err != nil { + return nil, err + } + + return Read(r, imp.fset, imp.imports, path) +} diff --git a/vendor/golang.org/x/tools/go/packages/doc.go b/vendor/golang.org/x/tools/go/packages/doc.go new file mode 100644 index 000000000..f1931d10e --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/doc.go @@ -0,0 +1,251 @@ +// Copyright 2018 The Go 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 packages loads Go packages for inspection and analysis. + +The [Load] function takes as input a list of patterns and returns a +list of [Package] values describing individual packages matched by those +patterns. +A [Config] specifies configuration options, the most important of which is +the [LoadMode], which controls the amount of detail in the loaded packages. + +Load passes most patterns directly to the underlying build tool. +The default build tool is the go command. +Its supported patterns are described at +https://pkg.go.dev/cmd/go#hdr-Package_lists_and_patterns. +Other build systems may be supported by providing a "driver"; +see [The driver protocol]. + +All patterns with the prefix "query=", where query is a +non-empty string of letters from [a-z], are reserved and may be +interpreted as query operators. + +Two query operators are currently supported: "file" and "pattern". + +The query "file=path/to/file.go" matches the package or packages enclosing +the Go source file path/to/file.go. For example "file=~/go/src/fmt/print.go" +might return the packages "fmt" and "fmt [fmt.test]". + +The query "pattern=string" causes "string" to be passed directly to +the underlying build tool. In most cases this is unnecessary, +but an application can use Load("pattern=" + x) as an escaping mechanism +to ensure that x is not interpreted as a query operator if it contains '='. + +All other query operators are reserved for future use and currently +cause Load to report an error. + +The Package struct provides basic information about the package, including + + - ID, a unique identifier for the package in the returned set; + - GoFiles, the names of the package's Go source files; + - Imports, a map from source import strings to the Packages they name; + - Types, the type information for the package's exported symbols; + - Syntax, the parsed syntax trees for the package's source code; and + - TypesInfo, the result of a complete type-check of the package syntax trees. + +(See the documentation for type Package for the complete list of fields +and more detailed descriptions.) + +For example, + + Load(nil, "bytes", "unicode...") + +returns four Package structs describing the standard library packages +bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern +can match multiple packages and that a package might be matched by +multiple patterns: in general it is not possible to determine which +packages correspond to which patterns. + +Note that the list returned by Load contains only the packages matched +by the patterns. Their dependencies can be found by walking the import +graph using the Imports fields. + +The Load function can be configured by passing a pointer to a Config as +the first argument. A nil Config is equivalent to the zero Config, which +causes Load to run in [LoadFiles] mode, collecting minimal information. +See the documentation for type Config for details. + +As noted earlier, the Config.Mode controls the amount of detail +reported about the loaded packages. See the documentation for type LoadMode +for details. + +Most tools should pass their command-line arguments (after any flags) +uninterpreted to Load, so that it can interpret them +according to the conventions of the underlying build system. + +See the Example function for typical usage. + +# The driver protocol + +Load may be used to load Go packages even in Go projects that use +alternative build systems, by installing an appropriate "driver" +program for the build system and specifying its location in the +GOPACKAGESDRIVER environment variable. +For example, +https://github.com/bazelbuild/rules_go/wiki/Editor-and-tool-integration +explains how to use the driver for Bazel. + +The driver program is responsible for interpreting patterns in its +preferred notation and reporting information about the packages that +those patterns identify. Drivers must also support the special "file=" +and "pattern=" patterns described above. + +The patterns are provided as positional command-line arguments. A +JSON-encoded [DriverRequest] message providing additional information +is written to the driver's standard input. The driver must write a +JSON-encoded [DriverResponse] message to its standard output. (This +message differs from the JSON schema produced by 'go list'.) + +The value of the PWD environment variable seen by the driver process +is the preferred name of its working directory. (The working directory +may have other aliases due to symbolic links; see the comment on the +Dir field of [exec.Cmd] for related information.) +When the driver process emits in its response the name of a file +that is a descendant of this directory, it must use an absolute path +that has the value of PWD as a prefix, to ensure that the returned +filenames satisfy the original query. +*/ +package packages // import "golang.org/x/tools/go/packages" + +/* + +Motivation and design considerations + +The new package's design solves problems addressed by two existing +packages: go/build, which locates and describes packages, and +golang.org/x/tools/go/loader, which loads, parses and type-checks them. +The go/build.Package structure encodes too much of the 'go build' way +of organizing projects, leaving us in need of a data type that describes a +package of Go source code independent of the underlying build system. +We wanted something that works equally well with go build and vgo, and +also other build systems such as Bazel and Blaze, making it possible to +construct analysis tools that work in all these environments. +Tools such as errcheck and staticcheck were essentially unavailable to +the Go community at Google, and some of Google's internal tools for Go +are unavailable externally. +This new package provides a uniform way to obtain package metadata by +querying each of these build systems, optionally supporting their +preferred command-line notations for packages, so that tools integrate +neatly with users' build environments. The Metadata query function +executes an external query tool appropriate to the current workspace. + +Loading packages always returns the complete import graph "all the way down", +even if all you want is information about a single package, because the query +mechanisms of all the build systems we currently support ({go,vgo} list, and +blaze/bazel aspect-based query) cannot provide detailed information +about one package without visiting all its dependencies too, so there is +no additional asymptotic cost to providing transitive information. +(This property might not be true of a hypothetical 5th build system.) + +In calls to TypeCheck, all initial packages, and any package that +transitively depends on one of them, must be loaded from source. +Consider A->B->C->D->E: if A,C are initial, A,B,C must be loaded from +source; D may be loaded from export data, and E may not be loaded at all +(though it's possible that D's export data mentions it, so a +types.Package may be created for it and exposed.) + +The old loader had a feature to suppress type-checking of function +bodies on a per-package basis, primarily intended to reduce the work of +obtaining type information for imported packages. Now that imports are +satisfied by export data, the optimization no longer seems necessary. + +Despite some early attempts, the old loader did not exploit export data, +instead always using the equivalent of WholeProgram mode. This was due +to the complexity of mixing source and export data packages (now +resolved by the upward traversal mentioned above), and because export data +files were nearly always missing or stale. Now that 'go build' supports +caching, all the underlying build systems can guarantee to produce +export data in a reasonable (amortized) time. + +Test "main" packages synthesized by the build system are now reported as +first-class packages, avoiding the need for clients (such as go/ssa) to +reinvent this generation logic. + +One way in which go/packages is simpler than the old loader is in its +treatment of in-package tests. In-package tests are packages that +consist of all the files of the library under test, plus the test files. +The old loader constructed in-package tests by a two-phase process of +mutation called "augmentation": first it would construct and type check +all the ordinary library packages and type-check the packages that +depend on them; then it would add more (test) files to the package and +type-check again. This two-phase approach had four major problems: +1) in processing the tests, the loader modified the library package, + leaving no way for a client application to see both the test + package and the library package; one would mutate into the other. +2) because test files can declare additional methods on types defined in + the library portion of the package, the dispatch of method calls in + the library portion was affected by the presence of the test files. + This should have been a clue that the packages were logically + different. +3) this model of "augmentation" assumed at most one in-package test + per library package, which is true of projects using 'go build', + but not other build systems. +4) because of the two-phase nature of test processing, all packages that + import the library package had to be processed before augmentation, + forcing a "one-shot" API and preventing the client from calling Load + in several times in sequence as is now possible in WholeProgram mode. + (TypeCheck mode has a similar one-shot restriction for a different reason.) + +Early drafts of this package supported "multi-shot" operation. +Although it allowed clients to make a sequence of calls (or concurrent +calls) to Load, building up the graph of Packages incrementally, +it was of marginal value: it complicated the API +(since it allowed some options to vary across calls but not others), +it complicated the implementation, +it cannot be made to work in Types mode, as explained above, +and it was less efficient than making one combined call (when this is possible). +Among the clients we have inspected, none made multiple calls to load +but could not be easily and satisfactorily modified to make only a single call. +However, applications changes may be required. +For example, the ssadump command loads the user-specified packages +and in addition the runtime package. It is tempting to simply append +"runtime" to the user-provided list, but that does not work if the user +specified an ad-hoc package such as [a.go b.go]. +Instead, ssadump no longer requests the runtime package, +but seeks it among the dependencies of the user-specified packages, +and emits an error if it is not found. + +Questions & Tasks + +- Add GOARCH/GOOS? + They are not portable concepts, but could be made portable. + Our goal has been to allow users to express themselves using the conventions + of the underlying build system: if the build system honors GOARCH + during a build and during a metadata query, then so should + applications built atop that query mechanism. + Conversely, if the target architecture of the build is determined by + command-line flags, the application can pass the relevant + flags through to the build system using a command such as: + myapp -query_flag="--cpu=amd64" -query_flag="--os=darwin" + However, this approach is low-level, unwieldy, and non-portable. + GOOS and GOARCH seem important enough to warrant a dedicated option. + +- How should we handle partial failures such as a mixture of good and + malformed patterns, existing and non-existent packages, successful and + failed builds, import failures, import cycles, and so on, in a call to + Load? + +- Support bazel, blaze, and go1.10 list, not just go1.11 list. + +- Handle (and test) various partial success cases, e.g. + a mixture of good packages and: + invalid patterns + nonexistent packages + empty packages + packages with malformed package or import declarations + unreadable files + import cycles + other parse errors + type errors + Make sure we record errors at the correct place in the graph. + +- Missing packages among initial arguments are not reported. + Return bogus packages for them, like golist does. + +- "undeclared name" errors (for example) are reported out of source file + order. I suspect this is due to the breadth-first resolution now used + by go/types. Is that a bug? Discuss with gri. + +*/ diff --git a/vendor/golang.org/x/tools/go/packages/external.go b/vendor/golang.org/x/tools/go/packages/external.go new file mode 100644 index 000000000..f37bc6510 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/external.go @@ -0,0 +1,153 @@ +// Copyright 2018 The Go 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 packages + +// This file defines the protocol that enables an external "driver" +// tool to supply package metadata in place of 'go list'. + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "os/exec" + "slices" + "strings" +) + +// DriverRequest defines the schema of a request for package metadata +// from an external driver program. The JSON-encoded DriverRequest +// message is provided to the driver program's standard input. The +// query patterns are provided as command-line arguments. +// +// See the package documentation for an overview. +type DriverRequest struct { + Mode LoadMode `json:"mode"` + + // Env specifies the environment the underlying build system should be run in. + Env []string `json:"env"` + + // BuildFlags are flags that should be passed to the underlying build system. + BuildFlags []string `json:"build_flags"` + + // Tests specifies whether the patterns should also return test packages. + Tests bool `json:"tests"` + + // Overlay maps file paths (relative to the driver's working directory) + // to the contents of overlay files (see Config.Overlay). + Overlay map[string][]byte `json:"overlay"` +} + +// DriverResponse defines the schema of a response from an external +// driver program, providing the results of a query for package +// metadata. The driver program must write a JSON-encoded +// DriverResponse message to its standard output. +// +// See the package documentation for an overview. +type DriverResponse struct { + // NotHandled is returned if the request can't be handled by the current + // driver. If an external driver returns a response with NotHandled, the + // rest of the DriverResponse is ignored, and go/packages will fallback + // to the next driver. If go/packages is extended in the future to support + // lists of multiple drivers, go/packages will fall back to the next driver. + NotHandled bool + + // Compiler and Arch are the arguments pass of types.SizesFor + // to get a types.Sizes to use when type checking. + Compiler string + Arch string + + // Roots is the set of package IDs that make up the root packages. + // We have to encode this separately because when we encode a single package + // we cannot know if it is one of the roots as that requires knowledge of the + // graph it is part of. + Roots []string `json:",omitempty"` + + // Packages is the full set of packages in the graph. + // The packages are not connected into a graph. + // The Imports if populated will be stubs that only have their ID set. + // Imports will be connected and then type and syntax information added in a + // later pass (see refine). + Packages []*Package + + // GoVersion is the minor version number used by the driver + // (e.g. the go command on the PATH) when selecting .go files. + // Zero means unknown. + GoVersion int +} + +// driver is the type for functions that query the build system for the +// packages named by the patterns. +type driver func(cfg *Config, patterns []string) (*DriverResponse, error) + +// findExternalDriver returns the file path of a tool that supplies +// the build system package structure, or "" if not found. +// If GOPACKAGESDRIVER is set in the environment findExternalTool returns its +// value, otherwise it searches for a binary named gopackagesdriver on the PATH. +func findExternalDriver(cfg *Config) driver { + const toolPrefix = "GOPACKAGESDRIVER=" + tool := "" + for _, env := range cfg.Env { + if val, ok := strings.CutPrefix(env, toolPrefix); ok { + tool = val + } + } + if tool != "" && tool == "off" { + return nil + } + if tool == "" { + var err error + tool, err = exec.LookPath("gopackagesdriver") + if err != nil { + return nil + } + } + return func(cfg *Config, patterns []string) (*DriverResponse, error) { + req, err := json.Marshal(DriverRequest{ + Mode: cfg.Mode, + Env: cfg.Env, + BuildFlags: cfg.BuildFlags, + Tests: cfg.Tests, + Overlay: cfg.Overlay, + }) + if err != nil { + return nil, fmt.Errorf("failed to encode message to driver tool: %v", err) + } + + buf := new(bytes.Buffer) + stderr := new(bytes.Buffer) + cmd := exec.CommandContext(cfg.Context, tool, patterns...) + cmd.Dir = cfg.Dir + // The cwd gets resolved to the real path. On Darwin, where + // /tmp is a symlink, this breaks anything that expects the + // working directory to keep the original path, including the + // go command when dealing with modules. + // + // os.Getwd stdlib has a special feature where if the + // cwd and the PWD are the same node then it trusts + // the PWD, so by setting it in the env for the child + // process we fix up all the paths returned by the go + // command. + // + // (See similar trick in Invocation.run in ../../internal/gocommand/invoke.go) + cmd.Env = append(slices.Clip(cfg.Env), "PWD="+cfg.Dir) + cmd.Stdin = bytes.NewReader(req) + cmd.Stdout = buf + cmd.Stderr = stderr + + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("%v: %v: %s", tool, err, cmd.Stderr) + } + if len(stderr.Bytes()) != 0 && os.Getenv("GOPACKAGESPRINTDRIVERERRORS") != "" { + fmt.Fprintf(os.Stderr, "%s stderr: <<%s>>\n", cmdDebugStr(cmd), stderr) + } + + var response DriverResponse + if err := json.Unmarshal(buf.Bytes(), &response); err != nil { + return nil, err + } + return &response, nil + } +} diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go new file mode 100644 index 000000000..0458b4f9c --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -0,0 +1,1086 @@ +// Copyright 2018 The Go 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 packages + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log" + "os" + "os/exec" + "path" + "path/filepath" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "unicode" + + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/packagesinternal" +) + +// debug controls verbose logging. +var debug, _ = strconv.ParseBool(os.Getenv("GOPACKAGESDEBUG")) + +// A goTooOldError reports that the go command +// found by exec.LookPath is too old to use the new go list behavior. +type goTooOldError struct { + error +} + +// responseDeduper wraps a DriverResponse, deduplicating its contents. +type responseDeduper struct { + seenRoots map[string]bool + seenPackages map[string]*Package + dr *DriverResponse +} + +func newDeduper() *responseDeduper { + return &responseDeduper{ + dr: &DriverResponse{}, + seenRoots: map[string]bool{}, + seenPackages: map[string]*Package{}, + } +} + +// addAll fills in r with a DriverResponse. +func (r *responseDeduper) addAll(dr *DriverResponse) { + for _, pkg := range dr.Packages { + r.addPackage(pkg) + } + for _, root := range dr.Roots { + r.addRoot(root) + } + r.dr.GoVersion = dr.GoVersion +} + +func (r *responseDeduper) addPackage(p *Package) { + if r.seenPackages[p.ID] != nil { + return + } + r.seenPackages[p.ID] = p + r.dr.Packages = append(r.dr.Packages, p) +} + +func (r *responseDeduper) addRoot(id string) { + if r.seenRoots[id] { + return + } + r.seenRoots[id] = true + r.dr.Roots = append(r.dr.Roots, id) +} + +type golistState struct { + cfg *Config + ctx context.Context + + runner *gocommand.Runner + + // overlay is the JSON file that encodes the Config.Overlay + // mapping, used by 'go list -overlay=...'. + overlay string + + envOnce sync.Once + goEnvError error + goEnv map[string]string + + rootsOnce sync.Once + rootDirsError error + rootDirs map[string]string + + goVersionOnce sync.Once + goVersionError error + goVersion int // The X in Go 1.X. + + // vendorDirs caches the (non)existence of vendor directories. + vendorDirs map[string]bool +} + +// getEnv returns Go environment variables. Only specific variables are +// populated -- computing all of them is slow. +func (state *golistState) getEnv() (map[string]string, error) { + state.envOnce.Do(func() { + var b *bytes.Buffer + b, state.goEnvError = state.invokeGo("env", "-json", "GOMOD", "GOPATH") + if state.goEnvError != nil { + return + } + + state.goEnv = make(map[string]string) + decoder := json.NewDecoder(b) + if state.goEnvError = decoder.Decode(&state.goEnv); state.goEnvError != nil { + return + } + }) + return state.goEnv, state.goEnvError +} + +// mustGetEnv is a convenience function that can be used if getEnv has already succeeded. +func (state *golistState) mustGetEnv() map[string]string { + env, err := state.getEnv() + if err != nil { + panic(fmt.Sprintf("mustGetEnv: %v", err)) + } + return env +} + +// goListDriver uses the go list command to interpret the patterns and produce +// the build system package structure. +// See driver for more details. +// +// overlay is the JSON file that encodes the cfg.Overlay +// mapping, used by 'go list -overlay=...' +func goListDriver(cfg *Config, runner *gocommand.Runner, overlay string, patterns []string) (_ *DriverResponse, err error) { + // Make sure that any asynchronous go commands are killed when we return. + parentCtx := cfg.Context + if parentCtx == nil { + parentCtx = context.Background() + } + ctx, cancel := context.WithCancel(parentCtx) + defer cancel() + + response := newDeduper() + + state := &golistState{ + cfg: cfg, + ctx: ctx, + vendorDirs: map[string]bool{}, + overlay: overlay, + runner: runner, + } + + // Fill in response.Sizes asynchronously if necessary. + if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { + errCh := make(chan error) + go func() { + compiler, arch, err := getSizesForArgs(ctx, state.cfgInvocation(), runner) + response.dr.Compiler = compiler + response.dr.Arch = arch + errCh <- err + }() + defer func() { + if sizesErr := <-errCh; sizesErr != nil { + err = sizesErr + } + }() + } + + // Determine files requested in contains patterns + var containFiles []string + restPatterns := make([]string, 0, len(patterns)) + // Extract file= and other [querytype]= patterns. Report an error if querytype + // doesn't exist. +extractQueries: + for _, pattern := range patterns { + eqidx := strings.Index(pattern, "=") + if eqidx < 0 { + restPatterns = append(restPatterns, pattern) + } else { + query, value := pattern[:eqidx], pattern[eqidx+len("="):] + switch query { + case "file": + containFiles = append(containFiles, value) + case "pattern": + restPatterns = append(restPatterns, value) + case "": // not a reserved query + restPatterns = append(restPatterns, pattern) + default: + for _, rune := range query { + if rune < 'a' || rune > 'z' { // not a reserved query + restPatterns = append(restPatterns, pattern) + continue extractQueries + } + } + // Reject all other patterns containing "=" + return nil, fmt.Errorf("invalid query type %q in query pattern %q", query, pattern) + } + } + } + + // See if we have any patterns to pass through to go list. Zero initial + // patterns also requires a go list call, since it's the equivalent of + // ".". + if len(restPatterns) > 0 || len(patterns) == 0 { + dr, err := state.createDriverResponse(restPatterns...) + if err != nil { + return nil, err + } + response.addAll(dr) + } + + if len(containFiles) != 0 { + if err := state.runContainsQueries(response, containFiles); err != nil { + return nil, err + } + } + + // (We may yet return an error due to defer.) + return response.dr, nil +} + +func (state *golistState) runContainsQueries(response *responseDeduper, queries []string) error { + for _, query := range queries { + // TODO(matloob): Do only one query per directory. + fdir := filepath.Dir(query) + // Pass absolute path of directory to go list so that it knows to treat it as a directory, + // not a package path. + pattern, err := filepath.Abs(fdir) + if err != nil { + return fmt.Errorf("could not determine absolute path of file= query path %q: %v", query, err) + } + dirResponse, err := state.createDriverResponse(pattern) + + // If there was an error loading the package, or no packages are returned, + // or the package is returned with errors, try to load the file as an + // ad-hoc package. + // Usually the error will appear in a returned package, but may not if we're + // in module mode and the ad-hoc is located outside a module. + if err != nil || len(dirResponse.Packages) == 0 || len(dirResponse.Packages) == 1 && len(dirResponse.Packages[0].GoFiles) == 0 && + len(dirResponse.Packages[0].Errors) == 1 { + var queryErr error + if dirResponse, queryErr = state.adhocPackage(pattern, query); queryErr != nil { + return err // return the original error + } + } + isRoot := make(map[string]bool, len(dirResponse.Roots)) + for _, root := range dirResponse.Roots { + isRoot[root] = true + } + for _, pkg := range dirResponse.Packages { + // Add any new packages to the main set + // We don't bother to filter packages that will be dropped by the changes of roots, + // that will happen anyway during graph construction outside this function. + // Over-reporting packages is not a problem. + response.addPackage(pkg) + // if the package was not a root one, it cannot have the file + if !isRoot[pkg.ID] { + continue + } + for _, pkgFile := range pkg.GoFiles { + if filepath.Base(query) == filepath.Base(pkgFile) { + response.addRoot(pkg.ID) + break + } + } + } + } + return nil +} + +// adhocPackage attempts to load or construct an ad-hoc package for a given +// query, if the original call to the driver produced inadequate results. +func (state *golistState) adhocPackage(pattern, query string) (*DriverResponse, error) { + response, err := state.createDriverResponse(query) + if err != nil { + return nil, err + } + // If we get nothing back from `go list`, + // try to make this file into its own ad-hoc package. + // TODO(rstambler): Should this check against the original response? + if len(response.Packages) == 0 { + response.Packages = append(response.Packages, &Package{ + ID: "command-line-arguments", + PkgPath: query, + GoFiles: []string{query}, + CompiledGoFiles: []string{query}, + Imports: make(map[string]*Package), + }) + response.Roots = append(response.Roots, "command-line-arguments") + } + // Handle special cases. + if len(response.Packages) == 1 { + // golang/go#33482: If this is a file= query for ad-hoc packages where + // the file only exists on an overlay, and exists outside of a module, + // add the file to the package and remove the errors. + if response.Packages[0].ID == "command-line-arguments" || + filepath.ToSlash(response.Packages[0].PkgPath) == filepath.ToSlash(query) { + if len(response.Packages[0].GoFiles) == 0 { + filename := filepath.Join(pattern, filepath.Base(query)) // avoid recomputing abspath + // TODO(matloob): check if the file is outside of a root dir? + for path := range state.cfg.Overlay { + if path == filename { + response.Packages[0].Errors = nil + response.Packages[0].GoFiles = []string{path} + response.Packages[0].CompiledGoFiles = []string{path} + } + } + } + } + } + return response, nil +} + +// Fields must match go list; +// see $GOROOT/src/cmd/go/internal/load/pkg.go. +type jsonPackage struct { + ImportPath string + Dir string + Name string + Target string + Export string + GoFiles []string + CompiledGoFiles []string + IgnoredGoFiles []string + IgnoredOtherFiles []string + EmbedPatterns []string + EmbedFiles []string + CFiles []string + CgoFiles []string + CXXFiles []string + MFiles []string + HFiles []string + FFiles []string + SFiles []string + SwigFiles []string + SwigCXXFiles []string + SysoFiles []string + Imports []string + ImportMap map[string]string + Deps []string + Module *Module + TestGoFiles []string + TestImports []string + XTestGoFiles []string + XTestImports []string + ForTest string // q in a "p [q.test]" package, else "" + DepOnly bool + + Error *packagesinternal.PackageError + DepsErrors []*packagesinternal.PackageError +} + +type jsonPackageError struct { + ImportStack []string + Pos string + Err string +} + +func otherFiles(p *jsonPackage) [][]string { + return [][]string{p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SwigFiles, p.SwigCXXFiles, p.SysoFiles} +} + +// createDriverResponse uses the "go list" command to expand the pattern +// words and return a response for the specified packages. +func (state *golistState) createDriverResponse(words ...string) (*DriverResponse, error) { + // go list uses the following identifiers in ImportPath and Imports: + // + // "p" -- importable package or main (command) + // "q.test" -- q's test executable + // "p [q.test]" -- variant of p as built for q's test executable + // "q_test [q.test]" -- q's external test package + // + // The packages p that are built differently for a test q.test + // are q itself, plus any helpers used by the external test q_test, + // typically including "testing" and all its dependencies. + + // Run "go list" for complete + // information on the specified packages. + goVersion, err := state.getGoVersion() + if err != nil { + return nil, err + } + buf, err := state.invokeGo("list", golistargs(state.cfg, words, goVersion)...) + if err != nil { + return nil, err + } + + seen := make(map[string]*jsonPackage) + pkgs := make(map[string]*Package) + additionalErrors := make(map[string][]Error) + // Decode the JSON and convert it to Package form. + response := &DriverResponse{ + GoVersion: goVersion, + } + for dec := json.NewDecoder(buf); dec.More(); { + p := new(jsonPackage) + if err := dec.Decode(p); err != nil { + return nil, fmt.Errorf("JSON decoding failed: %v", err) + } + + if p.ImportPath == "" { + // The documentation for go list says that “[e]rroneous packages will have + // a non-empty ImportPath”. If for some reason it comes back empty, we + // prefer to error out rather than silently discarding data or handing + // back a package without any way to refer to it. + if p.Error != nil { + return nil, Error{ + Pos: p.Error.Pos, + Msg: p.Error.Err, + } + } + return nil, fmt.Errorf("package missing import path: %+v", p) + } + + // Work around https://golang.org/issue/33157: + // go list -e, when given an absolute path, will find the package contained at + // that directory. But when no package exists there, it will return a fake package + // with an error and the ImportPath set to the absolute path provided to go list. + // Try to convert that absolute path to what its package path would be if it's + // contained in a known module or GOPATH entry. This will allow the package to be + // properly "reclaimed" when overlays are processed. + if filepath.IsAbs(p.ImportPath) && p.Error != nil { + pkgPath, ok, err := state.getPkgPath(p.ImportPath) + if err != nil { + return nil, err + } + if ok { + p.ImportPath = pkgPath + } + } + + if old, found := seen[p.ImportPath]; found { + // If one version of the package has an error, and the other doesn't, assume + // that this is a case where go list is reporting a fake dependency variant + // of the imported package: When a package tries to invalidly import another + // package, go list emits a variant of the imported package (with the same + // import path, but with an error on it, and the package will have a + // DepError set on it). An example of when this can happen is for imports of + // main packages: main packages can not be imported, but they may be + // separately matched and listed by another pattern. + // See golang.org/issue/36188 for more details. + + // The plan is that eventually, hopefully in Go 1.15, the error will be + // reported on the importing package rather than the duplicate "fake" + // version of the imported package. Once all supported versions of Go + // have the new behavior this logic can be deleted. + // TODO(matloob): delete the workaround logic once all supported versions of + // Go return the errors on the proper package. + + // There should be exactly one version of a package that doesn't have an + // error. + if old.Error == nil && p.Error == nil { + if !reflect.DeepEqual(p, old) { + return nil, fmt.Errorf("internal error: go list gives conflicting information for package %v", p.ImportPath) + } + continue + } + + // Determine if this package's error needs to be bubbled up. + // This is a hack, and we expect for go list to eventually set the error + // on the package. + if old.Error != nil { + var errkind string + if strings.Contains(old.Error.Err, "not an importable package") { + errkind = "not an importable package" + } else if strings.Contains(old.Error.Err, "use of internal package") && strings.Contains(old.Error.Err, "not allowed") { + errkind = "use of internal package not allowed" + } + if errkind != "" { + if len(old.Error.ImportStack) < 1 { + return nil, fmt.Errorf(`internal error: go list gave a %q error with empty import stack`, errkind) + } + importingPkg := old.Error.ImportStack[len(old.Error.ImportStack)-1] + if importingPkg == old.ImportPath { + // Using an older version of Go which put this package itself on top of import + // stack, instead of the importer. Look for importer in second from top + // position. + if len(old.Error.ImportStack) < 2 { + return nil, fmt.Errorf(`internal error: go list gave a %q error with an import stack without importing package`, errkind) + } + importingPkg = old.Error.ImportStack[len(old.Error.ImportStack)-2] + } + additionalErrors[importingPkg] = append(additionalErrors[importingPkg], Error{ + Pos: old.Error.Pos, + Msg: old.Error.Err, + Kind: ListError, + }) + } + } + + // Make sure that if there's a version of the package without an error, + // that's the one reported to the user. + if old.Error == nil { + continue + } + + // This package will replace the old one at the end of the loop. + } + seen[p.ImportPath] = p + + pkg := &Package{ + Name: p.Name, + ID: p.ImportPath, + Dir: p.Dir, + Target: p.Target, + GoFiles: absJoin(p.Dir, p.GoFiles, p.CgoFiles), + CompiledGoFiles: absJoin(p.Dir, p.CompiledGoFiles), + OtherFiles: absJoin(p.Dir, otherFiles(p)...), + EmbedFiles: absJoin(p.Dir, p.EmbedFiles), + EmbedPatterns: absJoin(p.Dir, p.EmbedPatterns), + IgnoredFiles: absJoin(p.Dir, p.IgnoredGoFiles, p.IgnoredOtherFiles), + ForTest: p.ForTest, + depsErrors: p.DepsErrors, + Module: p.Module, + } + + if (state.cfg.Mode&typecheckCgo) != 0 && len(p.CgoFiles) != 0 { + if len(p.CompiledGoFiles) > len(p.GoFiles) { + // We need the cgo definitions, which are in the first + // CompiledGoFile after the non-cgo ones. This is a hack but there + // isn't currently a better way to find it. We also need the pure + // Go files and unprocessed cgo files, all of which are already + // in pkg.GoFiles. + cgoTypes := p.CompiledGoFiles[len(p.GoFiles)] + pkg.CompiledGoFiles = append([]string{cgoTypes}, pkg.GoFiles...) + } else { + // golang/go#38990: go list silently fails to do cgo processing + pkg.CompiledGoFiles = nil + pkg.Errors = append(pkg.Errors, Error{ + Msg: "go list failed to return CompiledGoFiles. This may indicate failure to perform cgo processing; try building at the command line. See https://golang.org/issue/38990.", + Kind: ListError, + }) + } + } + + // Work around https://golang.org/issue/28749: + // cmd/go puts assembly, C, and C++ files in CompiledGoFiles. + // Remove files from CompiledGoFiles that are non-go files + // (or are not files that look like they are from the cache). + if len(pkg.CompiledGoFiles) > 0 { + out := pkg.CompiledGoFiles[:0] + for _, f := range pkg.CompiledGoFiles { + if ext := filepath.Ext(f); ext != ".go" && ext != "" { // ext == "" means the file is from the cache, so probably cgo-processed file + continue + } + out = append(out, f) + } + pkg.CompiledGoFiles = out + } + + // Extract the PkgPath from the package's ID. + if i := strings.IndexByte(pkg.ID, ' '); i >= 0 { + pkg.PkgPath = pkg.ID[:i] + } else { + pkg.PkgPath = pkg.ID + } + + if pkg.PkgPath == "unsafe" { + pkg.CompiledGoFiles = nil // ignore fake unsafe.go file (#59929) + } else if len(pkg.CompiledGoFiles) == 0 { + // Work around for pre-go.1.11 versions of go list. + // TODO(matloob): they should be handled by the fallback. + // Can we delete this? + pkg.CompiledGoFiles = pkg.GoFiles + } + + // Assume go list emits only absolute paths for Dir. + if p.Dir != "" && !filepath.IsAbs(p.Dir) { + log.Fatalf("internal error: go list returned non-absolute Package.Dir: %s", p.Dir) + } + + if p.Export != "" && !filepath.IsAbs(p.Export) { + pkg.ExportFile = filepath.Join(p.Dir, p.Export) + } else { + pkg.ExportFile = p.Export + } + + // imports + // + // Imports contains the IDs of all imported packages. + // ImportsMap records (path, ID) only where they differ. + ids := make(map[string]bool) + for _, id := range p.Imports { + ids[id] = true + } + pkg.Imports = make(map[string]*Package) + for path, id := range p.ImportMap { + pkg.Imports[path] = &Package{ID: id} // non-identity import + delete(ids, id) + } + for id := range ids { + if id == "C" { + continue + } + + pkg.Imports[id] = &Package{ID: id} // identity import + } + if !p.DepOnly { + response.Roots = append(response.Roots, pkg.ID) + } + + // Temporary work-around for golang/go#39986. Parse filenames out of + // error messages. This happens if there are unrecoverable syntax + // errors in the source, so we can't match on a specific error message. + // + // TODO(rfindley): remove this heuristic, in favor of considering + // InvalidGoFiles from the list driver. + if err := p.Error; err != nil && state.shouldAddFilenameFromError(p) { + addFilenameFromPos := func(pos string) bool { + split := strings.Split(pos, ":") + if len(split) < 1 { + return false + } + filename := strings.TrimSpace(split[0]) + if filename == "" { + return false + } + if !filepath.IsAbs(filename) { + filename = filepath.Join(state.cfg.Dir, filename) + } + info, _ := os.Stat(filename) + if info == nil { + return false + } + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, filename) + pkg.GoFiles = append(pkg.GoFiles, filename) + return true + } + found := addFilenameFromPos(err.Pos) + // In some cases, go list only reports the error position in the + // error text, not the error position. One such case is when the + // file's package name is a keyword (see golang.org/issue/39763). + if !found { + addFilenameFromPos(err.Err) + } + } + + if p.Error != nil { + msg := strings.TrimSpace(p.Error.Err) // Trim to work around golang.org/issue/32363. + // Address golang.org/issue/35964 by appending import stack to error message. + if msg == "import cycle not allowed" && len(p.Error.ImportStack) != 0 { + msg += fmt.Sprintf(": import stack: %v", p.Error.ImportStack) + } + pkg.Errors = append(pkg.Errors, Error{ + Pos: p.Error.Pos, + Msg: msg, + Kind: ListError, + }) + } + + pkgs[pkg.ID] = pkg + } + + for id, errs := range additionalErrors { + if p, ok := pkgs[id]; ok { + p.Errors = append(p.Errors, errs...) + } + } + for _, pkg := range pkgs { + response.Packages = append(response.Packages, pkg) + } + sort.Slice(response.Packages, func(i, j int) bool { return response.Packages[i].ID < response.Packages[j].ID }) + + return response, nil +} + +func (state *golistState) shouldAddFilenameFromError(p *jsonPackage) bool { + if len(p.GoFiles) > 0 || len(p.CompiledGoFiles) > 0 { + return false + } + + goV, err := state.getGoVersion() + if err != nil { + return false + } + + // On Go 1.14 and earlier, only add filenames from errors if the import stack is empty. + // The import stack behaves differently for these versions than newer Go versions. + if goV < 15 { + return len(p.Error.ImportStack) == 0 + } + + // On Go 1.15 and later, only parse filenames out of error if there's no import stack, + // or the current package is at the top of the import stack. This is not guaranteed + // to work perfectly, but should avoid some cases where files in errors don't belong to this + // package. + return len(p.Error.ImportStack) == 0 || p.Error.ImportStack[len(p.Error.ImportStack)-1] == p.ImportPath +} + +// getGoVersion returns the effective minor version of the go command. +func (state *golistState) getGoVersion() (int, error) { + state.goVersionOnce.Do(func() { + state.goVersion, state.goVersionError = gocommand.GoVersion(state.ctx, state.cfgInvocation(), state.runner) + }) + return state.goVersion, state.goVersionError +} + +// getPkgPath finds the package path of a directory if it's relative to a root +// directory. +func (state *golistState) getPkgPath(dir string) (string, bool, error) { + absDir, err := filepath.Abs(dir) + if err != nil { + return "", false, err + } + roots, err := state.determineRootDirs() + if err != nil { + return "", false, err + } + + for rdir, rpath := range roots { + // Make sure that the directory is in the module, + // to avoid creating a path relative to another module. + if !strings.HasPrefix(absDir, rdir) { + continue + } + // TODO(matloob): This doesn't properly handle symlinks. + r, err := filepath.Rel(rdir, dir) + if err != nil { + continue + } + if rpath != "" { + // We choose only one root even though the directory even it can belong in multiple modules + // or GOPATH entries. This is okay because we only need to work with absolute dirs when a + // file is missing from disk, for instance when gopls calls go/packages in an overlay. + // Once the file is saved, gopls, or the next invocation of the tool will get the correct + // result straight from golist. + // TODO(matloob): Implement module tiebreaking? + return path.Join(rpath, filepath.ToSlash(r)), true, nil + } + return filepath.ToSlash(r), true, nil + } + return "", false, nil +} + +// absJoin absolutizes and flattens the lists of files. +func absJoin(dir string, fileses ...[]string) (res []string) { + for _, files := range fileses { + for _, file := range files { + if !filepath.IsAbs(file) { + file = filepath.Join(dir, file) + } + res = append(res, file) + } + } + return res +} + +func jsonFlag(cfg *Config, goVersion int) string { + if goVersion < 19 { + return "-json" + } + var fields []string + added := make(map[string]bool) + addFields := func(fs ...string) { + for _, f := range fs { + if !added[f] { + added[f] = true + fields = append(fields, f) + } + } + } + addFields("Name", "ImportPath", "Error") // These fields are always needed + if cfg.Mode&NeedFiles != 0 || cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { + addFields("Dir", "GoFiles", "IgnoredGoFiles", "IgnoredOtherFiles", "CFiles", + "CgoFiles", "CXXFiles", "MFiles", "HFiles", "FFiles", "SFiles", + "SwigFiles", "SwigCXXFiles", "SysoFiles") + if cfg.Tests { + addFields("TestGoFiles", "XTestGoFiles") + } + } + if cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { + // CompiledGoFiles seems to be required for the test case TestCgoNoSyntax, + // even when -compiled isn't passed in. + // TODO(#52435): Should we make the test ask for -compiled, or automatically + // request CompiledGoFiles in certain circumstances? + addFields("Dir", "CompiledGoFiles") + } + if cfg.Mode&NeedCompiledGoFiles != 0 { + addFields("Dir", "CompiledGoFiles", "Export") + } + if cfg.Mode&NeedImports != 0 { + // When imports are requested, DepOnly is used to distinguish between packages + // explicitly requested and transitive imports of those packages. + addFields("DepOnly", "Imports", "ImportMap") + if cfg.Tests { + addFields("TestImports", "XTestImports") + } + } + if cfg.Mode&NeedDeps != 0 { + addFields("DepOnly") + } + if usesExportData(cfg) { + // Request Dir in the unlikely case Export is not absolute. + addFields("Dir", "Export") + } + if cfg.Mode&NeedForTest != 0 { + addFields("ForTest") + } + if cfg.Mode&needInternalDepsErrors != 0 { + addFields("DepsErrors") + } + if cfg.Mode&NeedModule != 0 { + addFields("Module") + } + if cfg.Mode&NeedEmbedFiles != 0 { + addFields("EmbedFiles") + } + if cfg.Mode&NeedEmbedPatterns != 0 { + addFields("EmbedPatterns") + } + if cfg.Mode&NeedTarget != 0 { + addFields("Target") + } + return "-json=" + strings.Join(fields, ",") +} + +func golistargs(cfg *Config, words []string, goVersion int) []string { + const findFlags = NeedImports | NeedTypes | NeedSyntax | NeedTypesInfo + fullargs := []string{ + "-e", jsonFlag(cfg, goVersion), + fmt.Sprintf("-compiled=%t", cfg.Mode&(NeedCompiledGoFiles|NeedSyntax|NeedTypes|NeedTypesInfo|NeedTypesSizes) != 0), + fmt.Sprintf("-test=%t", cfg.Tests), + fmt.Sprintf("-export=%t", usesExportData(cfg)), + fmt.Sprintf("-deps=%t", cfg.Mode&NeedImports != 0), + // go list doesn't let you pass -test and -find together, + // probably because you'd just get the TestMain. + fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0 && !usesExportData(cfg)), + } + + // golang/go#60456: with go1.21 and later, go list serves pgo variants, which + // can be costly to compute and may result in redundant processing for the + // caller. Disable these variants. If someone wants to add e.g. a NeedPGO + // mode flag, that should be a separate proposal. + if goVersion >= 21 { + fullargs = append(fullargs, "-pgo=off") + } + + fullargs = append(fullargs, cfg.BuildFlags...) + fullargs = append(fullargs, "--") + fullargs = append(fullargs, words...) + return fullargs +} + +// cfgInvocation returns an Invocation that reflects cfg's settings. +func (state *golistState) cfgInvocation() gocommand.Invocation { + cfg := state.cfg + return gocommand.Invocation{ + BuildFlags: cfg.BuildFlags, + ModFile: cfg.modFile, + ModFlag: cfg.modFlag, + CleanEnv: cfg.Env != nil, + Env: cfg.Env, + Logf: cfg.Logf, + WorkingDir: cfg.Dir, + Overlay: state.overlay, + } +} + +// invokeGo returns the stdout of a go command invocation. +func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, error) { + cfg := state.cfg + + inv := state.cfgInvocation() + inv.Verb = verb + inv.Args = args + + stdout, stderr, friendlyErr, err := state.runner.RunRaw(cfg.Context, inv) + if err != nil { + // Check for 'go' executable not being found. + if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound { + return nil, fmt.Errorf("'go list' driver requires 'go', but %s", exec.ErrNotFound) + } + + exitErr, ok := err.(*exec.ExitError) + if !ok { + // Catastrophic error: + // - context cancellation + return nil, fmt.Errorf("couldn't run 'go': %w", err) + } + + // Old go version? + if strings.Contains(stderr.String(), "flag provided but not defined") { + return nil, goTooOldError{fmt.Errorf("unsupported version of go: %s: %s", exitErr, stderr)} + } + + // Related to #24854 + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "unexpected directory layout") { + return nil, friendlyErr + } + + // Return an error if 'go list' failed due to missing tools in + // $GOROOT/pkg/tool/$GOOS_$GOARCH (#69606). + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), `go: no such tool`) { + return nil, friendlyErr + } + + // Is there an error running the C compiler in cgo? This will be reported in the "Error" field + // and should be suppressed by go list -e. + // + // This condition is not perfect yet because the error message can include other error messages than runtime/cgo. + isPkgPathRune := func(r rune) bool { + // From https://golang.org/ref/spec#Import_declarations: + // Implementation restriction: A compiler may restrict ImportPaths to non-empty strings + // using only characters belonging to Unicode's L, M, N, P, and S general categories + // (the Graphic characters without spaces) and may also exclude the + // characters !"#$%&'()*,:;<=>?[\]^`{|} and the Unicode replacement character U+FFFD. + return unicode.IsOneOf([]*unicode.RangeTable{unicode.L, unicode.M, unicode.N, unicode.P, unicode.S}, r) && + !strings.ContainsRune("!\"#$%&'()*,:;<=>?[\\]^`{|}\uFFFD", r) + } + // golang/go#36770: Handle case where cmd/go prints module download messages before the error. + msg := stderr.String() + for strings.HasPrefix(msg, "go: downloading") { + msg = msg[strings.IndexRune(msg, '\n')+1:] + } + if len(stderr.String()) > 0 && strings.HasPrefix(stderr.String(), "# ") { + msg := msg[len("# "):] + if strings.HasPrefix(strings.TrimLeftFunc(msg, isPkgPathRune), "\n") { + return stdout, nil + } + // Treat pkg-config errors as a special case (golang.org/issue/36770). + if strings.HasPrefix(msg, "pkg-config") { + return stdout, nil + } + } + + // This error only appears in stderr. See golang.org/cl/166398 for a fix in go list to show + // the error in the Err section of stdout in case -e option is provided. + // This fix is provided for backwards compatibility. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "named files must be .go files") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Similar to the previous error, but currently lacks a fix in Go. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "named files must all be in one directory") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Backwards compatibility for Go 1.11 because 1.12 and 1.13 put the directory in the ImportPath. + // If the package doesn't exist, put the absolute path of the directory into the error message, + // as Go 1.13 list does. + const noSuchDirectory = "no such directory" + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), noSuchDirectory) { + errstr := stderr.String() + abspath := strings.TrimSpace(errstr[strings.Index(errstr, noSuchDirectory)+len(noSuchDirectory):]) + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + abspath, strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for #29280: go list -e has incorrect behavior when an ad-hoc package doesn't exist. + // Note that the error message we look for in this case is different that the one looked for above. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "no such file or directory") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for #34273. go list -e with GO111MODULE=on has incorrect behavior when listing a + // directory outside any module. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "outside available modules") { + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + // TODO(matloob): command-line-arguments isn't correct here. + "command-line-arguments", strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Another variation of the previous error + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "outside module root") { + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + // TODO(matloob): command-line-arguments isn't correct here. + "command-line-arguments", strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for an instance of golang.org/issue/26755: go list -e will return a non-zero exit + // status if there's a dependency on a package that doesn't exist. But it should return + // a zero exit status and set an error on that package. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "no Go files in") { + // Don't clobber stdout if `go list` actually returned something. + if len(stdout.String()) > 0 { + return stdout, nil + } + // try to extract package name from string + stderrStr := stderr.String() + var importPath string + colon := strings.Index(stderrStr, ":") + if colon > 0 && strings.HasPrefix(stderrStr, "go build ") { + importPath = stderrStr[len("go build "):colon] + } + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + importPath, strings.Trim(stderrStr, "\n")) + return bytes.NewBufferString(output), nil + } + + // Export mode entails a build. + // If that build fails, errors appear on stderr + // (despite the -e flag) and the Export field is blank. + // Do not fail in that case. + // The same is true if an ad-hoc package given to go list doesn't exist. + // TODO(matloob): Remove these once we can depend on go list to exit with a zero status with -e even when + // packages don't exist or a build fails. + if !usesExportData(cfg) && !containsGoFile(args) { + return nil, friendlyErr + } + } + return stdout, nil +} + +func containsGoFile(s []string) bool { + for _, f := range s { + if strings.HasSuffix(f, ".go") { + return true + } + } + return false +} + +func cmdDebugStr(cmd *exec.Cmd) string { + env := make(map[string]string) + for _, kv := range cmd.Env { + split := strings.SplitN(kv, "=", 2) + k, v := split[0], split[1] + env[k] = v + } + + var args []string + for _, arg := range cmd.Args { + quoted := strconv.Quote(arg) + if quoted[1:len(quoted)-1] != arg || strings.Contains(arg, " ") { + args = append(args, quoted) + } else { + args = append(args, arg) + } + } + return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " ")) +} + +// getSizesForArgs queries 'go list' for the appropriate +// Compiler and GOARCH arguments to pass to [types.SizesFor]. +func getSizesForArgs(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) { + inv.Verb = "list" + inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"} + stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv) + var goarch, compiler string + if rawErr != nil { + rawErrMsg := rawErr.Error() + if strings.Contains(rawErrMsg, "cannot find main module") || + strings.Contains(rawErrMsg, "go.mod file not found") { + // User's running outside of a module. + // All bets are off. Get GOARCH and guess compiler is gc. + // TODO(matloob): Is this a problem in practice? + inv.Verb = "env" + inv.Args = []string{"GOARCH"} + envout, enverr := gocmdRunner.Run(ctx, inv) + if enverr != nil { + return "", "", enverr + } + goarch = strings.TrimSpace(envout.String()) + compiler = "gc" + } else if friendlyErr != nil { + return "", "", friendlyErr + } else { + // This should be unreachable, but be defensive + // in case RunRaw's error results are inconsistent. + return "", "", rawErr + } + } else { + fields := strings.Fields(stdout.String()) + if len(fields) < 2 { + return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", + stdout.String(), stderr.String()) + } + goarch = fields[0] + compiler = fields[1] + } + return compiler, goarch, nil +} diff --git a/vendor/golang.org/x/tools/go/packages/golist_overlay.go b/vendor/golang.org/x/tools/go/packages/golist_overlay.go new file mode 100644 index 000000000..d823c474a --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/golist_overlay.go @@ -0,0 +1,83 @@ +// Copyright 2018 The Go 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 packages + +import ( + "encoding/json" + "path/filepath" + + "golang.org/x/tools/internal/gocommand" +) + +// determineRootDirs returns a mapping from absolute directories that could +// contain code to their corresponding import path prefixes. +func (state *golistState) determineRootDirs() (map[string]string, error) { + env, err := state.getEnv() + if err != nil { + return nil, err + } + if env["GOMOD"] != "" { + state.rootsOnce.Do(func() { + state.rootDirs, state.rootDirsError = state.determineRootDirsModules() + }) + } else { + state.rootsOnce.Do(func() { + state.rootDirs, state.rootDirsError = state.determineRootDirsGOPATH() + }) + } + return state.rootDirs, state.rootDirsError +} + +func (state *golistState) determineRootDirsModules() (map[string]string, error) { + // List all of the modules--the first will be the directory for the main + // module. Any replaced modules will also need to be treated as roots. + // Editing files in the module cache isn't a great idea, so we don't + // plan to ever support that. + out, err := state.invokeGo("list", "-m", "-json", "all") + if err != nil { + // 'go list all' will fail if we're outside of a module and + // GO111MODULE=on. Try falling back without 'all'. + var innerErr error + out, innerErr = state.invokeGo("list", "-m", "-json") + if innerErr != nil { + return nil, err + } + } + roots := map[string]string{} + modules := map[string]string{} + var i int + for dec := json.NewDecoder(out); dec.More(); { + mod := new(gocommand.ModuleJSON) + if err := dec.Decode(mod); err != nil { + return nil, err + } + if mod.Dir != "" && mod.Path != "" { + // This is a valid module; add it to the map. + absDir, err := filepath.Abs(mod.Dir) + if err != nil { + return nil, err + } + modules[absDir] = mod.Path + // The first result is the main module. + if i == 0 || mod.Replace != nil && mod.Replace.Path != "" { + roots[absDir] = mod.Path + } + } + i++ + } + return roots, nil +} + +func (state *golistState) determineRootDirsGOPATH() (map[string]string, error) { + m := map[string]string{} + for _, dir := range filepath.SplitList(state.mustGetEnv()["GOPATH"]) { + absDir, err := filepath.Abs(dir) + if err != nil { + return nil, err + } + m[filepath.Join(absDir, "src")] = "" + } + return m, nil +} diff --git a/vendor/golang.org/x/tools/go/packages/loadmode_string.go b/vendor/golang.org/x/tools/go/packages/loadmode_string.go new file mode 100644 index 000000000..69eec9f44 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/loadmode_string.go @@ -0,0 +1,56 @@ +// Copyright 2019 The Go 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 packages + +import ( + "fmt" + "strings" +) + +var modes = [...]struct { + mode LoadMode + name string +}{ + {NeedName, "NeedName"}, + {NeedFiles, "NeedFiles"}, + {NeedCompiledGoFiles, "NeedCompiledGoFiles"}, + {NeedImports, "NeedImports"}, + {NeedDeps, "NeedDeps"}, + {NeedExportFile, "NeedExportFile"}, + {NeedTypes, "NeedTypes"}, + {NeedSyntax, "NeedSyntax"}, + {NeedTypesInfo, "NeedTypesInfo"}, + {NeedTypesSizes, "NeedTypesSizes"}, + {NeedForTest, "NeedForTest"}, + {NeedModule, "NeedModule"}, + {NeedEmbedFiles, "NeedEmbedFiles"}, + {NeedEmbedPatterns, "NeedEmbedPatterns"}, + {NeedTarget, "NeedTarget"}, +} + +func (mode LoadMode) String() string { + if mode == 0 { + return "LoadMode(0)" + } + var out []string + // named bits + for _, item := range modes { + if (mode & item.mode) != 0 { + mode ^= item.mode + out = append(out, item.name) + } + } + // unnamed residue + if mode != 0 { + if out == nil { + return fmt.Sprintf("LoadMode(%#x)", int(mode)) + } + out = append(out, fmt.Sprintf("%#x", int(mode))) + } + if len(out) == 1 { + return out[0] + } + return "(" + strings.Join(out, "|") + ")" +} diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go new file mode 100644 index 000000000..6665a04c1 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -0,0 +1,1573 @@ +// Copyright 2018 The Go 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 packages + +// See doc.go for package documentation and implementation notes. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/scanner" + "go/token" + "go/types" + "log" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/sync/errgroup" + + "golang.org/x/tools/go/gcexportdata" + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/packagesinternal" + "golang.org/x/tools/internal/typesinternal" +) + +// A LoadMode controls the amount of detail to return when loading. +// The bits below can be combined to specify which fields should be +// filled in the result packages. +// +// The zero value is a special case, equivalent to combining +// the NeedName, NeedFiles, and NeedCompiledGoFiles bits. +// +// ID and Errors (if present) will always be filled. +// [Load] may return more information than requested. +// +// The Mode flag is a union of several bits named NeedName, +// NeedFiles, and so on, each of which determines whether +// a given field of Package (Name, Files, etc) should be +// populated. +// +// For convenience, we provide named constants for the most +// common combinations of Need flags: +// +// [LoadFiles] lists of files in each package +// [LoadImports] ... plus imports +// [LoadTypes] ... plus type information +// [LoadSyntax] ... plus type-annotated syntax +// [LoadAllSyntax] ... for all dependencies +// +// Unfortunately there are a number of open bugs related to +// interactions among the LoadMode bits: +// - https://go.dev/issue/56633 +// - https://go.dev/issue/56677 +// - https://go.dev/issue/58726 +// - https://go.dev/issue/63517 +type LoadMode int + +const ( + // NeedName adds Name and PkgPath. + NeedName LoadMode = 1 << iota + + // NeedFiles adds Dir, GoFiles, OtherFiles, and IgnoredFiles + NeedFiles + + // NeedCompiledGoFiles adds CompiledGoFiles. + NeedCompiledGoFiles + + // NeedImports adds Imports. If NeedDeps is not set, the Imports field will contain + // "placeholder" Packages with only the ID set. + NeedImports + + // NeedDeps adds the fields requested by the LoadMode in the packages in Imports. + NeedDeps + + // NeedExportFile adds ExportFile. + NeedExportFile + + // NeedTypes adds Types, Fset, and IllTyped. + NeedTypes + + // NeedSyntax adds Syntax and Fset. + NeedSyntax + + // NeedTypesInfo adds TypesInfo and Fset. + NeedTypesInfo + + // NeedTypesSizes adds TypesSizes. + NeedTypesSizes + + // needInternalDepsErrors adds the internal deps errors field for use by gopls. + needInternalDepsErrors + + // NeedForTest adds ForTest. + // + // Tests must also be set on the context for this field to be populated. + NeedForTest + + // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+. + // Modifies CompiledGoFiles and Types, and has no effect on its own. + typecheckCgo + + // NeedModule adds Module. + NeedModule + + // NeedEmbedFiles adds EmbedFiles. + NeedEmbedFiles + + // NeedEmbedPatterns adds EmbedPatterns. + NeedEmbedPatterns + + // NeedTarget adds Target. + NeedTarget + + // Be sure to update loadmode_string.go when adding new items! +) + +const ( + // LoadFiles loads the name and file names for the initial packages. + LoadFiles = NeedName | NeedFiles | NeedCompiledGoFiles + + // LoadImports loads the name, file names, and import mapping for the initial packages. + LoadImports = LoadFiles | NeedImports + + // LoadTypes loads exported type information for the initial packages. + LoadTypes = LoadImports | NeedTypes | NeedTypesSizes + + // LoadSyntax loads typed syntax for the initial packages. + LoadSyntax = LoadTypes | NeedSyntax | NeedTypesInfo + + // LoadAllSyntax loads typed syntax for the initial packages and all dependencies. + LoadAllSyntax = LoadSyntax | NeedDeps + + // Deprecated: NeedExportsFile is a historical misspelling of NeedExportFile. + // + //go:fix inline + NeedExportsFile = NeedExportFile +) + +// A Config specifies details about how packages should be loaded. +// The zero value is a valid configuration. +// +// Calls to [Load] do not modify this struct. +type Config struct { + // Mode controls the level of information returned for each package. + Mode LoadMode + + // Context specifies the context for the load operation. + // Cancelling the context may cause [Load] to abort and + // return an error. + Context context.Context + + // Logf is the logger for the config. + // If the user provides a logger, debug logging is enabled. + // If the GOPACKAGESDEBUG environment variable is set to true, + // but the logger is nil, default to log.Printf. + Logf func(format string, args ...any) + + // Dir is the directory in which to run the build system's query tool + // that provides information about the packages. + // If Dir is empty, the tool is run in the current directory. + Dir string + + // Env is the environment to use when invoking the build system's query tool. + // If Env is nil, the current environment is used. + // As in os/exec's Cmd, only the last value in the slice for + // each environment key is used. To specify the setting of only + // a few variables, append to the current environment, as in: + // + // opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386") + // + Env []string + + // BuildFlags is a list of command-line flags to be passed through to + // the build system's query tool. + BuildFlags []string + + // Fset provides source position information for syntax trees and types. + // If Fset is nil, Load will use a new fileset, but preserve Fset's value. + Fset *token.FileSet + + // ParseFile is called to read and parse each file + // when preparing a package's type-checked syntax tree. + // It must be safe to call ParseFile simultaneously from multiple goroutines. + // If ParseFile is nil, the loader will uses parser.ParseFile. + // + // ParseFile should parse the source from src and use filename only for + // recording position information. + // + // An application may supply a custom implementation of ParseFile + // to change the effective file contents or the behavior of the parser, + // or to modify the syntax tree. For example, selectively eliminating + // unwanted function bodies can significantly accelerate type checking. + ParseFile func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) + + // If Tests is set, the loader includes not just the packages + // matching a particular pattern but also any related test packages, + // including test-only variants of the package and the test executable. + // + // For example, when using the go command, loading "fmt" with Tests=true + // returns four packages, with IDs "fmt" (the standard package), + // "fmt [fmt.test]" (the package as compiled for the test), + // "fmt_test" (the test functions from source files in package fmt_test), + // and "fmt.test" (the test binary). + // + // In build systems with explicit names for tests, + // setting Tests may have no effect. + Tests bool + + // Overlay is a mapping from absolute file paths to file contents. + // + // For each map entry, [Load] uses the alternative file + // contents provided by the overlay mapping instead of reading + // from the file system. This mechanism can be used to enable + // editor-integrated tools to correctly analyze the contents + // of modified but unsaved buffers, for example. + // + // The overlay mapping is passed to the build system's driver + // (see "The driver protocol") so that it too can report + // consistent package metadata about unsaved files. However, + // drivers may vary in their level of support for overlays. + Overlay map[string][]byte + + // -- Hidden configuration fields only for use in x/tools -- + + // modFile will be used for -modfile in go command invocations. + modFile string + + // modFlag will be used for -modfile in go command invocations. + modFlag string +} + +// Load loads and returns the Go packages named by the given patterns. +// +// The cfg parameter specifies loading options; nil behaves the same as an empty [Config]. +// +// The [Config.Mode] field is a set of bits that determine what kinds +// of information should be computed and returned. Modes that require +// more information tend to be slower. See [LoadMode] for details +// and important caveats. Its zero value is equivalent to +// [NeedName] | [NeedFiles] | [NeedCompiledGoFiles]. +// +// Each call to Load returns a new set of [Package] instances. +// The Packages and their Imports form a directed acyclic graph. +// +// If the [NeedTypes] mode flag was set, each call to Load uses a new +// [types.Importer], so [types.Object] and [types.Type] values from +// different calls to Load must not be mixed as they will have +// inconsistent notions of type identity. +// +// If any of the patterns was invalid as defined by the +// underlying build system, Load returns an error. +// It may return an empty list of packages without an error, +// for instance for an empty expansion of a valid wildcard. +// Errors associated with a particular package are recorded in the +// corresponding Package's Errors list, and do not cause Load to +// return an error. Clients may need to handle such errors before +// proceeding with further analysis. The [PrintErrors] function is +// provided for convenient display of all errors. +func Load(cfg *Config, patterns ...string) ([]*Package, error) { + ld := newLoader(cfg) + response, external, err := defaultDriver(&ld.Config, patterns...) + if err != nil { + return nil, err + } + + ld.sizes = types.SizesFor(response.Compiler, response.Arch) + if ld.sizes == nil && ld.Config.Mode&(NeedTypes|NeedTypesSizes|NeedTypesInfo) != 0 { + // Type size information is needed but unavailable. + if external { + // An external driver may fail to populate the Compiler/GOARCH fields, + // especially since they are relatively new (see #63700). + // Provide a sensible fallback in this case. + ld.sizes = types.SizesFor("gc", runtime.GOARCH) + if ld.sizes == nil { // gccgo-only arch + ld.sizes = types.SizesFor("gc", "amd64") + } + } else { + // Go list should never fail to deliver accurate size information. + // Reject the whole Load since the error is the same for every package. + return nil, fmt.Errorf("can't determine type sizes for compiler %q on GOARCH %q", + response.Compiler, response.Arch) + } + } + + return ld.refine(response) +} + +// defaultDriver is a driver that implements go/packages' fallback behavior. +// It will try to request to an external driver, if one exists. If there's +// no external driver, or the driver returns a response with NotHandled set, +// defaultDriver will fall back to the go list driver. +// The boolean result indicates that an external driver handled the request. +func defaultDriver(cfg *Config, patterns ...string) (*DriverResponse, bool, error) { + const ( + // windowsArgMax specifies the maximum command line length for + // the Windows' CreateProcess function. + windowsArgMax = 32767 + // maxEnvSize is a very rough estimation of the maximum environment + // size of a user. + maxEnvSize = 16384 + // safeArgMax specifies the maximum safe command line length to use + // by the underlying driver excl. the environment. We choose the Windows' + // ARG_MAX as the starting point because it's one of the lowest ARG_MAX + // constants out of the different supported platforms, + // e.g., https://www.in-ulm.de/~mascheck/various/argmax/#results. + safeArgMax = windowsArgMax - maxEnvSize + ) + chunks, err := splitIntoChunks(patterns, safeArgMax) + if err != nil { + return nil, false, err + } + + if driver := findExternalDriver(cfg); driver != nil { + response, err := callDriverOnChunks(driver, cfg, chunks) + if err != nil { + return nil, false, err + } else if !response.NotHandled { + return response, true, nil + } + // not handled: fall through + } + + // go list fallback + + // Write overlays once, as there are many calls + // to 'go list' (one per chunk plus others too). + overlayFile, cleanupOverlay, err := gocommand.WriteOverlays(cfg.Overlay) + if err != nil { + return nil, false, err + } + defer cleanupOverlay() + + var runner gocommand.Runner // (shared across many 'go list' calls) + driver := func(cfg *Config, patterns []string) (*DriverResponse, error) { + return goListDriver(cfg, &runner, overlayFile, patterns) + } + response, err := callDriverOnChunks(driver, cfg, chunks) + if err != nil { + return nil, false, err + } + return response, false, err +} + +// splitIntoChunks chunks the slice so that the total number of characters +// in a chunk is no longer than argMax. +func splitIntoChunks(patterns []string, argMax int) ([][]string, error) { + if argMax <= 0 { + return nil, errors.New("failed to split patterns into chunks, negative safe argMax value") + } + var chunks [][]string + charsInChunk := 0 + nextChunkStart := 0 + for i, v := range patterns { + vChars := len(v) + if vChars > argMax { + // a single pattern is longer than the maximum safe ARG_MAX, hardly should happen + return nil, errors.New("failed to split patterns into chunks, a pattern is too long") + } + charsInChunk += vChars + 1 // +1 is for a whitespace between patterns that has to be counted too + if charsInChunk > argMax { + chunks = append(chunks, patterns[nextChunkStart:i]) + nextChunkStart = i + charsInChunk = vChars + } + } + // add the last chunk + if nextChunkStart < len(patterns) { + chunks = append(chunks, patterns[nextChunkStart:]) + } + return chunks, nil +} + +func callDriverOnChunks(driver driver, cfg *Config, chunks [][]string) (*DriverResponse, error) { + if len(chunks) == 0 { + return driver(cfg, nil) + } + responses := make([]*DriverResponse, len(chunks)) + errNotHandled := errors.New("driver returned NotHandled") + var g errgroup.Group + for i, chunk := range chunks { + g.Go(func() (err error) { + responses[i], err = driver(cfg, chunk) + if responses[i] != nil && responses[i].NotHandled { + err = errNotHandled + } + return err + }) + } + if err := g.Wait(); err != nil { + if errors.Is(err, errNotHandled) { + return &DriverResponse{NotHandled: true}, nil + } + return nil, err + } + return mergeResponses(responses...), nil +} + +func mergeResponses(responses ...*DriverResponse) *DriverResponse { + if len(responses) == 0 { + return nil + } + response := newDeduper() + response.dr.NotHandled = false + response.dr.Compiler = responses[0].Compiler + response.dr.Arch = responses[0].Arch + response.dr.GoVersion = responses[0].GoVersion + for _, v := range responses { + response.addAll(v) + } + return response.dr +} + +// A Package describes a loaded Go package. +// +// It also defines part of the JSON schema of [DriverResponse]. +// See the package documentation for an overview. +type Package struct { + // ID is a unique identifier for a package, + // in a syntax provided by the underlying build system. + // + // Because the syntax varies based on the build system, + // clients should treat IDs as opaque and not attempt to + // interpret them. + ID string + + // Name is the package name as it appears in the package source code. + Name string + + // PkgPath is the package path as used by the go/types package. + PkgPath string + + // Dir is the directory associated with the package, if it exists. + // + // For packages listed by the go command, this is the directory containing + // the package files. + Dir string + + // Errors contains any errors encountered querying the metadata + // of the package, or while parsing or type-checking its files. + Errors []Error + + // TypeErrors contains the subset of errors produced during type checking. + TypeErrors []types.Error + + // GoFiles lists the absolute file paths of the package's Go source files. + // It may include files that should not be compiled, for example because + // they contain non-matching build tags, are documentary pseudo-files such as + // unsafe/unsafe.go or builtin/builtin.go, or are subject to cgo preprocessing. + GoFiles []string + + // CompiledGoFiles lists the absolute file paths of the package's source + // files that are suitable for type checking. + // This may differ from GoFiles if files are processed before compilation. + CompiledGoFiles []string + + // OtherFiles lists the absolute file paths of the package's non-Go source files, + // including assembly, C, C++, Fortran, Objective-C, SWIG, and so on. + OtherFiles []string + + // EmbedFiles lists the absolute file paths of the package's files + // embedded with go:embed. + EmbedFiles []string + + // EmbedPatterns lists the absolute file patterns of the package's + // files embedded with go:embed. + EmbedPatterns []string + + // IgnoredFiles lists source files that are not part of the package + // using the current build configuration but that might be part of + // the package using other build configurations. + IgnoredFiles []string + + // ExportFile is the absolute path to a file containing type + // information for the package as provided by the build system. + ExportFile string + + // Target is the absolute install path of the .a file, for libraries, + // and of the executable file, for binaries. + Target string + + // Imports maps import paths appearing in the package's Go source files + // to corresponding loaded Packages. + Imports map[string]*Package + + // Module is the module information for the package if it exists. + // + // Note: it may be missing for std and cmd; see Go issue #65816. + Module *Module + + // -- The following fields are not part of the driver JSON schema. -- + + // Types provides type information for the package. + // The NeedTypes LoadMode bit sets this field for packages matching the + // patterns; type information for dependencies may be missing or incomplete, + // unless NeedDeps and NeedImports are also set. + // + // Each call to [Load] returns a consistent set of type + // symbols, as defined by the comment at [types.Identical]. + // Avoid mixing type information from two or more calls to [Load]. + Types *types.Package `json:"-"` + + // Fset provides position information for Types, TypesInfo, and Syntax. + // It is set only when Types is set. + Fset *token.FileSet `json:"-"` + + // IllTyped indicates whether the package or any dependency contains errors. + // It is set only when Types is set. + IllTyped bool `json:"-"` + + // Syntax is the package's syntax trees, for the files listed in CompiledGoFiles. + // + // The NeedSyntax LoadMode bit populates this field for packages matching the patterns. + // If NeedDeps and NeedImports are also set, this field will also be populated + // for dependencies. + // + // Syntax is kept in the same order as CompiledGoFiles, with the caveat that nils are + // removed. If parsing returned nil, Syntax may be shorter than CompiledGoFiles. + Syntax []*ast.File `json:"-"` + + // TypesInfo provides type information about the package's syntax trees. + // It is set only when Syntax is set. + TypesInfo *types.Info `json:"-"` + + // TypesSizes provides the effective size function for types in TypesInfo. + TypesSizes types.Sizes `json:"-"` + + // -- internal -- + + // ForTest is the package under test, if any. + ForTest string + + // depsErrors is the DepsErrors field from the go list response, if any. + depsErrors []*packagesinternal.PackageError +} + +// Module provides module information for a package. +// +// It also defines part of the JSON schema of [DriverResponse]. +// See the package documentation for an overview. +type Module struct { + Path string // module path + Version string // module version + Replace *Module // replaced by this module + Time *time.Time // time version was created + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file used when loading this module, if any + GoVersion string // go version used in module + Error *ModuleError // error loading module +} + +// ModuleError holds errors loading a module. +type ModuleError struct { + Err string // the error itself +} + +func init() { + packagesinternal.GetDepsErrors = func(p any) []*packagesinternal.PackageError { + return p.(*Package).depsErrors + } + packagesinternal.SetModFile = func(config any, value string) { + config.(*Config).modFile = value + } + packagesinternal.SetModFlag = func(config any, value string) { + config.(*Config).modFlag = value + } + packagesinternal.TypecheckCgo = int(typecheckCgo) + packagesinternal.DepsErrors = int(needInternalDepsErrors) +} + +// An Error describes a problem with a package's metadata, syntax, or types. +type Error struct { + Pos string // "file:line:col" or "file:line" or "" or "-" + Msg string + Kind ErrorKind +} + +// ErrorKind describes the source of the error, allowing the user to +// differentiate between errors generated by the driver, the parser, or the +// type-checker. +type ErrorKind int + +const ( + UnknownError ErrorKind = iota + ListError + ParseError + TypeError +) + +func (err Error) Error() string { + pos := err.Pos + if pos == "" { + pos = "-" // like token.Position{}.String() + } + return pos + ": " + err.Msg +} + +// flatPackage is the JSON form of Package +// It drops all the type and syntax fields, and transforms the Imports +// +// TODO(adonovan): identify this struct with Package, effectively +// publishing the JSON protocol. +type flatPackage struct { + ID string + Name string `json:",omitempty"` + PkgPath string `json:",omitempty"` + Errors []Error `json:",omitempty"` + GoFiles []string `json:",omitempty"` + CompiledGoFiles []string `json:",omitempty"` + OtherFiles []string `json:",omitempty"` + EmbedFiles []string `json:",omitempty"` + EmbedPatterns []string `json:",omitempty"` + IgnoredFiles []string `json:",omitempty"` + ExportFile string `json:",omitempty"` + Imports map[string]string `json:",omitempty"` +} + +// MarshalJSON returns the Package in its JSON form. +// For the most part, the structure fields are written out unmodified, and +// the type and syntax fields are skipped. +// The imports are written out as just a map of path to package id. +// The errors are written using a custom type that tries to preserve the +// structure of error types we know about. +// +// This method exists to enable support for additional build systems. It is +// not intended for use by clients of the API and we may change the format. +func (p *Package) MarshalJSON() ([]byte, error) { + flat := &flatPackage{ + ID: p.ID, + Name: p.Name, + PkgPath: p.PkgPath, + Errors: p.Errors, + GoFiles: p.GoFiles, + CompiledGoFiles: p.CompiledGoFiles, + OtherFiles: p.OtherFiles, + EmbedFiles: p.EmbedFiles, + EmbedPatterns: p.EmbedPatterns, + IgnoredFiles: p.IgnoredFiles, + ExportFile: p.ExportFile, + } + if len(p.Imports) > 0 { + flat.Imports = make(map[string]string, len(p.Imports)) + for path, ipkg := range p.Imports { + flat.Imports[path] = ipkg.ID + } + } + return json.Marshal(flat) +} + +// UnmarshalJSON reads in a Package from its JSON format. +// See MarshalJSON for details about the format accepted. +func (p *Package) UnmarshalJSON(b []byte) error { + flat := &flatPackage{} + if err := json.Unmarshal(b, &flat); err != nil { + return err + } + *p = Package{ + ID: flat.ID, + Name: flat.Name, + PkgPath: flat.PkgPath, + Errors: flat.Errors, + GoFiles: flat.GoFiles, + CompiledGoFiles: flat.CompiledGoFiles, + OtherFiles: flat.OtherFiles, + EmbedFiles: flat.EmbedFiles, + EmbedPatterns: flat.EmbedPatterns, + IgnoredFiles: flat.IgnoredFiles, + ExportFile: flat.ExportFile, + } + if len(flat.Imports) > 0 { + p.Imports = make(map[string]*Package, len(flat.Imports)) + for path, id := range flat.Imports { + p.Imports[path] = &Package{ID: id} + } + } + return nil +} + +func (p *Package) String() string { return p.ID } + +// loaderPackage augments Package with state used during the loading phase +type loaderPackage struct { + *Package + importErrors map[string]error // maps each bad import to its error + preds []*loaderPackage // packages that import this one + unfinishedSuccs atomic.Int32 // number of direct imports not yet loaded + color uint8 // for cycle detection + needsrc bool // load from source (Mode >= LoadTypes) + needtypes bool // type information is either requested or depended on + initial bool // package was matched by a pattern + goVersion int // minor version number of go command on PATH +} + +// loader holds the working state of a single call to load. +type loader struct { + pkgs map[string]*loaderPackage // keyed by Package.ID + Config + sizes types.Sizes // non-nil if needed by mode + parseCache map[string]*parseValue + parseCacheMu sync.Mutex + exportMu sync.Mutex // enforces mutual exclusion of exportdata operations + + // Config.Mode contains the implied mode (see impliedLoadMode). + // Implied mode contains all the fields we need the data for. + // In requestedMode there are the actually requested fields. + // We'll zero them out before returning packages to the user. + // This makes it easier for us to get the conditions where + // we need certain modes right. + requestedMode LoadMode +} + +type parseValue struct { + f *ast.File + err error + ready chan struct{} +} + +func newLoader(cfg *Config) *loader { + ld := &loader{ + parseCache: map[string]*parseValue{}, + } + if cfg != nil { + ld.Config = *cfg + // If the user has provided a logger, use it. + ld.Config.Logf = cfg.Logf + } + if ld.Config.Logf == nil { + // If the GOPACKAGESDEBUG environment variable is set to true, + // but the user has not provided a logger, default to log.Printf. + if debug { + ld.Config.Logf = log.Printf + } else { + ld.Config.Logf = func(format string, args ...any) {} + } + } + if ld.Config.Mode == 0 { + ld.Config.Mode = NeedName | NeedFiles | NeedCompiledGoFiles // Preserve zero behavior of Mode for backwards compatibility. + } + if ld.Config.Env == nil { + ld.Config.Env = os.Environ() + } + if ld.Context == nil { + ld.Context = context.Background() + } + if ld.Dir == "" { + if dir, err := os.Getwd(); err == nil { + ld.Dir = dir + } + } + + // Save the actually requested fields. We'll zero them out before returning packages to the user. + ld.requestedMode = ld.Mode + ld.Mode = impliedLoadMode(ld.Mode) + + if ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { + if ld.Fset == nil { + ld.Fset = token.NewFileSet() + } + + // ParseFile is required even in LoadTypes mode + // because we load source if export data is missing. + if ld.ParseFile == nil { + ld.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) { + // We implicitly promise to keep doing ast.Object resolution. :( + const mode = parser.AllErrors | parser.ParseComments + return parser.ParseFile(fset, filename, src, mode) + } + } + } + + return ld +} + +// refine connects the supplied packages into a graph and then adds type +// and syntax information as requested by the LoadMode. +func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { + roots := response.Roots + rootMap := make(map[string]int, len(roots)) + for i, root := range roots { + rootMap[root] = i + } + ld.pkgs = make(map[string]*loaderPackage) + // first pass, fixup and build the map and roots + var initial = make([]*loaderPackage, len(roots)) + for _, pkg := range response.Packages { + rootIndex := -1 + if i, found := rootMap[pkg.ID]; found { + rootIndex = i + } + + // Overlays can invalidate export data. + // TODO(matloob): make this check fine-grained based on dependencies on overlaid files + exportDataInvalid := len(ld.Overlay) > 0 || pkg.ExportFile == "" && pkg.PkgPath != "unsafe" + // This package needs type information if the caller requested types and the package is + // either a root, or it's a non-root and the user requested dependencies ... + needtypes := (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) + // This package needs source if the call requested source (or types info, which implies source) + // and the package is either a root, or itas a non- root and the user requested dependencies... + needsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) || + // ... or if we need types and the exportData is invalid. We fall back to (incompletely) + // typechecking packages from source if they fail to compile. + (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && exportDataInvalid)) && pkg.PkgPath != "unsafe" + lpkg := &loaderPackage{ + Package: pkg, + needtypes: needtypes, + needsrc: needsrc, + goVersion: response.GoVersion, + } + ld.pkgs[lpkg.ID] = lpkg + if rootIndex >= 0 { + initial[rootIndex] = lpkg + lpkg.initial = true + } + } + for i, root := range roots { + if initial[i] == nil { + return nil, fmt.Errorf("root package %v is missing", root) + } + } + + // Materialize the import graph if it is needed (NeedImports), + // or if we'll be using loadPackages (Need{Syntax|Types|TypesInfo}). + var leaves []*loaderPackage // packages with no unfinished successors + if ld.Mode&(NeedImports|NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { + const ( + white = 0 // new + grey = 1 // in progress + black = 2 // complete + ) + + // visit traverses the import graph, depth-first, + // and materializes the graph as Packages.Imports. + // + // Valid imports are saved in the Packages.Import map. + // Invalid imports (cycles and missing nodes) are saved in the importErrors map. + // Thus, even in the presence of both kinds of errors, + // the Import graph remains a DAG. + // + // visit returns whether the package needs src or has a transitive + // dependency on a package that does. These are the only packages + // for which we load source code. + var stack []*loaderPackage + var visit func(from, lpkg *loaderPackage) bool + visit = func(from, lpkg *loaderPackage) bool { + if lpkg.color == grey { + panic("internal error: grey node") + } + if lpkg.color == white { + lpkg.color = grey + stack = append(stack, lpkg) // push + stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports + lpkg.Imports = make(map[string]*Package, len(stubs)) + for importPath, ipkg := range stubs { + var importErr error + imp := ld.pkgs[ipkg.ID] + if imp == nil { + // (includes package "C" when DisableCgo) + importErr = fmt.Errorf("missing package: %q", ipkg.ID) + } else if imp.color == grey { + importErr = fmt.Errorf("import cycle: %s", stack) + } + if importErr != nil { + if lpkg.importErrors == nil { + lpkg.importErrors = make(map[string]error) + } + lpkg.importErrors[importPath] = importErr + continue + } + + if visit(lpkg, imp) { + lpkg.needsrc = true + } + lpkg.Imports[importPath] = imp.Package + } + + // -- postorder -- + + // Complete type information is required for the + // immediate dependencies of each source package. + if lpkg.needsrc && ld.Mode&NeedTypes != 0 { + for _, ipkg := range lpkg.Imports { + ld.pkgs[ipkg.ID].needtypes = true + } + } + + // NeedTypeSizes causes TypeSizes to be set even + // on packages for which types aren't needed. + if ld.Mode&NeedTypesSizes != 0 { + lpkg.TypesSizes = ld.sizes + } + + // Add packages with no imports directly to the queue of leaves. + if len(lpkg.Imports) == 0 { + leaves = append(leaves, lpkg) + } + + stack = stack[:len(stack)-1] // pop + lpkg.color = black + } + + // Add edge from predecessor. + if from != nil { + from.unfinishedSuccs.Add(+1) // incref + lpkg.preds = append(lpkg.preds, from) + } + + return lpkg.needsrc + } + + // For each initial package, create its import DAG. + for _, lpkg := range initial { + visit(nil, lpkg) + } + + } else { + // !NeedImports: drop the stub (ID-only) import packages + // that we are not even going to try to resolve. + for _, lpkg := range initial { + lpkg.Imports = nil + } + } + + // Load type data and syntax if needed, starting at + // the initial packages (roots of the import DAG). + if ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { + + // We avoid using g.SetLimit to limit concurrency as + // it makes g.Go stop accepting work, which prevents + // workers from enqeuing, and thus finishing, and thus + // allowing the group to make progress: deadlock. + // + // Instead we use the ioLimit and cpuLimit semaphores. + g, _ := errgroup.WithContext(ld.Context) + + // enqueues adds a package to the type-checking queue. + // It must have no unfinished successors. + var enqueue func(*loaderPackage) + enqueue = func(lpkg *loaderPackage) { + g.Go(func() error { + // Parse and type-check. + ld.loadPackage(lpkg) + + // Notify each waiting predecessor, + // and enqueue it when it becomes a leaf. + for _, pred := range lpkg.preds { + if pred.unfinishedSuccs.Add(-1) == 0 { // decref + enqueue(pred) + } + } + + return nil + }) + } + + // Load leaves first, adding new packages + // to the queue as they become leaves. + for _, leaf := range leaves { + enqueue(leaf) + } + + if err := g.Wait(); err != nil { + return nil, err // cancelled + } + } + + // If the context is done, return its error and + // throw out [likely] incomplete packages. + if err := ld.Context.Err(); err != nil { + return nil, err + } + + result := make([]*Package, len(initial)) + for i, lpkg := range initial { + result[i] = lpkg.Package + } + for i := range ld.pkgs { + // Clear all unrequested fields, + // to catch programs that use more than they request. + if ld.requestedMode&NeedName == 0 { + ld.pkgs[i].Name = "" + ld.pkgs[i].PkgPath = "" + } + if ld.requestedMode&NeedFiles == 0 { + ld.pkgs[i].GoFiles = nil + ld.pkgs[i].OtherFiles = nil + ld.pkgs[i].IgnoredFiles = nil + } + if ld.requestedMode&NeedEmbedFiles == 0 { + ld.pkgs[i].EmbedFiles = nil + } + if ld.requestedMode&NeedEmbedPatterns == 0 { + ld.pkgs[i].EmbedPatterns = nil + } + if ld.requestedMode&NeedCompiledGoFiles == 0 { + ld.pkgs[i].CompiledGoFiles = nil + } + if ld.requestedMode&NeedImports == 0 { + ld.pkgs[i].Imports = nil + } + if ld.requestedMode&NeedExportFile == 0 { + ld.pkgs[i].ExportFile = "" + } + if ld.requestedMode&NeedTypes == 0 { + ld.pkgs[i].Types = nil + ld.pkgs[i].IllTyped = false + } + if ld.requestedMode&NeedSyntax == 0 { + ld.pkgs[i].Syntax = nil + } + if ld.requestedMode&(NeedSyntax|NeedTypes|NeedTypesInfo) == 0 { + ld.pkgs[i].Fset = nil + } + if ld.requestedMode&NeedTypesInfo == 0 { + ld.pkgs[i].TypesInfo = nil + } + if ld.requestedMode&NeedTypesSizes == 0 { + ld.pkgs[i].TypesSizes = nil + } + if ld.requestedMode&NeedModule == 0 { + ld.pkgs[i].Module = nil + } + } + + return result, nil +} + +// loadPackage loads/parses/typechecks the specified package. +// It must be called only once per Package, +// after immediate dependencies are loaded. +// Precondition: ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0. +func (ld *loader) loadPackage(lpkg *loaderPackage) { + if lpkg.PkgPath == "unsafe" { + // Fill in the blanks to avoid surprises. + lpkg.Types = types.Unsafe + lpkg.Fset = ld.Fset + lpkg.Syntax = []*ast.File{} + lpkg.TypesInfo = new(types.Info) + lpkg.TypesSizes = ld.sizes + return + } + + // Call NewPackage directly with explicit name. + // This avoids skew between golist and go/types when the files' + // package declarations are inconsistent. + lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name) + lpkg.Fset = ld.Fset + + // Start shutting down if the context is done and do not load + // source or export data files. + // Packages that import this one will have ld.Context.Err() != nil. + // ld.Context.Err() will be returned later by refine. + if ld.Context.Err() != nil { + return + } + + // Subtle: we populate all Types fields with an empty Package + // before loading export data so that export data processing + // never has to create a types.Package for an indirect dependency, + // which would then require that such created packages be explicitly + // inserted back into the Import graph as a final step after export data loading. + // (Hence this return is after the Types assignment.) + // The Diamond test exercises this case. + if !lpkg.needtypes && !lpkg.needsrc { + return + } + + // TODO(adonovan): this condition looks wrong: + // I think it should be lpkg.needtypes && !lpg.needsrc, + // so that NeedSyntax without NeedTypes can be satisfied by export data. + if !lpkg.needsrc { + if err := ld.loadFromExportData(lpkg); err != nil { + lpkg.Errors = append(lpkg.Errors, Error{ + Pos: "-", + Msg: err.Error(), + Kind: UnknownError, // e.g. can't find/open/parse export data + }) + } + return // not a source package, don't get syntax trees + } + + appendError := func(err error) { + // Convert various error types into the one true Error. + var errs []Error + switch err := err.(type) { + case Error: + // from driver + errs = append(errs, err) + + case *os.PathError: + // from parser + errs = append(errs, Error{ + Pos: err.Path + ":1", + Msg: err.Err.Error(), + Kind: ParseError, + }) + + case scanner.ErrorList: + // from parser + for _, err := range err { + errs = append(errs, Error{ + Pos: err.Pos.String(), + Msg: err.Msg, + Kind: ParseError, + }) + } + + case types.Error: + // from type checker + lpkg.TypeErrors = append(lpkg.TypeErrors, err) + errs = append(errs, Error{ + Pos: err.Fset.Position(err.Pos).String(), + Msg: err.Msg, + Kind: TypeError, + }) + + default: + // unexpected impoverished error from parser? + errs = append(errs, Error{ + Pos: "-", + Msg: err.Error(), + Kind: UnknownError, + }) + + // If you see this error message, please file a bug. + log.Printf("internal error: error %q (%T) without position", err, err) + } + + lpkg.Errors = append(lpkg.Errors, errs...) + } + + // If the go command on the PATH is newer than the runtime, + // then the go/{scanner,ast,parser,types} packages from the + // standard library may be unable to process the files + // selected by go list. + // + // There is currently no way to downgrade the effective + // version of the go command (see issue 52078), so we proceed + // with the newer go command but, in case of parse or type + // errors, we emit an additional diagnostic. + // + // See: + // - golang.org/issue/52078 (flag to set release tags) + // - golang.org/issue/50825 (gopls legacy version support) + // - golang.org/issue/55883 (go/packages confusing error) + // + // Should we assert a hard minimum of (currently) go1.16 here? + var runtimeVersion int + if _, err := fmt.Sscanf(runtime.Version(), "go1.%d", &runtimeVersion); err == nil && runtimeVersion < lpkg.goVersion { + defer func() { + if len(lpkg.Errors) > 0 { + appendError(Error{ + Pos: "-", + Msg: fmt.Sprintf("This application uses version go1.%d of the source-processing packages but runs version go1.%d of 'go list'. It may fail to process source files that rely on newer language features. If so, rebuild the application using a newer version of Go.", runtimeVersion, lpkg.goVersion), + Kind: UnknownError, + }) + } + }() + } + + if ld.Config.Mode&NeedTypes != 0 && len(lpkg.CompiledGoFiles) == 0 && lpkg.ExportFile != "" { + // The config requested loading sources and types, but sources are missing. + // Add an error to the package and fall back to loading from export data. + appendError(Error{"-", fmt.Sprintf("sources missing for package %s", lpkg.ID), ParseError}) + _ = ld.loadFromExportData(lpkg) // ignore any secondary errors + + return // can't get syntax trees for this package + } + + files, errs := ld.parseFiles(lpkg.CompiledGoFiles) + for _, err := range errs { + appendError(err) + } + + lpkg.Syntax = files + if ld.Config.Mode&(NeedTypes|NeedTypesInfo) == 0 { + return + } + + // Start shutting down if the context is done and do not type check. + // Packages that import this one will have ld.Context.Err() != nil. + // ld.Context.Err() will be returned later by refine. + if ld.Context.Err() != nil { + return + } + + // Populate TypesInfo only if needed, as it + // causes the type checker to work much harder. + if ld.Config.Mode&NeedTypesInfo != 0 { + lpkg.TypesInfo = &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + FileVersions: make(map[*ast.File]string), + } + } + lpkg.TypesSizes = ld.sizes + + importer := importerFunc(func(path string) (*types.Package, error) { + if path == "unsafe" { + return types.Unsafe, nil + } + + // The imports map is keyed by import path. + ipkg := lpkg.Imports[path] + if ipkg == nil { + if err := lpkg.importErrors[path]; err != nil { + return nil, err + } + // There was skew between the metadata and the + // import declarations, likely due to an edit + // race, or because the ParseFile feature was + // used to supply alternative file contents. + return nil, fmt.Errorf("no metadata for %s", path) + } + + if ipkg.Types != nil && ipkg.Types.Complete() { + return ipkg.Types, nil + } + log.Fatalf("internal error: package %q without types was imported from %q", path, lpkg) + panic("unreachable") + }) + + // type-check + tc := &types.Config{ + Importer: importer, + + // Type-check bodies of functions only in initial packages. + // Example: for import graph A->B->C and initial packages {A,C}, + // we can ignore function bodies in B. + IgnoreFuncBodies: ld.Mode&NeedDeps == 0 && !lpkg.initial, + + Error: appendError, + Sizes: ld.sizes, // may be nil + } + if lpkg.Module != nil && lpkg.Module.GoVersion != "" { + tc.GoVersion = "go" + lpkg.Module.GoVersion + } + if (ld.Mode & typecheckCgo) != 0 { + if !typesinternal.SetUsesCgo(tc) { + appendError(Error{ + Msg: "typecheckCgo requires Go 1.15+", + Kind: ListError, + }) + return + } + } + + // Type-checking is CPU intensive. + cpuLimit <- unit{} // acquire a token + defer func() { <-cpuLimit }() // release a token + + typErr := types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) + lpkg.importErrors = nil // no longer needed + + // In go/types go1.21 and go1.22, Checker.Files failed fast with a + // a "too new" error, without calling tc.Error and without + // proceeding to type-check the package (#66525). + // We rely on the runtimeVersion error to give the suggested remedy. + if typErr != nil && len(lpkg.Errors) == 0 && len(lpkg.Syntax) > 0 { + if msg := typErr.Error(); strings.HasPrefix(msg, "package requires newer Go version") { + appendError(types.Error{ + Fset: ld.Fset, + Pos: lpkg.Syntax[0].Package, + Msg: msg, + }) + } + } + + // If !Cgo, the type-checker uses FakeImportC mode, so + // it doesn't invoke the importer for import "C", + // nor report an error for the import, + // or for any undefined C.f reference. + // We must detect this explicitly and correctly + // mark the package as IllTyped (by reporting an error). + // TODO(adonovan): if these errors are annoying, + // we could just set IllTyped quietly. + if tc.FakeImportC { + outer: + for _, f := range lpkg.Syntax { + for _, imp := range f.Imports { + if imp.Path.Value == `"C"` { + err := types.Error{Fset: ld.Fset, Pos: imp.Pos(), Msg: `import "C" ignored`} + appendError(err) + break outer + } + } + } + } + + // If types.Checker.Files had an error that was unreported, + // make sure to report the unknown error so the package is illTyped. + if typErr != nil && len(lpkg.Errors) == 0 { + appendError(typErr) + } + + // Record accumulated errors. + illTyped := len(lpkg.Errors) > 0 + if !illTyped { + for _, imp := range lpkg.Imports { + if imp.IllTyped { + illTyped = true + break + } + } + } + lpkg.IllTyped = illTyped +} + +// An importFunc is an implementation of the single-method +// types.Importer interface based on a function value. +type importerFunc func(path string) (*types.Package, error) + +func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) } + +// We use a counting semaphore to limit +// the number of parallel I/O calls or CPU threads per process. +var ( + ioLimit = make(chan unit, 20) + cpuLimit = make(chan unit, runtime.GOMAXPROCS(0)) +) + +func (ld *loader) parseFile(filename string) (*ast.File, error) { + ld.parseCacheMu.Lock() + v, ok := ld.parseCache[filename] + if ok { + // cache hit + ld.parseCacheMu.Unlock() + <-v.ready + } else { + // cache miss + v = &parseValue{ready: make(chan struct{})} + ld.parseCache[filename] = v + ld.parseCacheMu.Unlock() + + var src []byte + for f, contents := range ld.Config.Overlay { + // TODO(adonovan): Inefficient for large overlays. + // Do an exact name-based map lookup + // (for nonexistent files) followed by a + // FileID-based map lookup (for existing ones). + if sameFile(f, filename) { + src = contents + break + } + } + var err error + if src == nil { + ioLimit <- unit{} // acquire a token + src, err = os.ReadFile(filename) + <-ioLimit // release a token + } + if err != nil { + v.err = err + } else { + // Parsing is CPU intensive. + cpuLimit <- unit{} // acquire a token + v.f, v.err = ld.ParseFile(ld.Fset, filename, src) + <-cpuLimit // release a token + } + + close(v.ready) + } + return v.f, v.err +} + +// parseFiles reads and parses the Go source files and returns the ASTs +// of the ones that could be at least partially parsed, along with a +// list of I/O and parse errors encountered. +// +// Because files are scanned in parallel, the token.Pos +// positions of the resulting ast.Files are not ordered. +func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { + var ( + n = len(filenames) + parsed = make([]*ast.File, n) + errors = make([]error, n) + ) + var g errgroup.Group + for i, filename := range filenames { + // This creates goroutines unnecessarily in the + // cache-hit case, but that case is uncommon. + g.Go(func() error { + parsed[i], errors[i] = ld.parseFile(filename) + return nil + }) + } + g.Wait() + + // Eliminate nils, preserving order. + var o int + for _, f := range parsed { + if f != nil { + parsed[o] = f + o++ + } + } + parsed = parsed[:o] + + o = 0 + for _, err := range errors { + if err != nil { + errors[o] = err + o++ + } + } + errors = errors[:o] + + return parsed, errors +} + +// sameFile returns true if x and y have the same basename and denote +// the same file. +func sameFile(x, y string) bool { + if x == y { + // It could be the case that y doesn't exist. + // For instance, it may be an overlay file that + // hasn't been written to disk. To handle that case + // let x == y through. (We added the exact absolute path + // string to the CompiledGoFiles list, so the unwritten + // overlay case implies x==y.) + return true + } + if strings.EqualFold(filepath.Base(x), filepath.Base(y)) { // (optimisation) + if xi, err := os.Stat(x); err == nil { + if yi, err := os.Stat(y); err == nil { + return os.SameFile(xi, yi) + } + } + } + return false +} + +// loadFromExportData ensures that type information is present for the specified +// package, loading it from an export data file on the first request. +// On success it sets lpkg.Types to a new Package. +func (ld *loader) loadFromExportData(lpkg *loaderPackage) error { + if lpkg.PkgPath == "" { + log.Fatalf("internal error: Package %s has no PkgPath", lpkg) + } + + // Because gcexportdata.Read has the potential to create or + // modify the types.Package for each node in the transitive + // closure of dependencies of lpkg, all exportdata operations + // must be sequential. (Finer-grained locking would require + // changes to the gcexportdata API.) + // + // The exportMu lock guards the lpkg.Types field and the + // types.Package it points to, for each loaderPackage in the graph. + // + // Not all accesses to Package.Pkg need to be protected by exportMu: + // graph ordering ensures that direct dependencies of source + // packages are fully loaded before the importer reads their Pkg field. + ld.exportMu.Lock() + defer ld.exportMu.Unlock() + + if tpkg := lpkg.Types; tpkg != nil && tpkg.Complete() { + return nil // cache hit + } + + lpkg.IllTyped = true // fail safe + + if lpkg.ExportFile == "" { + // Errors while building export data will have been printed to stderr. + return fmt.Errorf("no export data file") + } + f, err := os.Open(lpkg.ExportFile) + if err != nil { + return err + } + defer f.Close() + + // Read gc export data. + // + // We don't currently support gccgo export data because all + // underlying workspaces use the gc toolchain. (Even build + // systems that support gccgo don't use it for workspace + // queries.) + r, err := gcexportdata.NewReader(f) + if err != nil { + return fmt.Errorf("reading %s: %v", lpkg.ExportFile, err) + } + + // Build the view. + // + // The gcexportdata machinery has no concept of package ID. + // It identifies packages by their PkgPath, which although not + // globally unique is unique within the scope of one invocation + // of the linker, type-checker, or gcexportdata. + // + // So, we must build a PkgPath-keyed view of the global + // (conceptually ID-keyed) cache of packages and pass it to + // gcexportdata. The view must contain every existing + // package that might possibly be mentioned by the + // current package---its transitive closure. + // + // In loadPackage, we unconditionally create a types.Package for + // each dependency so that export data loading does not + // create new ones. + // + // TODO(adonovan): it would be simpler and more efficient + // if the export data machinery invoked a callback to + // get-or-create a package instead of a map. + // + view := make(map[string]*types.Package) // view seen by gcexportdata + seen := make(map[*loaderPackage]bool) // all visited packages + var visit func(pkgs map[string]*Package) + visit = func(pkgs map[string]*Package) { + for _, p := range pkgs { + lpkg := ld.pkgs[p.ID] + if !seen[lpkg] { + seen[lpkg] = true + view[lpkg.PkgPath] = lpkg.Types + visit(lpkg.Imports) + } + } + } + visit(lpkg.Imports) + + viewLen := len(view) + 1 // adding the self package + // Parse the export data. + // (May modify incomplete packages in view but not create new ones.) + tpkg, err := gcexportdata.Read(r, ld.Fset, view, lpkg.PkgPath) + if err != nil { + return fmt.Errorf("reading %s: %v", lpkg.ExportFile, err) + } + if _, ok := view["go.shape"]; ok { + // Account for the pseudopackage "go.shape" that gets + // created by generic code. + viewLen++ + } + if viewLen != len(view) { + log.Panicf("golang.org/x/tools/go/packages: unexpected new packages during load of %s", lpkg.PkgPath) + } + + lpkg.Types = tpkg + lpkg.IllTyped = false + return nil +} + +// impliedLoadMode returns loadMode with its dependencies. +func impliedLoadMode(loadMode LoadMode) LoadMode { + if loadMode&(NeedDeps|NeedTypes|NeedTypesInfo) != 0 { + // All these things require knowing the import graph. + loadMode |= NeedImports + } + if loadMode&NeedTypes != 0 { + // Types require the GoVersion from Module. + loadMode |= NeedModule + } + + return loadMode +} + +func usesExportData(cfg *Config) bool { + return cfg.Mode&NeedExportFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0 +} + +type unit struct{} diff --git a/vendor/golang.org/x/tools/go/packages/visit.go b/vendor/golang.org/x/tools/go/packages/visit.go new file mode 100644 index 000000000..df14ffd94 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/visit.go @@ -0,0 +1,68 @@ +// Copyright 2018 The Go 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 packages + +import ( + "fmt" + "os" + "sort" +) + +// Visit visits all the packages in the import graph whose roots are +// pkgs, calling the optional pre function the first time each package +// is encountered (preorder), and the optional post function after a +// package's dependencies have been visited (postorder). +// The boolean result of pre(pkg) determines whether +// the imports of package pkg are visited. +func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { + seen := make(map[*Package]bool) + var visit func(*Package) + visit = func(pkg *Package) { + if !seen[pkg] { + seen[pkg] = true + + if pre == nil || pre(pkg) { + paths := make([]string, 0, len(pkg.Imports)) + for path := range pkg.Imports { + paths = append(paths, path) + } + sort.Strings(paths) // Imports is a map, this makes visit stable + for _, path := range paths { + visit(pkg.Imports[path]) + } + } + + if post != nil { + post(pkg) + } + } + } + for _, pkg := range pkgs { + visit(pkg) + } +} + +// PrintErrors prints to os.Stderr the accumulated errors of all +// packages in the import graph rooted at pkgs, dependencies first. +// PrintErrors returns the number of errors printed. +func PrintErrors(pkgs []*Package) int { + var n int + errModules := make(map[*Module]bool) + Visit(pkgs, nil, func(pkg *Package) { + for _, err := range pkg.Errors { + fmt.Fprintln(os.Stderr, err) + n++ + } + + // Print pkg.Module.Error once if present. + mod := pkg.Module + if mod != nil && mod.Error != nil && !errModules[mod] { + errModules[mod] = true + fmt.Fprintln(os.Stderr, mod.Error.Err) + n++ + } + }) + return n +} diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go new file mode 100644 index 000000000..16ed3c178 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -0,0 +1,817 @@ +// Copyright 2018 The Go 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 objectpath defines a naming scheme for types.Objects +// (that is, named entities in Go programs) relative to their enclosing +// package. +// +// Type-checker objects are canonical, so they are usually identified by +// their address in memory (a pointer), but a pointer has meaning only +// within one address space. By contrast, objectpath names allow the +// identity of an object to be sent from one program to another, +// establishing a correspondence between types.Object variables that are +// distinct but logically equivalent. +// +// A single object may have multiple paths. In this example, +// +// type A struct{ X int } +// type B A +// +// the field X has two paths due to its membership of both A and B. +// The For(obj) function always returns one of these paths, arbitrarily +// but consistently. +package objectpath + +import ( + "fmt" + "go/types" + "strconv" + "strings" + + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/typesinternal" +) + +// TODO(adonovan): think about generic aliases. + +// A Path is an opaque name that identifies a types.Object +// relative to its package. Conceptually, the name consists of a +// sequence of destructuring operations applied to the package scope +// to obtain the original object. +// The name does not include the package itself. +type Path string + +// Encoding +// +// An object path is a textual and (with training) human-readable encoding +// of a sequence of destructuring operators, starting from a types.Package. +// The sequences represent a path through the package/object/type graph. +// We classify these operators by their type: +// +// PO package->object Package.Scope.Lookup +// OT object->type Object.Type +// TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying,Rhs} [EKPRUTrCa] +// TO type->object Type.{At,Field,Method,Obj} [AFMO] +// +// All valid paths start with a package and end at an object +// and thus may be defined by the regular language: +// +// objectpath = PO (OT TT* TO)* +// +// The concrete encoding follows directly: +// - The only PO operator is Package.Scope.Lookup, which requires an identifier. +// - The only OT operator is Object.Type, +// which we encode as '.' because dot cannot appear in an identifier. +// - The TT operators are encoded as [EKPRUTrCa]; +// two of these ({,Recv}TypeParams) require an integer operand, +// which is encoded as a string of decimal digits. +// - The TO operators are encoded as [AFMO]; +// three of these (At,Field,Method) require an integer operand, +// which is encoded as a string of decimal digits. +// These indices are stable across different representations +// of the same package, even source and export data. +// The indices used are implementation specific and may not correspond to +// the argument to the go/types function. +// +// In the example below, +// +// package p +// +// type T interface { +// f() (a string, b struct{ X int }) +// } +// +// field X has the path "T.UM0.RA1.F0", +// representing the following sequence of operations: +// +// p.Lookup("T") T +// .Type().Underlying().Method(0). f +// .Type().Results().At(1) b +// .Type().Field(0) X +// +// The encoding is not maximally compact---every R or P is +// followed by an A, for example---but this simplifies the +// encoder and decoder. +const ( + // object->type operators + opType = '.' // .Type() (Object) + + // type->type operators + opElem = 'E' // .Elem() (Pointer, Slice, Array, Chan, Map) + opKey = 'K' // .Key() (Map) + opParams = 'P' // .Params() (Signature) + opResults = 'R' // .Results() (Signature) + opUnderlying = 'U' // .Underlying() (Named) + opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) + opRecvTypeParam = 'r' // .RecvTypeParams.At(i) (Signature) + opConstraint = 'C' // .Constraint() (TypeParam) + opRhs = 'a' // .Rhs() (Alias) + + // type->object operators + opAt = 'A' // .At(i) (Tuple) + opField = 'F' // .Field(i) (Struct) + opMethod = 'M' // .Method(i) (Named or Interface; not Struct: "promoted" names are ignored) + opObj = 'O' // .Obj() (Named, TypeParam) +) + +// For is equivalent to new(Encoder).For(obj). +// +// It may be more efficient to reuse a single Encoder across several calls. +func For(obj types.Object) (Path, error) { + return new(Encoder).For(obj) +} + +// An Encoder amortizes the cost of encoding the paths of multiple objects. +// The zero value of an Encoder is ready to use. +type Encoder struct { + scopeMemo map[*types.Scope][]types.Object // memoization of scopeObjects +} + +// For returns the path to an object relative to its package, +// or an error if the object is not accessible from the package's Scope. +// +// The For function guarantees to return a path only for the following objects: +// - package-level types +// - exported package-level non-types +// - methods +// - parameter and result variables +// - struct fields +// These objects are sufficient to define the API of their package. +// The objects described by a package's export data are drawn from this set. +// +// The set of objects accessible from a package's Scope depends on +// whether the package was produced by type-checking syntax, or +// reading export data; the latter may have a smaller Scope since +// export data trims objects that are not reachable from an exported +// declaration. For example, the For function will return a path for +// an exported method of an unexported type that is not reachable +// from any public declaration; this path will cause the Object +// function to fail if called on a package loaded from export data. +// TODO(adonovan): is this a bug or feature? Should this package +// compute accessibility in the same way? +// +// For does not return a path for predeclared names, imported package +// names, local names, and unexported package-level names (except +// types). +// +// Example: given this definition, +// +// package p +// +// type T interface { +// f() (a string, b struct{ X int }) +// } +// +// For(X) would return a path that denotes the following sequence of operations: +// +// p.Scope().Lookup("T") (TypeName T) +// .Type().Underlying().Method(0). (method Func f) +// .Type().Results().At(1) (field Var b) +// .Type().Field(0) (field Var X) +// +// where p is the package (*types.Package) to which X belongs. +func (enc *Encoder) For(obj types.Object) (Path, error) { + pkg := obj.Pkg() + + // This table lists the cases of interest. + // + // Object Action + // ------ ------ + // nil reject + // builtin reject + // pkgname reject + // label reject + // var + // package-level accept + // func param/result accept + // local reject + // struct field accept + // const + // package-level accept + // local reject + // func + // package-level accept + // init functions reject + // concrete method accept + // interface method accept + // type + // package-level accept + // local reject + // + // The only accessible package-level objects are members of pkg itself. + // + // The cases are handled in four steps: + // + // 1. reject nil and builtin + // 2. accept package-level objects + // 3. reject obviously invalid objects + // 4. search the API for the path to the param/result/field/method. + + // 1. reference to nil or builtin? + if pkg == nil { + return "", fmt.Errorf("predeclared %s has no path", obj) + } + scope := pkg.Scope() + + // 2. package-level object? + if scope.Lookup(obj.Name()) == obj { + // Only exported objects (and non-exported types) have a path. + // Non-exported types may be referenced by other objects. + if _, ok := obj.(*types.TypeName); !ok && !obj.Exported() { + return "", fmt.Errorf("no path for non-exported %v", obj) + } + return Path(obj.Name()), nil + } + + // 3. Not a package-level object. + // Reject obviously non-viable cases. + switch obj := obj.(type) { + case *types.TypeName: + if _, ok := types.Unalias(obj.Type()).(*types.TypeParam); !ok { + // With the exception of type parameters, only package-level type names + // have a path. + return "", fmt.Errorf("no path for %v", obj) + } + case *types.Const, // Only package-level constants have a path. + *types.Label, // Labels are function-local. + *types.PkgName: // PkgNames are file-local. + return "", fmt.Errorf("no path for %v", obj) + + case *types.Var: + // Could be: + // - a field (obj.IsField()) + // - a func parameter or result + // - a local var. + // Sadly there is no way to distinguish + // a param/result from a local + // so we must proceed to the find. + + case *types.Func: + // A func, if not package-level, must be a method. + if recv := obj.Type().(*types.Signature).Recv(); recv == nil { + return "", fmt.Errorf("func is not a method: %v", obj) + } + + if path, ok := enc.concreteMethod(obj); ok { + // Fast path for concrete methods that avoids looping over scope. + return path, nil + } + + default: + panic(obj) + } + + // 4. Search the API for the path to the var (field/param/result) or method. + + // First inspect package-level named types. + // In the presence of path aliases, these give + // the best paths because non-types may + // refer to types, but not the reverse. + empty := make([]byte, 0, 48) // initial space + objs := enc.scopeObjects(scope) + for _, o := range objs { + tname, ok := o.(*types.TypeName) + if !ok { + continue // handle non-types in second pass + } + + path := append(empty, o.Name()...) + path = append(path, opType) + + T := o.Type() + if alias, ok := T.(*types.Alias); ok { + if r := findTypeParam(obj, aliases.TypeParams(alias), path, opTypeParam); r != nil { + return Path(r), nil + } + if r := find(obj, aliases.Rhs(alias), append(path, opRhs)); r != nil { + return Path(r), nil + } + + } else if tname.IsAlias() { + // legacy alias + if r := find(obj, T, path); r != nil { + return Path(r), nil + } + + } else if named, ok := T.(*types.Named); ok { + // defined (named) type + if r := findTypeParam(obj, named.TypeParams(), path, opTypeParam); r != nil { + return Path(r), nil + } + if r := find(obj, named.Underlying(), append(path, opUnderlying)); r != nil { + return Path(r), nil + } + } + } + + // Then inspect everything else: + // non-types, and declared methods of defined types. + for _, o := range objs { + path := append(empty, o.Name()...) + if _, ok := o.(*types.TypeName); !ok { + if o.Exported() { + // exported non-type (const, var, func) + if r := find(obj, o.Type(), append(path, opType)); r != nil { + return Path(r), nil + } + } + continue + } + + // Inspect declared methods of defined types. + if T, ok := types.Unalias(o.Type()).(*types.Named); ok { + path = append(path, opType) + // The method index here is always with respect + // to the underlying go/types data structures, + // which ultimately derives from source order + // and must be preserved by export data. + for i := 0; i < T.NumMethods(); i++ { + m := T.Method(i) + path2 := appendOpArg(path, opMethod, i) + if m == obj { + return Path(path2), nil // found declared method + } + if r := find(obj, m.Type(), append(path2, opType)); r != nil { + return Path(r), nil + } + } + } + } + + return "", fmt.Errorf("can't find path for %v in %s", obj, pkg.Path()) +} + +func appendOpArg(path []byte, op byte, arg int) []byte { + path = append(path, op) + path = strconv.AppendInt(path, int64(arg), 10) + return path +} + +// concreteMethod returns the path for meth, which must have a non-nil receiver. +// The second return value indicates success and may be false if the method is +// an interface method or if it is an instantiated method. +// +// This function is just an optimization that avoids the general scope walking +// approach. You are expected to fall back to the general approach if this +// function fails. +func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { + // Concrete methods can only be declared on package-scoped named types. For + // that reason we can skip the expensive walk over the package scope: the + // path will always be package -> named type -> method. We can trivially get + // the type name from the receiver, and only have to look over the type's + // methods to find the method index. + // + // Methods on generic types require special consideration, however. Consider + // the following package: + // + // L1: type S[T any] struct{} + // L2: func (recv S[A]) Foo() { recv.Bar() } + // L3: func (recv S[B]) Bar() { } + // L4: type Alias = S[int] + // L5: func _[T any]() { var s S[int]; s.Foo() } + // + // The receivers of methods on generic types are instantiations. L2 and L3 + // instantiate S with the type-parameters A and B, which are scoped to the + // respective methods. L4 and L5 each instantiate S with int. Each of these + // instantiations has its own method set, full of methods (and thus objects) + // with receivers whose types are the respective instantiations. In other + // words, we have + // + // S[A].Foo, S[A].Bar + // S[B].Foo, S[B].Bar + // S[int].Foo, S[int].Bar + // + // We may thus be trying to produce object paths for any of these objects. + // + // S[A].Foo and S[B].Bar are the origin methods, and their paths are S.Foo + // and S.Bar, which are the paths that this function naturally produces. + // + // S[A].Bar, S[B].Foo, and both methods on S[int] are instantiations that + // don't correspond to the origin methods. For S[int], this is significant. + // The most precise object path for S[int].Foo, for example, is Alias.Foo, + // not S.Foo. Our function, however, would produce S.Foo, which would + // resolve to a different object. + // + // For S[A].Bar and S[B].Foo it could be argued that S.Bar and S.Foo are + // still the correct paths, since only the origin methods have meaningful + // paths. But this is likely only true for trivial cases and has edge cases. + // Since this function is only an optimization, we err on the side of giving + // up, deferring to the slower but definitely correct algorithm. Most users + // of objectpath will only be giving us origin methods, anyway, as referring + // to instantiated methods is usually not useful. + + if meth.Origin() != meth { + return "", false + } + + _, named := typesinternal.ReceiverNamed(meth.Type().(*types.Signature).Recv()) + if named == nil { + return "", false + } + + if types.IsInterface(named) { + // Named interfaces don't have to be package-scoped + // + // TODO(dominikh): opt: if scope.Lookup(name) == named, then we can apply this optimization to interface + // methods, too, I think. + return "", false + } + + // Preallocate space for the name, opType, opMethod, and some digits. + name := named.Obj().Name() + path := make([]byte, 0, len(name)+8) + path = append(path, name...) + path = append(path, opType) + + // Method indices are w.r.t. the go/types data structures, + // ultimately deriving from source order, + // which is preserved by export data. + for i := 0; i < named.NumMethods(); i++ { + if named.Method(i) == meth { + path = appendOpArg(path, opMethod, i) + return Path(path), true + } + } + + // Due to golang/go#59944, go/types fails to associate the receiver with + // certain methods on cgo types. + // + // TODO(rfindley): replace this panic once golang/go#59944 is fixed in all Go + // versions gopls supports. + return "", false + // panic(fmt.Sprintf("couldn't find method %s on type %s; methods: %#v", meth, named, enc.namedMethods(named))) +} + +// find finds obj within type T, returning the path to it, or nil if not found. +// +// The seen map is used to short circuit cycles through type parameters. If +// nil, it will be allocated as necessary. +// +// The seenMethods map is used internally to short circuit cycles through +// interface methods, such as occur in the following example: +// +// type I interface { f() interface{I} } +// +// See golang/go#68046 for details. +func find(obj types.Object, T types.Type, path []byte) []byte { + return (&finder{obj: obj}).find(T, path) +} + +// finder closes over search state for a call to find. +type finder struct { + obj types.Object // the sought object + seenTParamNames map[*types.TypeName]bool // for cycle breaking through type parameters + seenMethods map[*types.Func]bool // for cycle breaking through recursive interfaces +} + +func (f *finder) find(T types.Type, path []byte) []byte { + switch T := T.(type) { + case *types.Alias: + return f.find(types.Unalias(T), path) + case *types.Basic, *types.Named: + // Named types belonging to pkg were handled already, + // so T must belong to another package. No path. + return nil + case *types.Pointer: + return f.find(T.Elem(), append(path, opElem)) + case *types.Slice: + return f.find(T.Elem(), append(path, opElem)) + case *types.Array: + return f.find(T.Elem(), append(path, opElem)) + case *types.Chan: + return f.find(T.Elem(), append(path, opElem)) + case *types.Map: + if r := f.find(T.Key(), append(path, opKey)); r != nil { + return r + } + return f.find(T.Elem(), append(path, opElem)) + case *types.Signature: + if r := f.findTypeParam(T.RecvTypeParams(), path, opRecvTypeParam); r != nil { + return r + } + if r := f.findTypeParam(T.TypeParams(), path, opTypeParam); r != nil { + return r + } + if r := f.find(T.Params(), append(path, opParams)); r != nil { + return r + } + return f.find(T.Results(), append(path, opResults)) + case *types.Struct: + for i := 0; i < T.NumFields(); i++ { + fld := T.Field(i) + path2 := appendOpArg(path, opField, i) + if fld == f.obj { + return path2 // found field var + } + if r := f.find(fld.Type(), append(path2, opType)); r != nil { + return r + } + } + return nil + case *types.Tuple: + for i := 0; i < T.Len(); i++ { + v := T.At(i) + path2 := appendOpArg(path, opAt, i) + if v == f.obj { + return path2 // found param/result var + } + if r := f.find(v.Type(), append(path2, opType)); r != nil { + return r + } + } + return nil + case *types.Interface: + for i := 0; i < T.NumMethods(); i++ { + m := T.Method(i) + if f.seenMethods[m] { + return nil + } + path2 := appendOpArg(path, opMethod, i) + if m == f.obj { + return path2 // found interface method + } + if f.seenMethods == nil { + f.seenMethods = make(map[*types.Func]bool) + } + f.seenMethods[m] = true + if r := f.find(m.Type(), append(path2, opType)); r != nil { + return r + } + } + return nil + case *types.TypeParam: + name := T.Obj() + if f.seenTParamNames[name] { + return nil + } + if name == f.obj { + return append(path, opObj) + } + if f.seenTParamNames == nil { + f.seenTParamNames = make(map[*types.TypeName]bool) + } + f.seenTParamNames[name] = true + if r := f.find(T.Constraint(), append(path, opConstraint)); r != nil { + return r + } + return nil + } + panic(T) +} + +func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, op byte) []byte { + return (&finder{obj: obj}).findTypeParam(list, path, op) +} + +func (f *finder) findTypeParam(list *types.TypeParamList, path []byte, op byte) []byte { + for i := 0; i < list.Len(); i++ { + tparam := list.At(i) + path2 := appendOpArg(path, op, i) + if r := f.find(tparam, path2); r != nil { + return r + } + } + return nil +} + +// Object returns the object denoted by path p within the package pkg. +func Object(pkg *types.Package, p Path) (types.Object, error) { + pathstr := string(p) + if pathstr == "" { + return nil, fmt.Errorf("empty path") + } + + var pkgobj, suffix string + if dot := strings.IndexByte(pathstr, opType); dot < 0 { + pkgobj = pathstr + } else { + pkgobj = pathstr[:dot] + suffix = pathstr[dot:] // suffix starts with "." + } + + obj := pkg.Scope().Lookup(pkgobj) + if obj == nil { + return nil, fmt.Errorf("package %s does not contain %q", pkg.Path(), pkgobj) + } + + // abstraction of *types.{Pointer,Slice,Array,Chan,Map} + type hasElem interface { + Elem() types.Type + } + // abstraction of *types.{Named,Signature} + type hasTypeParams interface { + TypeParams() *types.TypeParamList + } + // abstraction of *types.{Named,TypeParam} + type hasObj interface { + Obj() *types.TypeName + } + + // The loop state is the pair (t, obj), + // exactly one of which is non-nil, initially obj. + // All suffixes start with '.' (the only object->type operation), + // followed by optional type->type operations, + // then a type->object operation. + // The cycle then repeats. + var t types.Type + for suffix != "" { + code := suffix[0] + suffix = suffix[1:] + + // Codes [AFMTr] have an integer operand. + var index int + switch code { + case opAt, opField, opMethod, opTypeParam, opRecvTypeParam: + rest := strings.TrimLeft(suffix, "0123456789") + numerals := suffix[:len(suffix)-len(rest)] + suffix = rest + i, err := strconv.Atoi(numerals) + if err != nil { + return nil, fmt.Errorf("invalid path: bad numeric operand %q for code %q", numerals, code) + } + index = int(i) + case opObj: + // no operand + default: + // The suffix must end with a type->object operation. + if suffix == "" { + return nil, fmt.Errorf("invalid path: ends with %q, want [AFMO]", code) + } + } + + if code == opType { + if t != nil { + return nil, fmt.Errorf("invalid path: unexpected %q in type context", opType) + } + t = obj.Type() + obj = nil + continue + } + + if t == nil { + return nil, fmt.Errorf("invalid path: code %q in object context", code) + } + + // Inv: t != nil, obj == nil + + t = types.Unalias(t) + switch code { + case opElem: + hasElem, ok := t.(hasElem) // Pointer, Slice, Array, Chan, Map + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want pointer, slice, array, chan or map)", code, t, t) + } + t = hasElem.Elem() + + case opKey: + mapType, ok := t.(*types.Map) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want map)", code, t, t) + } + t = mapType.Key() + + case opParams: + sig, ok := t.(*types.Signature) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) + } + t = sig.Params() + + case opResults: + sig, ok := t.(*types.Signature) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) + } + t = sig.Results() + + case opUnderlying: + named, ok := t.(*types.Named) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named)", code, t, t) + } + t = named.Underlying() + + case opRhs: + if alias, ok := t.(*types.Alias); ok { + t = aliases.Rhs(alias) + } else if false && aliases.Enabled() { + // The Enabled check is too expensive, so for now we + // simply assume that aliases are not enabled. + // TODO(adonovan): replace with "if true {" when go1.24 is assured. + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t) + } + + case opTypeParam: + hasTypeParams, ok := t.(hasTypeParams) // Named, Signature + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or signature)", code, t, t) + } + tparams := hasTypeParams.TypeParams() + if n := tparams.Len(); index >= n { + return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) + } + t = tparams.At(index) + + case opRecvTypeParam: + sig, ok := t.(*types.Signature) // Signature + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) + } + rtparams := sig.RecvTypeParams() + if n := rtparams.Len(); index >= n { + return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) + } + t = rtparams.At(index) + + case opConstraint: + tparam, ok := t.(*types.TypeParam) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want type parameter)", code, t, t) + } + t = tparam.Constraint() + + case opAt: + tuple, ok := t.(*types.Tuple) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want tuple)", code, t, t) + } + if n := tuple.Len(); index >= n { + return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) + } + obj = tuple.At(index) + t = nil + + case opField: + structType, ok := t.(*types.Struct) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want struct)", code, t, t) + } + if n := structType.NumFields(); index >= n { + return nil, fmt.Errorf("field index %d out of range [0-%d)", index, n) + } + obj = structType.Field(index) + t = nil + + case opMethod: + switch t := t.(type) { + case *types.Interface: + if index >= t.NumMethods() { + return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) + } + obj = t.Method(index) // Id-ordered + + case *types.Named: + if index >= t.NumMethods() { + return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) + } + obj = t.Method(index) + + default: + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want interface or named)", code, t, t) + } + t = nil + + case opObj: + hasObj, ok := t.(hasObj) + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or type param)", code, t, t) + } + obj = hasObj.Obj() + t = nil + + default: + return nil, fmt.Errorf("invalid path: unknown code %q", code) + } + } + + if obj == nil { + panic(p) // path does not end in an object-valued operator + } + + if obj.Pkg() != pkg { + return nil, fmt.Errorf("path denotes %s, which belongs to a different package", obj) + } + + return obj, nil // success +} + +// scopeObjects is a memoization of scope objects. +// Callers must not modify the result. +func (enc *Encoder) scopeObjects(scope *types.Scope) []types.Object { + m := enc.scopeMemo + if m == nil { + m = make(map[*types.Scope][]types.Object) + enc.scopeMemo = m + } + objs, ok := m[scope] + if !ok { + names := scope.Names() // allocates and sorts + objs = make([]types.Object, len(names)) + for i, name := range names { + objs[i] = scope.Lookup(name) + } + m[scope] = objs + } + return objs +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/callee.go b/vendor/golang.org/x/tools/go/types/typeutil/callee.go new file mode 100644 index 000000000..53b713393 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/callee.go @@ -0,0 +1,85 @@ +// Copyright 2018 The Go 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 typeutil + +import ( + "go/ast" + "go/types" + _ "unsafe" // for linkname +) + +// Callee returns the named target of a function call, if any: +// a function, method, builtin, or variable. +// +// Functions and methods may potentially have type parameters. +// +// Note: for calls of instantiated functions and methods, Callee returns +// the corresponding generic function or method on the generic type. +func Callee(info *types.Info, call *ast.CallExpr) types.Object { + obj := info.Uses[usedIdent(info, call.Fun)] + if obj == nil { + return nil + } + if _, ok := obj.(*types.TypeName); ok { + return nil + } + return obj +} + +// StaticCallee returns the target (function or method) of a static function +// call, if any. It returns nil for calls to builtins. +// +// Note: for calls of instantiated functions and methods, StaticCallee returns +// the corresponding generic function or method on the generic type. +func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func { + obj := info.Uses[usedIdent(info, call.Fun)] + fn, _ := obj.(*types.Func) + if fn == nil || interfaceMethod(fn) { + return nil + } + return fn +} + +// usedIdent is the implementation of [internal/typesinternal.UsedIdent]. +// It returns the identifier associated with e. +// See typesinternal.UsedIdent for a fuller description. +// This function should live in typesinternal, but cannot because it would +// create an import cycle. +// +//go:linkname usedIdent +func usedIdent(info *types.Info, e ast.Expr) *ast.Ident { + if info.Types == nil || info.Uses == nil { + panic("one of info.Types or info.Uses is nil; both must be populated") + } + // Look through type instantiation if necessary. + switch d := ast.Unparen(e).(type) { + case *ast.IndexExpr: + if info.Types[d.Index].IsType() { + e = d.X + } + case *ast.IndexListExpr: + e = d.X + } + + switch e := ast.Unparen(e).(type) { + // info.Uses always has the object we want, even for selector expressions. + // We don't need info.Selections. + // See go/types/recording.go:recordSelection. + case *ast.Ident: + return e + case *ast.SelectorExpr: + return e.Sel + } + return nil +} + +// interfaceMethod reports whether its argument is a method of an interface. +// This function should live in typesinternal, but cannot because it would create an import cycle. +// +//go:linkname interfaceMethod +func interfaceMethod(f *types.Func) bool { + recv := f.Signature().Recv() + return recv != nil && types.IsInterface(recv.Type()) +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/imports.go b/vendor/golang.org/x/tools/go/types/typeutil/imports.go new file mode 100644 index 000000000..b81ce0c33 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/imports.go @@ -0,0 +1,30 @@ +// Copyright 2014 The Go 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 typeutil + +import "go/types" + +// Dependencies returns all dependencies of the specified packages. +// +// Dependent packages appear in topological order: if package P imports +// package Q, Q appears earlier than P in the result. +// The algorithm follows import statements in the order they +// appear in the source code, so the result is a total order. +func Dependencies(pkgs ...*types.Package) []*types.Package { + var result []*types.Package + seen := make(map[*types.Package]bool) + var visit func(pkgs []*types.Package) + visit = func(pkgs []*types.Package) { + for _, p := range pkgs { + if !seen[p] { + seen[p] = true + visit(p.Imports()) + result = append(result, p) + } + } + } + visit(pkgs) + return result +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/map.go b/vendor/golang.org/x/tools/go/types/typeutil/map.go new file mode 100644 index 000000000..b6d542c64 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/map.go @@ -0,0 +1,475 @@ +// Copyright 2014 The Go 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 typeutil defines various utilities for types, such as [Map], +// a hash table that maps [types.Type] to any value. +package typeutil + +import ( + "bytes" + "fmt" + "go/types" + "hash/maphash" + "unsafe" + + "golang.org/x/tools/internal/typeparams" +) + +// Map is a hash-table-based mapping from types (types.Type) to +// arbitrary values. The concrete types that implement +// the Type interface are pointers. Since they are not canonicalized, +// == cannot be used to check for equivalence, and thus we cannot +// simply use a Go map. +// +// Just as with map[K]V, a nil *Map is a valid empty map. +// +// Read-only map operations ([Map.At], [Map.Len], and so on) may +// safely be called concurrently. +// +// TODO(adonovan): deprecate in favor of https://go.dev/issues/69420 +// and 69559, if the latter proposals for a generic hash-map type and +// a types.Hash function are accepted. +type Map struct { + table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused + length int // number of map entries +} + +// entry is an entry (key/value association) in a hash bucket. +type entry struct { + key types.Type + value any +} + +// SetHasher has no effect. +// +// It is a relic of an optimization that is no longer profitable. Do +// not use [Hasher], [MakeHasher], or [SetHasher] in new code. +func (m *Map) SetHasher(Hasher) {} + +// Delete removes the entry with the given key, if any. +// It returns true if the entry was found. +func (m *Map) Delete(key types.Type) bool { + if m != nil && m.table != nil { + hash := hash(key) + bucket := m.table[hash] + for i, e := range bucket { + if e.key != nil && types.Identical(key, e.key) { + // We can't compact the bucket as it + // would disturb iterators. + bucket[i] = entry{} + m.length-- + return true + } + } + } + return false +} + +// At returns the map entry for the given key. +// The result is nil if the entry is not present. +func (m *Map) At(key types.Type) any { + if m != nil && m.table != nil { + for _, e := range m.table[hash(key)] { + if e.key != nil && types.Identical(key, e.key) { + return e.value + } + } + } + return nil +} + +// Set sets the map entry for key to val, +// and returns the previous entry, if any. +func (m *Map) Set(key types.Type, value any) (prev any) { + if m.table != nil { + hash := hash(key) + bucket := m.table[hash] + var hole *entry + for i, e := range bucket { + if e.key == nil { + hole = &bucket[i] + } else if types.Identical(key, e.key) { + prev = e.value + bucket[i].value = value + return + } + } + + if hole != nil { + *hole = entry{key, value} // overwrite deleted entry + } else { + m.table[hash] = append(bucket, entry{key, value}) + } + } else { + hash := hash(key) + m.table = map[uint32][]entry{hash: {entry{key, value}}} + } + + m.length++ + return +} + +// Len returns the number of map entries. +func (m *Map) Len() int { + if m != nil { + return m.length + } + return 0 +} + +// Iterate calls function f on each entry in the map in unspecified order. +// +// If f should mutate the map, Iterate provides the same guarantees as +// Go maps: if f deletes a map entry that Iterate has not yet reached, +// f will not be invoked for it, but if f inserts a map entry that +// Iterate has not yet reached, whether or not f will be invoked for +// it is unspecified. +func (m *Map) Iterate(f func(key types.Type, value any)) { + if m != nil { + for _, bucket := range m.table { + for _, e := range bucket { + if e.key != nil { + f(e.key, e.value) + } + } + } + } +} + +// Keys returns a new slice containing the set of map keys. +// The order is unspecified. +func (m *Map) Keys() []types.Type { + keys := make([]types.Type, 0, m.Len()) + m.Iterate(func(key types.Type, _ any) { + keys = append(keys, key) + }) + return keys +} + +func (m *Map) toString(values bool) string { + if m == nil { + return "{}" + } + var buf bytes.Buffer + fmt.Fprint(&buf, "{") + sep := "" + m.Iterate(func(key types.Type, value any) { + fmt.Fprint(&buf, sep) + sep = ", " + fmt.Fprint(&buf, key) + if values { + fmt.Fprintf(&buf, ": %q", value) + } + }) + fmt.Fprint(&buf, "}") + return buf.String() +} + +// String returns a string representation of the map's entries. +// Values are printed using fmt.Sprintf("%v", v). +// Order is unspecified. +func (m *Map) String() string { + return m.toString(true) +} + +// KeysString returns a string representation of the map's key set. +// Order is unspecified. +func (m *Map) KeysString() string { + return m.toString(false) +} + +// -- Hasher -- + +// hash returns the hash of type t. +// TODO(adonovan): replace by types.Hash when Go proposal #69420 is accepted. +func hash(t types.Type) uint32 { + return theHasher.Hash(t) +} + +// A Hasher provides a [Hasher.Hash] method to map a type to its hash value. +// Hashers are stateless, and all are equivalent. +type Hasher struct{} + +var theHasher Hasher + +// MakeHasher returns Hasher{}. +// Hashers are stateless; all are equivalent. +func MakeHasher() Hasher { return theHasher } + +// Hash computes a hash value for the given type t such that +// Identical(t, t') => Hash(t) == Hash(t'). +func (h Hasher) Hash(t types.Type) uint32 { + return hasher{inGenericSig: false}.hash(t) +} + +// hasher holds the state of a single Hash traversal: whether we are +// inside the signature of a generic function; this is used to +// optimize [hasher.hashTypeParam]. +type hasher struct{ inGenericSig bool } + +// hashString computes the Fowler–Noll–Vo hash of s. +func hashString(s string) uint32 { + var h uint32 + for i := 0; i < len(s); i++ { + h ^= uint32(s[i]) + h *= 16777619 + } + return h +} + +// hash computes the hash of t. +func (h hasher) hash(t types.Type) uint32 { + // See Identical for rationale. + switch t := t.(type) { + case *types.Basic: + return uint32(t.Kind()) + + case *types.Alias: + return h.hash(types.Unalias(t)) + + case *types.Array: + return 9043 + 2*uint32(t.Len()) + 3*h.hash(t.Elem()) + + case *types.Slice: + return 9049 + 2*h.hash(t.Elem()) + + case *types.Struct: + var hash uint32 = 9059 + for i, n := 0, t.NumFields(); i < n; i++ { + f := t.Field(i) + if f.Anonymous() { + hash += 8861 + } + hash += hashString(t.Tag(i)) + hash += hashString(f.Name()) // (ignore f.Pkg) + hash += h.hash(f.Type()) + } + return hash + + case *types.Pointer: + return 9067 + 2*h.hash(t.Elem()) + + case *types.Signature: + var hash uint32 = 9091 + if t.Variadic() { + hash *= 8863 + } + + tparams := t.TypeParams() + if n := tparams.Len(); n > 0 { + h.inGenericSig = true // affects constraints, params, and results + + for i := range n { + tparam := tparams.At(i) + hash += 7 * h.hash(tparam.Constraint()) + } + } + + return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results()) + + case *types.Union: + return h.hashUnion(t) + + case *types.Interface: + // Interfaces are identical if they have the same set of methods, with + // identical names and types, and they have the same set of type + // restrictions. See go/types.identical for more details. + var hash uint32 = 9103 + + // Hash methods. + for i, n := 0, t.NumMethods(); i < n; i++ { + // Method order is not significant. + // Ignore m.Pkg(). + m := t.Method(i) + // Use shallow hash on method signature to + // avoid anonymous interface cycles. + hash += 3*hashString(m.Name()) + 5*h.shallowHash(m.Type()) + } + + // Hash type restrictions. + terms, err := typeparams.InterfaceTermSet(t) + // if err != nil t has invalid type restrictions. + if err == nil { + hash += h.hashTermSet(terms) + } + + return hash + + case *types.Map: + return 9109 + 2*h.hash(t.Key()) + 3*h.hash(t.Elem()) + + case *types.Chan: + return 9127 + 2*uint32(t.Dir()) + 3*h.hash(t.Elem()) + + case *types.Named: + hash := h.hashTypeName(t.Obj()) + targs := t.TypeArgs() + for i := 0; i < targs.Len(); i++ { + targ := targs.At(i) + hash += 2 * h.hash(targ) + } + return hash + + case *types.TypeParam: + return h.hashTypeParam(t) + + case *types.Tuple: + return h.hashTuple(t) + } + + panic(fmt.Sprintf("%T: %v", t, t)) +} + +func (h hasher) hashTuple(tuple *types.Tuple) uint32 { + // See go/types.identicalTypes for rationale. + n := tuple.Len() + hash := 9137 + 2*uint32(n) + for i := range n { + hash += 3 * h.hash(tuple.At(i).Type()) + } + return hash +} + +func (h hasher) hashUnion(t *types.Union) uint32 { + // Hash type restrictions. + terms, err := typeparams.UnionTermSet(t) + // if err != nil t has invalid type restrictions. Fall back on a non-zero + // hash. + if err != nil { + return 9151 + } + return h.hashTermSet(terms) +} + +func (h hasher) hashTermSet(terms []*types.Term) uint32 { + hash := 9157 + 2*uint32(len(terms)) + for _, term := range terms { + // term order is not significant. + termHash := h.hash(term.Type()) + if term.Tilde() { + termHash *= 9161 + } + hash += 3 * termHash + } + return hash +} + +// hashTypeParam returns the hash of a type parameter. +func (h hasher) hashTypeParam(t *types.TypeParam) uint32 { + // Within the signature of a generic function, TypeParams are + // identical if they have the same index and constraint, so we + // hash them based on index. + // + // When we are outside a generic function, free TypeParams are + // identical iff they are the same object, so we can use a + // more discriminating hash consistent with object identity. + // This optimization saves [Map] about 4% when hashing all the + // types.Info.Types in the forward closure of net/http. + if !h.inGenericSig { + // Optimization: outside a generic function signature, + // use a more discrimating hash consistent with object identity. + return h.hashTypeName(t.Obj()) + } + return 9173 + 3*uint32(t.Index()) +} + +var theSeed = maphash.MakeSeed() + +// hashTypeName hashes the pointer of tname. +func (hasher) hashTypeName(tname *types.TypeName) uint32 { + // Since types.Identical uses == to compare TypeNames, + // the Hash function uses maphash.Comparable. + // TODO(adonovan): or will, when it becomes available in go1.24. + // In the meantime we use the pointer's numeric value. + // + // hash := maphash.Comparable(theSeed, tname) + // + // (Another approach would be to hash the name and package + // path, and whether or not it is a package-level typename. It + // is rare for a package to define multiple local types with + // the same name.) + ptr := uintptr(unsafe.Pointer(tname)) + if unsafe.Sizeof(ptr) == 8 { + hash := uint64(ptr) + return uint32(hash ^ (hash >> 32)) + } else { + return uint32(ptr) + } +} + +// shallowHash computes a hash of t without looking at any of its +// element Types, to avoid potential anonymous cycles in the types of +// interface methods. +// +// When an unnamed non-empty interface type appears anywhere among the +// arguments or results of an interface method, there is a potential +// for endless recursion. Consider: +// +// type X interface { m() []*interface { X } } +// +// The problem is that the Methods of the interface in m's result type +// include m itself; there is no mention of the named type X that +// might help us break the cycle. +// (See comment in go/types.identical, case *Interface, for more.) +func (h hasher) shallowHash(t types.Type) uint32 { + // t is the type of an interface method (Signature), + // its params or results (Tuples), or their immediate + // elements (mostly Slice, Pointer, Basic, Named), + // so there's no need to optimize anything else. + switch t := t.(type) { + case *types.Alias: + return h.shallowHash(types.Unalias(t)) + + case *types.Signature: + var hash uint32 = 604171 + if t.Variadic() { + hash *= 971767 + } + // The Signature/Tuple recursion is always finite + // and invariably shallow. + return hash + 1062599*h.shallowHash(t.Params()) + 1282529*h.shallowHash(t.Results()) + + case *types.Tuple: + n := t.Len() + hash := 9137 + 2*uint32(n) + for i := range n { + hash += 53471161 * h.shallowHash(t.At(i).Type()) + } + return hash + + case *types.Basic: + return 45212177 * uint32(t.Kind()) + + case *types.Array: + return 1524181 + 2*uint32(t.Len()) + + case *types.Slice: + return 2690201 + + case *types.Struct: + return 3326489 + + case *types.Pointer: + return 4393139 + + case *types.Union: + return 562448657 + + case *types.Interface: + return 2124679 // no recursion here + + case *types.Map: + return 9109 + + case *types.Chan: + return 9127 + + case *types.Named: + return h.hashTypeName(t.Obj()) + + case *types.TypeParam: + return h.hashTypeParam(t) + } + panic(fmt.Sprintf("shallowHash: %T: %v", t, t)) +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go b/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go new file mode 100644 index 000000000..f7666028f --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go @@ -0,0 +1,71 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements a cache of method sets. + +package typeutil + +import ( + "go/types" + "sync" +) + +// A MethodSetCache records the method set of each type T for which +// MethodSet(T) is called so that repeat queries are fast. +// The zero value is a ready-to-use cache instance. +type MethodSetCache struct { + mu sync.Mutex + named map[*types.Named]struct{ value, pointer *types.MethodSet } // method sets for named N and *N + others map[types.Type]*types.MethodSet // all other types +} + +// MethodSet returns the method set of type T. It is thread-safe. +// +// If cache is nil, this function is equivalent to types.NewMethodSet(T). +// Utility functions can thus expose an optional *MethodSetCache +// parameter to clients that care about performance. +func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet { + if cache == nil { + return types.NewMethodSet(T) + } + cache.mu.Lock() + defer cache.mu.Unlock() + + switch T := types.Unalias(T).(type) { + case *types.Named: + return cache.lookupNamed(T).value + + case *types.Pointer: + if N, ok := types.Unalias(T.Elem()).(*types.Named); ok { + return cache.lookupNamed(N).pointer + } + } + + // all other types + // (The map uses pointer equivalence, not type identity.) + mset := cache.others[T] + if mset == nil { + mset = types.NewMethodSet(T) + if cache.others == nil { + cache.others = make(map[types.Type]*types.MethodSet) + } + cache.others[T] = mset + } + return mset +} + +func (cache *MethodSetCache) lookupNamed(named *types.Named) struct{ value, pointer *types.MethodSet } { + if cache.named == nil { + cache.named = make(map[*types.Named]struct{ value, pointer *types.MethodSet }) + } + // Avoid recomputing mset(*T) for each distinct Pointer + // instance whose underlying type is a named type. + msets, ok := cache.named[named] + if !ok { + msets.value = types.NewMethodSet(named) + msets.pointer = types.NewMethodSet(types.NewPointer(named)) + cache.named[named] = msets + } + return msets +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/ui.go b/vendor/golang.org/x/tools/go/types/typeutil/ui.go new file mode 100644 index 000000000..9dda6a25d --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/ui.go @@ -0,0 +1,53 @@ +// Copyright 2014 The Go 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 typeutil + +// This file defines utilities for user interfaces that display types. + +import ( + "go/types" +) + +// IntuitiveMethodSet returns the intuitive method set of a type T, +// which is the set of methods you can call on an addressable value of +// that type. +// +// The result always contains MethodSet(T), and is exactly MethodSet(T) +// for interface types and for pointer-to-concrete types. +// For all other concrete types T, the result additionally +// contains each method belonging to *T if there is no identically +// named method on T itself. +// +// This corresponds to user intuition about method sets; +// this function is intended only for user interfaces. +// +// The order of the result is as for types.MethodSet(T). +func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection { + isPointerToConcrete := func(T types.Type) bool { + ptr, ok := types.Unalias(T).(*types.Pointer) + return ok && !types.IsInterface(ptr.Elem()) + } + + var result []*types.Selection + mset := msets.MethodSet(T) + if types.IsInterface(T) || isPointerToConcrete(T) { + for i, n := 0, mset.Len(); i < n; i++ { + result = append(result, mset.At(i)) + } + } else { + // T is some other concrete type. + // Report methods of T and *T, preferring those of T. + pmset := msets.MethodSet(types.NewPointer(T)) + for i, n := 0, pmset.Len(); i < n; i++ { + meth := pmset.At(i) + if m := mset.Lookup(meth.Obj().Pkg(), meth.Obj().Name()); m != nil { + meth = m + } + result = append(result, meth) + } + + } + return result +} diff --git a/vendor/golang.org/x/tools/imports/forward.go b/vendor/golang.org/x/tools/imports/forward.go new file mode 100644 index 000000000..cb6db8893 --- /dev/null +++ b/vendor/golang.org/x/tools/imports/forward.go @@ -0,0 +1,77 @@ +// Copyright 2019 The Go 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 imports implements a Go pretty-printer (like package "go/format") +// that also adds or removes import statements as necessary. +package imports // import "golang.org/x/tools/imports" + +import ( + "log" + "os" + + "golang.org/x/tools/internal/gocommand" + intimp "golang.org/x/tools/internal/imports" +) + +// Options specifies options for processing files. +type Options struct { + Fragment bool // Accept fragment of a source file (no package statement) + AllErrors bool // Report all errors (not just the first 10 on different lines) + + Comments bool // Print comments (true if nil *Options provided) + TabIndent bool // Use tabs for indent (true if nil *Options provided) + TabWidth int // Tab width (8 if nil *Options provided) + + FormatOnly bool // Disable the insertion and deletion of imports +} + +// Debug controls verbose logging. +var Debug = false + +// LocalPrefix is a comma-separated string of import path prefixes, which, if +// set, instructs Process to sort the import paths with the given prefixes +// into another group after 3rd-party packages. +var LocalPrefix string + +// Process formats and adjusts imports for the provided file. +// If opt is nil the defaults are used, and if src is nil the source +// is read from the filesystem. +// +// Note that filename's directory influences which imports can be chosen, +// so it is important that filename be accurate. +// To process data “as if” it were in filename, pass the data as a non-nil src. +func Process(filename string, src []byte, opt *Options) ([]byte, error) { + var err error + if src == nil { + src, err = os.ReadFile(filename) + if err != nil { + return nil, err + } + } + if opt == nil { + opt = &Options{Comments: true, TabIndent: true, TabWidth: 8} + } + intopt := &intimp.Options{ + Env: &intimp.ProcessEnv{ + GocmdRunner: &gocommand.Runner{}, + }, + LocalPrefix: LocalPrefix, + AllErrors: opt.AllErrors, + Comments: opt.Comments, + FormatOnly: opt.FormatOnly, + Fragment: opt.Fragment, + TabIndent: opt.TabIndent, + TabWidth: opt.TabWidth, + } + if Debug { + intopt.Env.Logf = log.Printf + } + return intimp.Process(filename, src, intopt) +} + +// VendorlessPath returns the devendorized version of the import path ipath. +// For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b". +func VendorlessPath(ipath string) string { + return intimp.VendorlessPath(ipath) +} diff --git a/vendor/golang.org/x/tools/internal/aliases/aliases.go b/vendor/golang.org/x/tools/internal/aliases/aliases.go new file mode 100644 index 000000000..b9425f5a2 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/aliases/aliases.go @@ -0,0 +1,38 @@ +// Copyright 2024 The Go 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 aliases + +import ( + "go/token" + "go/types" +) + +// Package aliases defines backward compatible shims +// for the types.Alias type representation added in 1.22. +// This defines placeholders for x/tools until 1.26. + +// NewAlias creates a new TypeName in Package pkg that +// is an alias for the type rhs. +// +// The enabled parameter determines whether the resulting [TypeName]'s +// type is an [types.Alias]. Its value must be the result of a call to +// [Enabled], which computes the effective value of +// GODEBUG=gotypesalias=... by invoking the type checker. The Enabled +// function is expensive and should be called once per task (e.g. +// package import), not once per call to NewAlias. +// +// Precondition: enabled || len(tparams)==0. +// If materialized aliases are disabled, there must not be any type parameters. +func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type, tparams []*types.TypeParam) *types.TypeName { + if enabled { + tname := types.NewTypeName(pos, pkg, name, nil) + SetTypeParams(types.NewAlias(tname, rhs), tparams) + return tname + } + if len(tparams) > 0 { + panic("cannot create an alias with type parameters when gotypesalias is not enabled") + } + return types.NewTypeName(pos, pkg, name, rhs) +} diff --git a/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go b/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go new file mode 100644 index 000000000..7716a3331 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go @@ -0,0 +1,80 @@ +// Copyright 2024 The Go 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 aliases + +import ( + "go/ast" + "go/parser" + "go/token" + "go/types" +) + +// Rhs returns the type on the right-hand side of the alias declaration. +func Rhs(alias *types.Alias) types.Type { + if alias, ok := any(alias).(interface{ Rhs() types.Type }); ok { + return alias.Rhs() // go1.23+ + } + + // go1.22's Alias didn't have the Rhs method, + // so Unalias is the best we can do. + return types.Unalias(alias) +} + +// TypeParams returns the type parameter list of the alias. +func TypeParams(alias *types.Alias) *types.TypeParamList { + if alias, ok := any(alias).(interface{ TypeParams() *types.TypeParamList }); ok { + return alias.TypeParams() // go1.23+ + } + return nil +} + +// SetTypeParams sets the type parameters of the alias type. +func SetTypeParams(alias *types.Alias, tparams []*types.TypeParam) { + if alias, ok := any(alias).(interface { + SetTypeParams(tparams []*types.TypeParam) + }); ok { + alias.SetTypeParams(tparams) // go1.23+ + } else if len(tparams) > 0 { + panic("cannot set type parameters of an Alias type in go1.22") + } +} + +// TypeArgs returns the type arguments used to instantiate the Alias type. +func TypeArgs(alias *types.Alias) *types.TypeList { + if alias, ok := any(alias).(interface{ TypeArgs() *types.TypeList }); ok { + return alias.TypeArgs() // go1.23+ + } + return nil // empty (go1.22) +} + +// Origin returns the generic Alias type of which alias is an instance. +// If alias is not an instance of a generic alias, Origin returns alias. +func Origin(alias *types.Alias) *types.Alias { + if alias, ok := any(alias).(interface{ Origin() *types.Alias }); ok { + return alias.Origin() // go1.23+ + } + return alias // not an instance of a generic alias (go1.22) +} + +// Enabled reports whether [NewAlias] should create [types.Alias] types. +// +// This function is expensive! Call it sparingly. +func Enabled() bool { + // The only reliable way to compute the answer is to invoke go/types. + // We don't parse the GODEBUG environment variable, because + // (a) it's tricky to do so in a manner that is consistent + // with the godebug package; in particular, a simple + // substring check is not good enough. The value is a + // rightmost-wins list of options. But more importantly: + // (b) it is impossible to detect changes to the effective + // setting caused by os.Setenv("GODEBUG"), as happens in + // many tests. Therefore any attempt to cache the result + // is just incorrect. + fset := token.NewFileSet() + f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", parser.SkipObjectResolution) + pkg, _ := new(types.Config).Check("p", fset, []*ast.File{f}, nil) + _, enabled := pkg.Scope().Lookup("A").Type().(*types.Alias) + return enabled +} diff --git a/vendor/golang.org/x/tools/internal/astutil/edge/edge.go b/vendor/golang.org/x/tools/internal/astutil/edge/edge.go new file mode 100644 index 000000000..4f6ccfd6e --- /dev/null +++ b/vendor/golang.org/x/tools/internal/astutil/edge/edge.go @@ -0,0 +1,295 @@ +// Copyright 2025 The Go 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 edge defines identifiers for each field of an ast.Node +// struct type that refers to another Node. +package edge + +import ( + "fmt" + "go/ast" + "reflect" +) + +// A Kind describes a field of an ast.Node struct. +type Kind uint8 + +// String returns a description of the edge kind. +func (k Kind) String() string { + if k == Invalid { + return "" + } + info := fieldInfos[k] + return fmt.Sprintf("%v.%s", info.nodeType.Elem().Name(), info.name) +} + +// NodeType returns the pointer-to-struct type of the ast.Node implementation. +func (k Kind) NodeType() reflect.Type { return fieldInfos[k].nodeType } + +// FieldName returns the name of the field. +func (k Kind) FieldName() string { return fieldInfos[k].name } + +// FieldType returns the declared type of the field. +func (k Kind) FieldType() reflect.Type { return fieldInfos[k].fieldType } + +// Get returns the direct child of n identified by (k, idx). +// n's type must match k.NodeType(). +// idx must be a valid slice index, or -1 for a non-slice. +func (k Kind) Get(n ast.Node, idx int) ast.Node { + if k.NodeType() != reflect.TypeOf(n) { + panic(fmt.Sprintf("%v.Get(%T): invalid node type", k, n)) + } + v := reflect.ValueOf(n).Elem().Field(fieldInfos[k].index) + if idx != -1 { + v = v.Index(idx) // asserts valid index + } else { + // (The type assertion below asserts that v is not a slice.) + } + return v.Interface().(ast.Node) // may be nil +} + +const ( + Invalid Kind = iota // for nodes at the root of the traversal + + // Kinds are sorted alphabetically. + // Numbering is not stable. + // Each is named Type_Field, where Type is the + // ast.Node struct type and Field is the name of the field + + ArrayType_Elt + ArrayType_Len + AssignStmt_Lhs + AssignStmt_Rhs + BinaryExpr_X + BinaryExpr_Y + BlockStmt_List + BranchStmt_Label + CallExpr_Args + CallExpr_Fun + CaseClause_Body + CaseClause_List + ChanType_Value + CommClause_Body + CommClause_Comm + CommentGroup_List + CompositeLit_Elts + CompositeLit_Type + DeclStmt_Decl + DeferStmt_Call + Ellipsis_Elt + ExprStmt_X + FieldList_List + Field_Comment + Field_Doc + Field_Names + Field_Tag + Field_Type + File_Decls + File_Doc + File_Name + ForStmt_Body + ForStmt_Cond + ForStmt_Init + ForStmt_Post + FuncDecl_Body + FuncDecl_Doc + FuncDecl_Name + FuncDecl_Recv + FuncDecl_Type + FuncLit_Body + FuncLit_Type + FuncType_Params + FuncType_Results + FuncType_TypeParams + GenDecl_Doc + GenDecl_Specs + GoStmt_Call + IfStmt_Body + IfStmt_Cond + IfStmt_Else + IfStmt_Init + ImportSpec_Comment + ImportSpec_Doc + ImportSpec_Name + ImportSpec_Path + IncDecStmt_X + IndexExpr_Index + IndexExpr_X + IndexListExpr_Indices + IndexListExpr_X + InterfaceType_Methods + KeyValueExpr_Key + KeyValueExpr_Value + LabeledStmt_Label + LabeledStmt_Stmt + MapType_Key + MapType_Value + ParenExpr_X + RangeStmt_Body + RangeStmt_Key + RangeStmt_Value + RangeStmt_X + ReturnStmt_Results + SelectStmt_Body + SelectorExpr_Sel + SelectorExpr_X + SendStmt_Chan + SendStmt_Value + SliceExpr_High + SliceExpr_Low + SliceExpr_Max + SliceExpr_X + StarExpr_X + StructType_Fields + SwitchStmt_Body + SwitchStmt_Init + SwitchStmt_Tag + TypeAssertExpr_Type + TypeAssertExpr_X + TypeSpec_Comment + TypeSpec_Doc + TypeSpec_Name + TypeSpec_Type + TypeSpec_TypeParams + TypeSwitchStmt_Assign + TypeSwitchStmt_Body + TypeSwitchStmt_Init + UnaryExpr_X + ValueSpec_Comment + ValueSpec_Doc + ValueSpec_Names + ValueSpec_Type + ValueSpec_Values + + maxKind +) + +// Assert that the encoding fits in 7 bits, +// as the inspector relies on this. +// (We are currently at 104.) +var _ = [1 << 7]struct{}{}[maxKind] + +type fieldInfo struct { + nodeType reflect.Type // pointer-to-struct type of ast.Node implementation + name string + index int + fieldType reflect.Type +} + +func info[N ast.Node](fieldName string) fieldInfo { + nodePtrType := reflect.TypeFor[N]() + f, ok := nodePtrType.Elem().FieldByName(fieldName) + if !ok { + panic(fieldName) + } + return fieldInfo{nodePtrType, fieldName, f.Index[0], f.Type} +} + +var fieldInfos = [...]fieldInfo{ + Invalid: {}, + ArrayType_Elt: info[*ast.ArrayType]("Elt"), + ArrayType_Len: info[*ast.ArrayType]("Len"), + AssignStmt_Lhs: info[*ast.AssignStmt]("Lhs"), + AssignStmt_Rhs: info[*ast.AssignStmt]("Rhs"), + BinaryExpr_X: info[*ast.BinaryExpr]("X"), + BinaryExpr_Y: info[*ast.BinaryExpr]("Y"), + BlockStmt_List: info[*ast.BlockStmt]("List"), + BranchStmt_Label: info[*ast.BranchStmt]("Label"), + CallExpr_Args: info[*ast.CallExpr]("Args"), + CallExpr_Fun: info[*ast.CallExpr]("Fun"), + CaseClause_Body: info[*ast.CaseClause]("Body"), + CaseClause_List: info[*ast.CaseClause]("List"), + ChanType_Value: info[*ast.ChanType]("Value"), + CommClause_Body: info[*ast.CommClause]("Body"), + CommClause_Comm: info[*ast.CommClause]("Comm"), + CommentGroup_List: info[*ast.CommentGroup]("List"), + CompositeLit_Elts: info[*ast.CompositeLit]("Elts"), + CompositeLit_Type: info[*ast.CompositeLit]("Type"), + DeclStmt_Decl: info[*ast.DeclStmt]("Decl"), + DeferStmt_Call: info[*ast.DeferStmt]("Call"), + Ellipsis_Elt: info[*ast.Ellipsis]("Elt"), + ExprStmt_X: info[*ast.ExprStmt]("X"), + FieldList_List: info[*ast.FieldList]("List"), + Field_Comment: info[*ast.Field]("Comment"), + Field_Doc: info[*ast.Field]("Doc"), + Field_Names: info[*ast.Field]("Names"), + Field_Tag: info[*ast.Field]("Tag"), + Field_Type: info[*ast.Field]("Type"), + File_Decls: info[*ast.File]("Decls"), + File_Doc: info[*ast.File]("Doc"), + File_Name: info[*ast.File]("Name"), + ForStmt_Body: info[*ast.ForStmt]("Body"), + ForStmt_Cond: info[*ast.ForStmt]("Cond"), + ForStmt_Init: info[*ast.ForStmt]("Init"), + ForStmt_Post: info[*ast.ForStmt]("Post"), + FuncDecl_Body: info[*ast.FuncDecl]("Body"), + FuncDecl_Doc: info[*ast.FuncDecl]("Doc"), + FuncDecl_Name: info[*ast.FuncDecl]("Name"), + FuncDecl_Recv: info[*ast.FuncDecl]("Recv"), + FuncDecl_Type: info[*ast.FuncDecl]("Type"), + FuncLit_Body: info[*ast.FuncLit]("Body"), + FuncLit_Type: info[*ast.FuncLit]("Type"), + FuncType_Params: info[*ast.FuncType]("Params"), + FuncType_Results: info[*ast.FuncType]("Results"), + FuncType_TypeParams: info[*ast.FuncType]("TypeParams"), + GenDecl_Doc: info[*ast.GenDecl]("Doc"), + GenDecl_Specs: info[*ast.GenDecl]("Specs"), + GoStmt_Call: info[*ast.GoStmt]("Call"), + IfStmt_Body: info[*ast.IfStmt]("Body"), + IfStmt_Cond: info[*ast.IfStmt]("Cond"), + IfStmt_Else: info[*ast.IfStmt]("Else"), + IfStmt_Init: info[*ast.IfStmt]("Init"), + ImportSpec_Comment: info[*ast.ImportSpec]("Comment"), + ImportSpec_Doc: info[*ast.ImportSpec]("Doc"), + ImportSpec_Name: info[*ast.ImportSpec]("Name"), + ImportSpec_Path: info[*ast.ImportSpec]("Path"), + IncDecStmt_X: info[*ast.IncDecStmt]("X"), + IndexExpr_Index: info[*ast.IndexExpr]("Index"), + IndexExpr_X: info[*ast.IndexExpr]("X"), + IndexListExpr_Indices: info[*ast.IndexListExpr]("Indices"), + IndexListExpr_X: info[*ast.IndexListExpr]("X"), + InterfaceType_Methods: info[*ast.InterfaceType]("Methods"), + KeyValueExpr_Key: info[*ast.KeyValueExpr]("Key"), + KeyValueExpr_Value: info[*ast.KeyValueExpr]("Value"), + LabeledStmt_Label: info[*ast.LabeledStmt]("Label"), + LabeledStmt_Stmt: info[*ast.LabeledStmt]("Stmt"), + MapType_Key: info[*ast.MapType]("Key"), + MapType_Value: info[*ast.MapType]("Value"), + ParenExpr_X: info[*ast.ParenExpr]("X"), + RangeStmt_Body: info[*ast.RangeStmt]("Body"), + RangeStmt_Key: info[*ast.RangeStmt]("Key"), + RangeStmt_Value: info[*ast.RangeStmt]("Value"), + RangeStmt_X: info[*ast.RangeStmt]("X"), + ReturnStmt_Results: info[*ast.ReturnStmt]("Results"), + SelectStmt_Body: info[*ast.SelectStmt]("Body"), + SelectorExpr_Sel: info[*ast.SelectorExpr]("Sel"), + SelectorExpr_X: info[*ast.SelectorExpr]("X"), + SendStmt_Chan: info[*ast.SendStmt]("Chan"), + SendStmt_Value: info[*ast.SendStmt]("Value"), + SliceExpr_High: info[*ast.SliceExpr]("High"), + SliceExpr_Low: info[*ast.SliceExpr]("Low"), + SliceExpr_Max: info[*ast.SliceExpr]("Max"), + SliceExpr_X: info[*ast.SliceExpr]("X"), + StarExpr_X: info[*ast.StarExpr]("X"), + StructType_Fields: info[*ast.StructType]("Fields"), + SwitchStmt_Body: info[*ast.SwitchStmt]("Body"), + SwitchStmt_Init: info[*ast.SwitchStmt]("Init"), + SwitchStmt_Tag: info[*ast.SwitchStmt]("Tag"), + TypeAssertExpr_Type: info[*ast.TypeAssertExpr]("Type"), + TypeAssertExpr_X: info[*ast.TypeAssertExpr]("X"), + TypeSpec_Comment: info[*ast.TypeSpec]("Comment"), + TypeSpec_Doc: info[*ast.TypeSpec]("Doc"), + TypeSpec_Name: info[*ast.TypeSpec]("Name"), + TypeSpec_Type: info[*ast.TypeSpec]("Type"), + TypeSpec_TypeParams: info[*ast.TypeSpec]("TypeParams"), + TypeSwitchStmt_Assign: info[*ast.TypeSwitchStmt]("Assign"), + TypeSwitchStmt_Body: info[*ast.TypeSwitchStmt]("Body"), + TypeSwitchStmt_Init: info[*ast.TypeSwitchStmt]("Init"), + UnaryExpr_X: info[*ast.UnaryExpr]("X"), + ValueSpec_Comment: info[*ast.ValueSpec]("Comment"), + ValueSpec_Doc: info[*ast.ValueSpec]("Doc"), + ValueSpec_Names: info[*ast.ValueSpec]("Names"), + ValueSpec_Type: info[*ast.ValueSpec]("Type"), + ValueSpec_Values: info[*ast.ValueSpec]("Values"), +} diff --git a/vendor/golang.org/x/tools/internal/event/core/event.go b/vendor/golang.org/x/tools/internal/event/core/event.go new file mode 100644 index 000000000..a6cf0e64a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/core/event.go @@ -0,0 +1,85 @@ +// Copyright 2019 The Go 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 core provides support for event based telemetry. +package core + +import ( + "fmt" + "time" + + "golang.org/x/tools/internal/event/label" +) + +// Event holds the information about an event of note that occurred. +type Event struct { + at time.Time + + // As events are often on the stack, storing the first few labels directly + // in the event can avoid an allocation at all for the very common cases of + // simple events. + // The length needs to be large enough to cope with the majority of events + // but no so large as to cause undue stack pressure. + // A log message with two values will use 3 labels (one for each value and + // one for the message itself). + + static [3]label.Label // inline storage for the first few labels + dynamic []label.Label // dynamically sized storage for remaining labels +} + +// eventLabelMap implements label.Map for a the labels of an Event. +type eventLabelMap struct { + event Event +} + +func (ev Event) At() time.Time { return ev.at } + +func (ev Event) Format(f fmt.State, r rune) { + if !ev.at.IsZero() { + fmt.Fprint(f, ev.at.Format("2006/01/02 15:04:05 ")) + } + for index := 0; ev.Valid(index); index++ { + if l := ev.Label(index); l.Valid() { + fmt.Fprintf(f, "\n\t%v", l) + } + } +} + +func (ev Event) Valid(index int) bool { + return index >= 0 && index < len(ev.static)+len(ev.dynamic) +} + +func (ev Event) Label(index int) label.Label { + if index < len(ev.static) { + return ev.static[index] + } + return ev.dynamic[index-len(ev.static)] +} + +func (ev Event) Find(key label.Key) label.Label { + for _, l := range ev.static { + if l.Key() == key { + return l + } + } + for _, l := range ev.dynamic { + if l.Key() == key { + return l + } + } + return label.Label{} +} + +func MakeEvent(static [3]label.Label, labels []label.Label) Event { + return Event{ + static: static, + dynamic: labels, + } +} + +// CloneEvent event returns a copy of the event with the time adjusted to at. +func CloneEvent(ev Event, at time.Time) Event { + ev.at = at + return ev +} diff --git a/vendor/golang.org/x/tools/internal/event/core/export.go b/vendor/golang.org/x/tools/internal/event/core/export.go new file mode 100644 index 000000000..05f3a9a57 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/core/export.go @@ -0,0 +1,70 @@ +// Copyright 2019 The Go 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 core + +import ( + "context" + "sync/atomic" + "time" + "unsafe" + + "golang.org/x/tools/internal/event/label" +) + +// Exporter is a function that handles events. +// It may return a modified context and event. +type Exporter func(context.Context, Event, label.Map) context.Context + +var ( + exporter unsafe.Pointer +) + +// SetExporter sets the global exporter function that handles all events. +// The exporter is called synchronously from the event call site, so it should +// return quickly so as not to hold up user code. +func SetExporter(e Exporter) { + p := unsafe.Pointer(&e) + if e == nil { + // &e is always valid, and so p is always valid, but for the early abort + // of ProcessEvent to be efficient it needs to make the nil check on the + // pointer without having to dereference it, so we make the nil function + // also a nil pointer + p = nil + } + atomic.StorePointer(&exporter, p) +} + +// deliver is called to deliver an event to the supplied exporter. +// it will fill in the time. +func deliver(ctx context.Context, exporter Exporter, ev Event) context.Context { + // add the current time to the event + ev.at = time.Now() + // hand the event off to the current exporter + return exporter(ctx, ev, ev) +} + +// Export is called to deliver an event to the global exporter if set. +func Export(ctx context.Context, ev Event) context.Context { + // get the global exporter and abort early if there is not one + exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) + if exporterPtr == nil { + return ctx + } + return deliver(ctx, *exporterPtr, ev) +} + +// ExportPair is called to deliver a start event to the supplied exporter. +// It also returns a function that will deliver the end event to the same +// exporter. +// It will fill in the time. +func ExportPair(ctx context.Context, begin, end Event) (context.Context, func()) { + // get the global exporter and abort early if there is not one + exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) + if exporterPtr == nil { + return ctx, func() {} + } + ctx = deliver(ctx, *exporterPtr, begin) + return ctx, func() { deliver(ctx, *exporterPtr, end) } +} diff --git a/vendor/golang.org/x/tools/internal/event/core/fast.go b/vendor/golang.org/x/tools/internal/event/core/fast.go new file mode 100644 index 000000000..06c1d4615 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/core/fast.go @@ -0,0 +1,77 @@ +// Copyright 2019 The Go 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 core + +import ( + "context" + + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" +) + +// Log1 takes a message and one label delivers a log event to the exporter. +// It is a customized version of Print that is faster and does no allocation. +func Log1(ctx context.Context, message string, t1 label.Label) { + Export(ctx, MakeEvent([3]label.Label{ + keys.Msg.Of(message), + t1, + }, nil)) +} + +// Log2 takes a message and two labels and delivers a log event to the exporter. +// It is a customized version of Print that is faster and does no allocation. +func Log2(ctx context.Context, message string, t1 label.Label, t2 label.Label) { + Export(ctx, MakeEvent([3]label.Label{ + keys.Msg.Of(message), + t1, + t2, + }, nil)) +} + +// Metric1 sends a label event to the exporter with the supplied labels. +func Metric1(ctx context.Context, t1 label.Label) context.Context { + return Export(ctx, MakeEvent([3]label.Label{ + keys.Metric.New(), + t1, + }, nil)) +} + +// Metric2 sends a label event to the exporter with the supplied labels. +func Metric2(ctx context.Context, t1, t2 label.Label) context.Context { + return Export(ctx, MakeEvent([3]label.Label{ + keys.Metric.New(), + t1, + t2, + }, nil)) +} + +// Start1 sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start1(ctx context.Context, name string, t1 label.Label) (context.Context, func()) { + return ExportPair(ctx, + MakeEvent([3]label.Label{ + keys.Start.Of(name), + t1, + }, nil), + MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} + +// Start2 sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start2(ctx context.Context, name string, t1, t2 label.Label) (context.Context, func()) { + return ExportPair(ctx, + MakeEvent([3]label.Label{ + keys.Start.Of(name), + t1, + t2, + }, nil), + MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} diff --git a/vendor/golang.org/x/tools/internal/event/doc.go b/vendor/golang.org/x/tools/internal/event/doc.go new file mode 100644 index 000000000..5dc6e6bab --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/doc.go @@ -0,0 +1,7 @@ +// Copyright 2019 The Go 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 event provides a set of packages that cover the main +// concepts of telemetry in an implementation agnostic way. +package event diff --git a/vendor/golang.org/x/tools/internal/event/event.go b/vendor/golang.org/x/tools/internal/event/event.go new file mode 100644 index 000000000..4d55e577d --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/event.go @@ -0,0 +1,127 @@ +// Copyright 2019 The Go 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 event + +import ( + "context" + + "golang.org/x/tools/internal/event/core" + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" +) + +// Exporter is a function that handles events. +// It may return a modified context and event. +type Exporter func(context.Context, core.Event, label.Map) context.Context + +// SetExporter sets the global exporter function that handles all events. +// The exporter is called synchronously from the event call site, so it should +// return quickly so as not to hold up user code. +func SetExporter(e Exporter) { + core.SetExporter(core.Exporter(e)) +} + +// Log takes a message and a label list and combines them into a single event +// before delivering them to the exporter. +func Log(ctx context.Context, message string, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Msg.Of(message), + }, labels)) +} + +// IsLog returns true if the event was built by the Log function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsLog(ev core.Event) bool { + return ev.Label(0).Key() == keys.Msg +} + +// Error takes a message and a label list and combines them into a single event +// before delivering them to the exporter. It captures the error in the +// delivered event. +func Error(ctx context.Context, message string, err error, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Msg.Of(message), + keys.Err.Of(err), + }, labels)) +} + +// IsError returns true if the event was built by the Error function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsError(ev core.Event) bool { + return ev.Label(0).Key() == keys.Msg && + ev.Label(1).Key() == keys.Err +} + +// Metric sends a label event to the exporter with the supplied labels. +func Metric(ctx context.Context, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Metric.New(), + }, labels)) +} + +// IsMetric returns true if the event was built by the Metric function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsMetric(ev core.Event) bool { + return ev.Label(0).Key() == keys.Metric +} + +// Label sends a label event to the exporter with the supplied labels. +func Label(ctx context.Context, labels ...label.Label) context.Context { + return core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Label.New(), + }, labels)) +} + +// IsLabel returns true if the event was built by the Label function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsLabel(ev core.Event) bool { + return ev.Label(0).Key() == keys.Label +} + +// Start sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func()) { + return core.ExportPair(ctx, + core.MakeEvent([3]label.Label{ + keys.Start.Of(name), + }, labels), + core.MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} + +// IsStart returns true if the event was built by the Start function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsStart(ev core.Event) bool { + return ev.Label(0).Key() == keys.Start +} + +// IsEnd returns true if the event was built by the End function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsEnd(ev core.Event) bool { + return ev.Label(0).Key() == keys.End +} + +// Detach returns a context without an associated span. +// This allows the creation of spans that are not children of the current span. +func Detach(ctx context.Context) context.Context { + return core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Detach.New(), + }, nil)) +} + +// IsDetach returns true if the event was built by the Detach function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsDetach(ev core.Event) bool { + return ev.Label(0).Key() == keys.Detach +} diff --git a/vendor/golang.org/x/tools/internal/event/keys/keys.go b/vendor/golang.org/x/tools/internal/event/keys/keys.go new file mode 100644 index 000000000..4cfa51b61 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/keys/keys.go @@ -0,0 +1,564 @@ +// Copyright 2019 The Go 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 keys + +import ( + "fmt" + "io" + "math" + "strconv" + + "golang.org/x/tools/internal/event/label" +) + +// Value represents a key for untyped values. +type Value struct { + name string + description string +} + +// New creates a new Key for untyped values. +func New(name, description string) *Value { + return &Value{name: name, description: description} +} + +func (k *Value) Name() string { return k.name } +func (k *Value) Description() string { return k.description } + +func (k *Value) Format(w io.Writer, buf []byte, l label.Label) { + fmt.Fprint(w, k.From(l)) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Value) Get(lm label.Map) any { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return nil +} + +// From can be used to get a value from a Label. +func (k *Value) From(t label.Label) any { return t.UnpackValue() } + +// Of creates a new Label with this key and the supplied value. +func (k *Value) Of(value any) label.Label { return label.OfValue(k, value) } + +// Tag represents a key for tagging labels that have no value. +// These are used when the existence of the label is the entire information it +// carries, such as marking events to be of a specific kind, or from a specific +// package. +type Tag struct { + name string + description string +} + +// NewTag creates a new Key for tagging labels. +func NewTag(name, description string) *Tag { + return &Tag{name: name, description: description} +} + +func (k *Tag) Name() string { return k.name } +func (k *Tag) Description() string { return k.description } + +func (k *Tag) Format(w io.Writer, buf []byte, l label.Label) {} + +// New creates a new Label with this key. +func (k *Tag) New() label.Label { return label.OfValue(k, nil) } + +// Int represents a key +type Int struct { + name string + description string +} + +// NewInt creates a new Key for int values. +func NewInt(name, description string) *Int { + return &Int{name: name, description: description} +} + +func (k *Int) Name() string { return k.name } +func (k *Int) Description() string { return k.description } + +func (k *Int) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int) Of(v int) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int) Get(lm label.Map) int { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int) From(t label.Label) int { return int(t.Unpack64()) } + +// Int8 represents a key +type Int8 struct { + name string + description string +} + +// NewInt8 creates a new Key for int8 values. +func NewInt8(name, description string) *Int8 { + return &Int8{name: name, description: description} +} + +func (k *Int8) Name() string { return k.name } +func (k *Int8) Description() string { return k.description } + +func (k *Int8) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int8) Of(v int8) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int8) Get(lm label.Map) int8 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int8) From(t label.Label) int8 { return int8(t.Unpack64()) } + +// Int16 represents a key +type Int16 struct { + name string + description string +} + +// NewInt16 creates a new Key for int16 values. +func NewInt16(name, description string) *Int16 { + return &Int16{name: name, description: description} +} + +func (k *Int16) Name() string { return k.name } +func (k *Int16) Description() string { return k.description } + +func (k *Int16) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int16) Of(v int16) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int16) Get(lm label.Map) int16 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int16) From(t label.Label) int16 { return int16(t.Unpack64()) } + +// Int32 represents a key +type Int32 struct { + name string + description string +} + +// NewInt32 creates a new Key for int32 values. +func NewInt32(name, description string) *Int32 { + return &Int32{name: name, description: description} +} + +func (k *Int32) Name() string { return k.name } +func (k *Int32) Description() string { return k.description } + +func (k *Int32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int32) Of(v int32) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int32) Get(lm label.Map) int32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int32) From(t label.Label) int32 { return int32(t.Unpack64()) } + +// Int64 represents a key +type Int64 struct { + name string + description string +} + +// NewInt64 creates a new Key for int64 values. +func NewInt64(name, description string) *Int64 { + return &Int64{name: name, description: description} +} + +func (k *Int64) Name() string { return k.name } +func (k *Int64) Description() string { return k.description } + +func (k *Int64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, k.From(l), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int64) Of(v int64) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int64) Get(lm label.Map) int64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int64) From(t label.Label) int64 { return int64(t.Unpack64()) } + +// UInt represents a key +type UInt struct { + name string + description string +} + +// NewUInt creates a new Key for uint values. +func NewUInt(name, description string) *UInt { + return &UInt{name: name, description: description} +} + +func (k *UInt) Name() string { return k.name } +func (k *UInt) Description() string { return k.description } + +func (k *UInt) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt) Of(v uint) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt) Get(lm label.Map) uint { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt) From(t label.Label) uint { return uint(t.Unpack64()) } + +// UInt8 represents a key +type UInt8 struct { + name string + description string +} + +// NewUInt8 creates a new Key for uint8 values. +func NewUInt8(name, description string) *UInt8 { + return &UInt8{name: name, description: description} +} + +func (k *UInt8) Name() string { return k.name } +func (k *UInt8) Description() string { return k.description } + +func (k *UInt8) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt8) Of(v uint8) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt8) Get(lm label.Map) uint8 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt8) From(t label.Label) uint8 { return uint8(t.Unpack64()) } + +// UInt16 represents a key +type UInt16 struct { + name string + description string +} + +// NewUInt16 creates a new Key for uint16 values. +func NewUInt16(name, description string) *UInt16 { + return &UInt16{name: name, description: description} +} + +func (k *UInt16) Name() string { return k.name } +func (k *UInt16) Description() string { return k.description } + +func (k *UInt16) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt16) Of(v uint16) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt16) Get(lm label.Map) uint16 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt16) From(t label.Label) uint16 { return uint16(t.Unpack64()) } + +// UInt32 represents a key +type UInt32 struct { + name string + description string +} + +// NewUInt32 creates a new Key for uint32 values. +func NewUInt32(name, description string) *UInt32 { + return &UInt32{name: name, description: description} +} + +func (k *UInt32) Name() string { return k.name } +func (k *UInt32) Description() string { return k.description } + +func (k *UInt32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt32) Of(v uint32) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt32) Get(lm label.Map) uint32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt32) From(t label.Label) uint32 { return uint32(t.Unpack64()) } + +// UInt64 represents a key +type UInt64 struct { + name string + description string +} + +// NewUInt64 creates a new Key for uint64 values. +func NewUInt64(name, description string) *UInt64 { + return &UInt64{name: name, description: description} +} + +func (k *UInt64) Name() string { return k.name } +func (k *UInt64) Description() string { return k.description } + +func (k *UInt64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, k.From(l), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt64) Of(v uint64) label.Label { return label.Of64(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt64) Get(lm label.Map) uint64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt64) From(t label.Label) uint64 { return t.Unpack64() } + +// Float32 represents a key +type Float32 struct { + name string + description string +} + +// NewFloat32 creates a new Key for float32 values. +func NewFloat32(name, description string) *Float32 { + return &Float32{name: name, description: description} +} + +func (k *Float32) Name() string { return k.name } +func (k *Float32) Description() string { return k.description } + +func (k *Float32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendFloat(buf, float64(k.From(l)), 'E', -1, 32)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Float32) Of(v float32) label.Label { + return label.Of64(k, uint64(math.Float32bits(v))) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Float32) Get(lm label.Map) float32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Float32) From(t label.Label) float32 { + return math.Float32frombits(uint32(t.Unpack64())) +} + +// Float64 represents a key +type Float64 struct { + name string + description string +} + +// NewFloat64 creates a new Key for int64 values. +func NewFloat64(name, description string) *Float64 { + return &Float64{name: name, description: description} +} + +func (k *Float64) Name() string { return k.name } +func (k *Float64) Description() string { return k.description } + +func (k *Float64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendFloat(buf, k.From(l), 'E', -1, 64)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Float64) Of(v float64) label.Label { + return label.Of64(k, math.Float64bits(v)) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Float64) Get(lm label.Map) float64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Float64) From(t label.Label) float64 { + return math.Float64frombits(t.Unpack64()) +} + +// String represents a key +type String struct { + name string + description string +} + +// NewString creates a new Key for int64 values. +func NewString(name, description string) *String { + return &String{name: name, description: description} +} + +func (k *String) Name() string { return k.name } +func (k *String) Description() string { return k.description } + +func (k *String) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendQuote(buf, k.From(l))) +} + +// Of creates a new Label with this key and the supplied value. +func (k *String) Of(v string) label.Label { return label.OfString(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *String) Get(lm label.Map) string { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return "" +} + +// From can be used to get a value from a Label. +func (k *String) From(t label.Label) string { return t.UnpackString() } + +// Boolean represents a key +type Boolean struct { + name string + description string +} + +// NewBoolean creates a new Key for bool values. +func NewBoolean(name, description string) *Boolean { + return &Boolean{name: name, description: description} +} + +func (k *Boolean) Name() string { return k.name } +func (k *Boolean) Description() string { return k.description } + +func (k *Boolean) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendBool(buf, k.From(l))) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Boolean) Of(v bool) label.Label { + if v { + return label.Of64(k, 1) + } + return label.Of64(k, 0) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Boolean) Get(lm label.Map) bool { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return false +} + +// From can be used to get a value from a Label. +func (k *Boolean) From(t label.Label) bool { return t.Unpack64() > 0 } + +// Error represents a key +type Error struct { + name string + description string +} + +// NewError creates a new Key for int64 values. +func NewError(name, description string) *Error { + return &Error{name: name, description: description} +} + +func (k *Error) Name() string { return k.name } +func (k *Error) Description() string { return k.description } + +func (k *Error) Format(w io.Writer, buf []byte, l label.Label) { + io.WriteString(w, k.From(l).Error()) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Error) Of(v error) label.Label { return label.OfValue(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Error) Get(lm label.Map) error { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return nil +} + +// From can be used to get a value from a Label. +func (k *Error) From(t label.Label) error { + err, _ := t.UnpackValue().(error) + return err +} diff --git a/vendor/golang.org/x/tools/internal/event/keys/standard.go b/vendor/golang.org/x/tools/internal/event/keys/standard.go new file mode 100644 index 000000000..7e9586659 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/keys/standard.go @@ -0,0 +1,22 @@ +// Copyright 2020 The Go 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 keys + +var ( + // Msg is a key used to add message strings to label lists. + Msg = NewString("message", "a readable message") + // Label is a key used to indicate an event adds labels to the context. + Label = NewTag("label", "a label context marker") + // Start is used for things like traces that have a name. + Start = NewString("start", "span start") + // Metric is a key used to indicate an event records metrics. + End = NewTag("end", "a span end marker") + // Metric is a key used to indicate an event records metrics. + Detach = NewTag("detach", "a span detach marker") + // Err is a key used to add error values to label lists. + Err = NewError("error", "an error that occurred") + // Metric is a key used to indicate an event records metrics. + Metric = NewTag("metric", "a metric event marker") +) diff --git a/vendor/golang.org/x/tools/internal/event/keys/util.go b/vendor/golang.org/x/tools/internal/event/keys/util.go new file mode 100644 index 000000000..c0e8e731c --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/keys/util.go @@ -0,0 +1,21 @@ +// Copyright 2023 The Go 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 keys + +import ( + "sort" + "strings" +) + +// Join returns a canonical join of the keys in S: +// a sorted comma-separated string list. +func Join[S ~[]T, T ~string](s S) string { + strs := make([]string, 0, len(s)) + for _, v := range s { + strs = append(strs, string(v)) + } + sort.Strings(strs) + return strings.Join(strs, ",") +} diff --git a/vendor/golang.org/x/tools/internal/event/label/label.go b/vendor/golang.org/x/tools/internal/event/label/label.go new file mode 100644 index 000000000..92a391057 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/label/label.go @@ -0,0 +1,214 @@ +// Copyright 2019 The Go 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 label + +import ( + "fmt" + "io" + "reflect" + "slices" + "unsafe" +) + +// Key is used as the identity of a Label. +// Keys are intended to be compared by pointer only, the name should be unique +// for communicating with external systems, but it is not required or enforced. +type Key interface { + // Name returns the key name. + Name() string + // Description returns a string that can be used to describe the value. + Description() string + + // Format is used in formatting to append the value of the label to the + // supplied buffer. + // The formatter may use the supplied buf as a scratch area to avoid + // allocations. + Format(w io.Writer, buf []byte, l Label) +} + +// Label holds a key and value pair. +// It is normally used when passing around lists of labels. +type Label struct { + key Key + packed uint64 + untyped any +} + +// Map is the interface to a collection of Labels indexed by key. +type Map interface { + // Find returns the label that matches the supplied key. + Find(key Key) Label +} + +// List is the interface to something that provides an iterable +// list of labels. +// Iteration should start from 0 and continue until Valid returns false. +type List interface { + // Valid returns true if the index is within range for the list. + // It does not imply the label at that index will itself be valid. + Valid(index int) bool + // Label returns the label at the given index. + Label(index int) Label +} + +// list implements LabelList for a list of Labels. +type list struct { + labels []Label +} + +// filter wraps a LabelList filtering out specific labels. +type filter struct { + keys []Key + underlying List +} + +// listMap implements LabelMap for a simple list of labels. +type listMap struct { + labels []Label +} + +// mapChain implements LabelMap for a list of underlying LabelMap. +type mapChain struct { + maps []Map +} + +// OfValue creates a new label from the key and value. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func OfValue(k Key, value any) Label { return Label{key: k, untyped: value} } + +// UnpackValue assumes the label was built using LabelOfValue and returns the value +// that was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) UnpackValue() any { return t.untyped } + +// Of64 creates a new label from a key and a uint64. This is often +// used for non uint64 values that can be packed into a uint64. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func Of64(k Key, v uint64) Label { return Label{key: k, packed: v} } + +// Unpack64 assumes the label was built using LabelOf64 and returns the value that +// was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) Unpack64() uint64 { return t.packed } + +type stringptr unsafe.Pointer + +// OfString creates a new label from a key and a string. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func OfString(k Key, v string) Label { + hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) + return Label{ + key: k, + packed: uint64(hdr.Len), + untyped: stringptr(hdr.Data), + } +} + +// UnpackString assumes the label was built using LabelOfString and returns the +// value that was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) UnpackString() string { + var v string + hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) + hdr.Data = uintptr(t.untyped.(stringptr)) + hdr.Len = int(t.packed) + return v +} + +// Valid returns true if the Label is a valid one (it has a key). +func (t Label) Valid() bool { return t.key != nil } + +// Key returns the key of this Label. +func (t Label) Key() Key { return t.key } + +// Format is used for debug printing of labels. +func (t Label) Format(f fmt.State, r rune) { + if !t.Valid() { + io.WriteString(f, `nil`) + return + } + io.WriteString(f, t.Key().Name()) + io.WriteString(f, "=") + var buf [128]byte + t.Key().Format(f, buf[:0], t) +} + +func (l *list) Valid(index int) bool { + return index >= 0 && index < len(l.labels) +} + +func (l *list) Label(index int) Label { + return l.labels[index] +} + +func (f *filter) Valid(index int) bool { + return f.underlying.Valid(index) +} + +func (f *filter) Label(index int) Label { + l := f.underlying.Label(index) + if slices.Contains(f.keys, l.Key()) { + return Label{} + } + return l +} + +func (lm listMap) Find(key Key) Label { + for _, l := range lm.labels { + if l.Key() == key { + return l + } + } + return Label{} +} + +func (c mapChain) Find(key Key) Label { + for _, src := range c.maps { + l := src.Find(key) + if l.Valid() { + return l + } + } + return Label{} +} + +var emptyList = &list{} + +func NewList(labels ...Label) List { + if len(labels) == 0 { + return emptyList + } + return &list{labels: labels} +} + +func Filter(l List, keys ...Key) List { + if len(keys) == 0 { + return l + } + return &filter{keys: keys, underlying: l} +} + +func NewMap(labels ...Label) Map { + return listMap{labels: labels} +} + +func MergeMaps(srcs ...Map) Map { + var nonNil []Map + for _, src := range srcs { + if src != nil { + nonNil = append(nonNil, src) + } + } + if len(nonNil) == 1 { + return nonNil[0] + } + return mapChain{maps: nonNil} +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/bimport.go b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go new file mode 100644 index 000000000..734c46198 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go @@ -0,0 +1,89 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the remaining vestiges of +// $GOROOT/src/go/internal/gcimporter/bimport.go. + +package gcimporter + +import ( + "fmt" + "go/token" + "go/types" + "sync" +) + +func errorf(format string, args ...any) { + panic(fmt.Sprintf(format, args...)) +} + +const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go + +// Synthesize a token.Pos +type fakeFileSet struct { + fset *token.FileSet + files map[string]*fileInfo +} + +type fileInfo struct { + file *token.File + lastline int +} + +const maxlines = 64 * 1024 + +func (s *fakeFileSet) pos(file string, line, column int) token.Pos { + // TODO(mdempsky): Make use of column. + + // Since we don't know the set of needed file positions, we reserve maxlines + // positions per file. We delay calling token.File.SetLines until all + // positions have been calculated (by way of fakeFileSet.setLines), so that + // we can avoid setting unnecessary lines. See also golang/go#46586. + f := s.files[file] + if f == nil { + f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)} + s.files[file] = f + } + if line > maxlines { + line = 1 + } + if line > f.lastline { + f.lastline = line + } + + // Return a fake position assuming that f.file consists only of newlines. + return token.Pos(f.file.Base() + line - 1) +} + +func (s *fakeFileSet) setLines() { + fakeLinesOnce.Do(func() { + fakeLines = make([]int, maxlines) + for i := range fakeLines { + fakeLines[i] = i + } + }) + for _, f := range s.files { + f.file.SetLines(fakeLines[:f.lastline]) + } +} + +var ( + fakeLines []int + fakeLinesOnce sync.Once +) + +func chanDir(d int) types.ChanDir { + // tag values must match the constants in cmd/compile/internal/gc/go.go + switch d { + case 1 /* Crecv */ : + return types.RecvOnly + case 2 /* Csend */ : + return types.SendOnly + case 3 /* Cboth */ : + return types.SendRecv + default: + errorf("unexpected channel dir %d", d) + return 0 + } +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go b/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go new file mode 100644 index 000000000..5662a311d --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go @@ -0,0 +1,421 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file should be kept in sync with $GOROOT/src/internal/exportdata/exportdata.go. +// This file also additionally implements FindExportData for gcexportdata.NewReader. + +package gcimporter + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "go/build" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" +) + +// FindExportData positions the reader r at the beginning of the +// export data section of an underlying cmd/compile created archive +// file by reading from it. The reader must be positioned at the +// start of the file before calling this function. +// This returns the length of the export data in bytes. +// +// This function is needed by [gcexportdata.Read], which must +// accept inputs produced by the last two releases of cmd/compile, +// plus tip. +func FindExportData(r *bufio.Reader) (size int64, err error) { + arsize, err := FindPackageDefinition(r) + if err != nil { + return + } + size = int64(arsize) + + objapi, headers, err := ReadObjectHeaders(r) + if err != nil { + return + } + size -= int64(len(objapi)) + for _, h := range headers { + size -= int64(len(h)) + } + + // Check for the binary export data section header "$$B\n". + // TODO(taking): Unify with ReadExportDataHeader so that it stops at the 'u' instead of reading + line, err := r.ReadSlice('\n') + if err != nil { + return + } + hdr := string(line) + if hdr != "$$B\n" { + err = fmt.Errorf("unknown export data header: %q", hdr) + return + } + size -= int64(len(hdr)) + + // For files with a binary export data header "$$B\n", + // these are always terminated by an end-of-section marker "\n$$\n". + // So the last bytes must always be this constant. + // + // The end-of-section marker is not a part of the export data itself. + // Do not include these in size. + // + // It would be nice to have sanity check that the final bytes after + // the export data are indeed the end-of-section marker. The split + // of gcexportdata.NewReader and gcexportdata.Read make checking this + // ugly so gcimporter gives up enforcing this. The compiler and go/types + // importer do enforce this, which seems good enough. + const endofsection = "\n$$\n" + size -= int64(len(endofsection)) + + if size < 0 { + err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", arsize, size) + return + } + + return +} + +// ReadUnified reads the contents of the unified export data from a reader r +// that contains the contents of a GC-created archive file. +// +// On success, the reader will be positioned after the end-of-section marker "\n$$\n". +// +// Supported GC-created archive files have 4 layers of nesting: +// - An archive file containing a package definition file. +// - The package definition file contains headers followed by a data section. +// Headers are lines (≤ 4kb) that do not start with "$$". +// - The data section starts with "$$B\n" followed by export data followed +// by an end of section marker "\n$$\n". (The section start "$$\n" is no +// longer supported.) +// - The export data starts with a format byte ('u') followed by the in +// the given format. (See ReadExportDataHeader for older formats.) +// +// Putting this together, the bytes in a GC-created archive files are expected +// to look like the following. +// See cmd/internal/archive for more details on ar file headers. +// +// | \n | ar file signature +// | __.PKGDEF...size...\n | ar header for __.PKGDEF including size. +// | go object <...>\n | objabi header +// | \n | other headers such as build id +// | $$B\n | binary format marker +// | u\n | unified export +// | $$\n | end-of-section marker +// | [optional padding] | padding byte (0x0A) if size is odd +// | [ar file header] | other ar files +// | [ar file data] | +func ReadUnified(r *bufio.Reader) (data []byte, err error) { + // We historically guaranteed headers at the default buffer size (4096) work. + // This ensures we can use ReadSlice throughout. + const minBufferSize = 4096 + r = bufio.NewReaderSize(r, minBufferSize) + + size, err := FindPackageDefinition(r) + if err != nil { + return + } + n := size + + objapi, headers, err := ReadObjectHeaders(r) + if err != nil { + return + } + n -= len(objapi) + for _, h := range headers { + n -= len(h) + } + + hdrlen, err := ReadExportDataHeader(r) + if err != nil { + return + } + n -= hdrlen + + // size also includes the end of section marker. Remove that many bytes from the end. + const marker = "\n$$\n" + n -= len(marker) + + if n < 0 { + err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", size, n) + return + } + + // Read n bytes from buf. + data = make([]byte, n) + _, err = io.ReadFull(r, data) + if err != nil { + return + } + + // Check for marker at the end. + var suffix [len(marker)]byte + _, err = io.ReadFull(r, suffix[:]) + if err != nil { + return + } + if s := string(suffix[:]); s != marker { + err = fmt.Errorf("read %q instead of end-of-section marker (%q)", s, marker) + return + } + + return +} + +// FindPackageDefinition positions the reader r at the beginning of a package +// definition file ("__.PKGDEF") within a GC-created archive by reading +// from it, and returns the size of the package definition file in the archive. +// +// The reader must be positioned at the start of the archive file before calling +// this function, and "__.PKGDEF" is assumed to be the first file in the archive. +// +// See cmd/internal/archive for details on the archive format. +func FindPackageDefinition(r *bufio.Reader) (size int, err error) { + // Uses ReadSlice to limit risk of malformed inputs. + + // Read first line to make sure this is an object file. + line, err := r.ReadSlice('\n') + if err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + + // Is the first line an archive file signature? + if string(line) != "!\n" { + err = fmt.Errorf("not the start of an archive file (%q)", line) + return + } + + // package export block should be first + size = readArchiveHeader(r, "__.PKGDEF") + if size <= 0 { + err = fmt.Errorf("not a package file") + return + } + + return +} + +// ReadObjectHeaders reads object headers from the reader. Object headers are +// lines that do not start with an end-of-section marker "$$". The first header +// is the objabi header. On success, the reader will be positioned at the beginning +// of the end-of-section marker. +// +// It returns an error if any header does not fit in r.Size() bytes. +func ReadObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) { + // line is a temporary buffer for headers. + // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs. + var line []byte + + // objapi header should be the first line + if line, err = r.ReadSlice('\n'); err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + objapi = string(line) + + // objapi header begins with "go object ". + if !strings.HasPrefix(objapi, "go object ") { + err = fmt.Errorf("not a go object file: %s", objapi) + return + } + + // process remaining object header lines + for { + // check for an end of section marker "$$" + line, err = r.Peek(2) + if err != nil { + return + } + if string(line) == "$$" { + return // stop + } + + // read next header + line, err = r.ReadSlice('\n') + if err != nil { + return + } + headers = append(headers, string(line)) + } +} + +// ReadExportDataHeader reads the export data header and format from r. +// It returns the number of bytes read, or an error if the format is no longer +// supported or it failed to read. +// +// The only currently supported format is binary export data in the +// unified export format. +func ReadExportDataHeader(r *bufio.Reader) (n int, err error) { + // Read export data header. + line, err := r.ReadSlice('\n') + if err != nil { + return + } + + hdr := string(line) + switch hdr { + case "$$\n": + err = fmt.Errorf("old textual export format no longer supported (recompile package)") + return + + case "$$B\n": + var format byte + format, err = r.ReadByte() + if err != nil { + return + } + // The unified export format starts with a 'u'. + switch format { + case 'u': + default: + // Older no longer supported export formats include: + // indexed export format which started with an 'i'; and + // the older binary export format which started with a 'c', + // 'd', or 'v' (from "version"). + err = fmt.Errorf("binary export format %q is no longer supported (recompile package)", format) + return + } + + default: + err = fmt.Errorf("unknown export data header: %q", hdr) + return + } + + n = len(hdr) + 1 // + 1 is for 'u' + return +} + +// FindPkg returns the filename and unique package id for an import +// path based on package information provided by build.Import (using +// the build.Default build.Context). A relative srcDir is interpreted +// relative to the current working directory. +// +// FindPkg is only used in tests within x/tools. +func FindPkg(path, srcDir string) (filename, id string, err error) { + // TODO(taking): Move internal/exportdata.FindPkg into its own file, + // and then this copy into a _test package. + if path == "" { + return "", "", errors.New("path is empty") + } + + var noext string + switch { + default: + // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" + // Don't require the source files to be present. + if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282 + srcDir = abs + } + var bp *build.Package + bp, err = build.Import(path, srcDir, build.FindOnly|build.AllowBinary) + if bp.PkgObj == "" { + if bp.Goroot && bp.Dir != "" { + filename, err = lookupGorootExport(bp.Dir) + if err == nil { + _, err = os.Stat(filename) + } + if err == nil { + return filename, bp.ImportPath, nil + } + } + goto notfound + } else { + noext = strings.TrimSuffix(bp.PkgObj, ".a") + } + id = bp.ImportPath + + case build.IsLocalImport(path): + // "./x" -> "/this/directory/x.ext", "/this/directory/x" + noext = filepath.Join(srcDir, path) + id = noext + + case filepath.IsAbs(path): + // for completeness only - go/build.Import + // does not support absolute imports + // "/x" -> "/x.ext", "/x" + noext = path + id = path + } + + if false { // for debugging + if path != id { + fmt.Printf("%s -> %s\n", path, id) + } + } + + // try extensions + for _, ext := range pkgExts { + filename = noext + ext + f, statErr := os.Stat(filename) + if statErr == nil && !f.IsDir() { + return filename, id, nil + } + if err == nil { + err = statErr + } + } + +notfound: + if err == nil { + return "", path, fmt.Errorf("can't find import: %q", path) + } + return "", path, fmt.Errorf("can't find import: %q: %w", path, err) +} + +var pkgExts = [...]string{".a", ".o"} // a file from the build cache will have no extension + +var exportMap sync.Map // package dir → func() (string, error) + +// lookupGorootExport returns the location of the export data +// (normally found in the build cache, but located in GOROOT/pkg +// in prior Go releases) for the package located in pkgDir. +// +// (We use the package's directory instead of its import path +// mainly to simplify handling of the packages in src/vendor +// and cmd/vendor.) +// +// lookupGorootExport is only used in tests within x/tools. +func lookupGorootExport(pkgDir string) (string, error) { + f, ok := exportMap.Load(pkgDir) + if !ok { + var ( + listOnce sync.Once + exportPath string + err error + ) + f, _ = exportMap.LoadOrStore(pkgDir, func() (string, error) { + listOnce.Do(func() { + cmd := exec.Command(filepath.Join(build.Default.GOROOT, "bin", "go"), "list", "-export", "-f", "{{.Export}}", pkgDir) + cmd.Dir = build.Default.GOROOT + cmd.Env = append(os.Environ(), "PWD="+cmd.Dir, "GOROOT="+build.Default.GOROOT) + var output []byte + output, err = cmd.Output() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { + err = errors.New(string(ee.Stderr)) + } + return + } + + exports := strings.Split(string(bytes.TrimSpace(output)), "\n") + if len(exports) != 1 { + err = fmt.Errorf("go list reported %d exports; expected 1", len(exports)) + return + } + + exportPath = exports[0] + }) + + return exportPath, err + }) + } + + return f.(func() (string, error))() +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go new file mode 100644 index 000000000..3dbd21d1b --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -0,0 +1,108 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a reduced copy of $GOROOT/src/go/internal/gcimporter/gcimporter.go. + +// Package gcimporter provides various functions for reading +// gc-generated object files that can be used to implement the +// Importer interface defined by the Go 1.5 standard library package. +// +// The encoding is deterministic: if the encoder is applied twice to +// the same types.Package data structure, both encodings are equal. +// This property may be important to avoid spurious changes in +// applications such as build systems. +// +// However, the encoder is not necessarily idempotent. Importing an +// exported package may yield a types.Package that, while it +// represents the same set of Go types as the original, may differ in +// the details of its internal representation. Because of these +// differences, re-encoding the imported package may yield a +// different, but equally valid, encoding of the package. +package gcimporter // import "golang.org/x/tools/internal/gcimporter" + +import ( + "bufio" + "fmt" + "go/token" + "go/types" + "io" + "os" +) + +const ( + // Enable debug during development: it adds some additional checks, and + // prevents errors from being recovered. + debug = false + + // If trace is set, debugging output is printed to std out. + trace = false +) + +// Import imports a gc-generated package given its import path and srcDir, adds +// the corresponding package object to the packages map, and returns the object. +// The packages map must contain all packages already imported. +// +// Import is only used in tests. +func Import(fset *token.FileSet, packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) { + var rc io.ReadCloser + var id string + if lookup != nil { + // With custom lookup specified, assume that caller has + // converted path to a canonical import path for use in the map. + if path == "unsafe" { + return types.Unsafe, nil + } + id = path + + // No need to re-import if the package was imported completely before. + if pkg = packages[id]; pkg != nil && pkg.Complete() { + return + } + f, err := lookup(path) + if err != nil { + return nil, err + } + rc = f + } else { + var filename string + filename, id, err = FindPkg(path, srcDir) + if filename == "" { + if path == "unsafe" { + return types.Unsafe, nil + } + return nil, err + } + + // no need to re-import if the package was imported completely before + if pkg = packages[id]; pkg != nil && pkg.Complete() { + return + } + + // open file + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + if err != nil { + // add file name to error + err = fmt.Errorf("%s: %v", filename, err) + } + }() + rc = f + } + defer rc.Close() + + buf := bufio.NewReader(rc) + data, err := ReadUnified(buf) + if err != nil { + err = fmt.Errorf("import %q: %v", path, err) + return + } + + // unified: emitted by cmd/compile since go1.20. + _, pkg, err = UImportData(fset, packages, data, id) + + return +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go new file mode 100644 index 000000000..780873e3a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go @@ -0,0 +1,1596 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Indexed package export. +// +// The indexed export data format is an evolution of the previous +// binary export data format. Its chief contribution is introducing an +// index table, which allows efficient random access of individual +// declarations and inline function bodies. In turn, this allows +// avoiding unnecessary work for compilation units that import large +// packages. +// +// +// The top-level data format is structured as: +// +// Header struct { +// Tag byte // 'i' +// Version uvarint +// StringSize uvarint +// DataSize uvarint +// } +// +// Strings [StringSize]byte +// Data [DataSize]byte +// +// MainIndex []struct{ +// PkgPath stringOff +// PkgName stringOff +// PkgHeight uvarint +// +// Decls []struct{ +// Name stringOff +// Offset declOff +// } +// } +// +// Fingerprint [8]byte +// +// uvarint means a uint64 written out using uvarint encoding. +// +// []T means a uvarint followed by that many T objects. In other +// words: +// +// Len uvarint +// Elems [Len]T +// +// stringOff means a uvarint that indicates an offset within the +// Strings section. At that offset is another uvarint, followed by +// that many bytes, which form the string value. +// +// declOff means a uvarint that indicates an offset within the Data +// section where the associated declaration can be found. +// +// +// There are five kinds of declarations, distinguished by their first +// byte: +// +// type Var struct { +// Tag byte // 'V' +// Pos Pos +// Type typeOff +// } +// +// type Func struct { +// Tag byte // 'F' or 'G' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'G' +// Signature Signature +// } +// +// type Const struct { +// Tag byte // 'C' +// Pos Pos +// Value Value +// } +// +// type Type struct { +// Tag byte // 'T' or 'U' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'U' +// Underlying typeOff +// +// Methods []struct{ // omitted if Underlying is an interface type +// Pos Pos +// Name stringOff +// Recv Param +// Signature Signature +// } +// } +// +// type Alias struct { +// Tag byte // 'A' or 'B' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'B' +// Type typeOff +// } +// +// // "Automatic" declaration of each typeparam +// type TypeParam struct { +// Tag byte // 'P' +// Pos Pos +// Implicit bool +// Constraint typeOff +// } +// +// typeOff means a uvarint that either indicates a predeclared type, +// or an offset into the Data section. If the uvarint is less than +// predeclReserved, then it indicates the index into the predeclared +// types list (see predeclared in bexport.go for order). Otherwise, +// subtracting predeclReserved yields the offset of a type descriptor. +// +// Value means a type, kind, and type-specific value. See +// (*exportWriter).value for details. +// +// +// There are twelve kinds of type descriptors, distinguished by an itag: +// +// type DefinedType struct { +// Tag itag // definedType +// Name stringOff +// PkgPath stringOff +// } +// +// type PointerType struct { +// Tag itag // pointerType +// Elem typeOff +// } +// +// type SliceType struct { +// Tag itag // sliceType +// Elem typeOff +// } +// +// type ArrayType struct { +// Tag itag // arrayType +// Len uint64 +// Elem typeOff +// } +// +// type ChanType struct { +// Tag itag // chanType +// Dir uint64 // 1 RecvOnly; 2 SendOnly; 3 SendRecv +// Elem typeOff +// } +// +// type MapType struct { +// Tag itag // mapType +// Key typeOff +// Elem typeOff +// } +// +// type FuncType struct { +// Tag itag // signatureType +// PkgPath stringOff +// Signature Signature +// } +// +// type StructType struct { +// Tag itag // structType +// PkgPath stringOff +// Fields []struct { +// Pos Pos +// Name stringOff +// Type typeOff +// Embedded bool +// Note stringOff +// } +// } +// +// type InterfaceType struct { +// Tag itag // interfaceType +// PkgPath stringOff +// Embeddeds []struct { +// Pos Pos +// Type typeOff +// } +// Methods []struct { +// Pos Pos +// Name stringOff +// Signature Signature +// } +// } +// +// // Reference to a type param declaration +// type TypeParamType struct { +// Tag itag // typeParamType +// Name stringOff +// PkgPath stringOff +// } +// +// // Instantiation of a generic type (like List[T2] or List[int]) +// type InstanceType struct { +// Tag itag // instanceType +// Pos pos +// TypeArgs []typeOff +// BaseType typeOff +// } +// +// type UnionType struct { +// Tag itag // interfaceType +// Terms []struct { +// tilde bool +// Type typeOff +// } +// } +// +// +// +// type Signature struct { +// Params []Param +// Results []Param +// Variadic bool // omitted if Results is empty +// } +// +// type Param struct { +// Pos Pos +// Name stringOff +// Type typOff +// } +// +// +// Pos encodes a file:line:column triple, incorporating a simple delta +// encoding scheme within a data object. See exportWriter.pos for +// details. + +package gcimporter + +import ( + "bytes" + "encoding/binary" + "fmt" + "go/constant" + "go/token" + "go/types" + "io" + "math/big" + "reflect" + "slices" + "sort" + "strconv" + "strings" + + "golang.org/x/tools/go/types/objectpath" + "golang.org/x/tools/internal/aliases" +) + +// IExportShallow encodes "shallow" export data for the specified package. +// +// For types, we use "shallow" export data. Historically, the Go +// compiler always produced a summary of the types for a given package +// that included types from other packages that it indirectly +// referenced: "deep" export data. This had the advantage that the +// compiler (and analogous tools such as gopls) need only load one +// file per direct import. However, it meant that the files tended to +// get larger based on the level of the package in the import +// graph. For example, higher-level packages in the kubernetes module +// have over 1MB of "deep" export data, even when they have almost no +// content of their own, merely because they mention a major type that +// references many others. In pathological cases the export data was +// 300x larger than the source for a package due to this quadratic +// growth. +// +// "Shallow" export data means that the serialized types describe only +// a single package. If those types mention types from other packages, +// the type checker may need to request additional packages beyond +// just the direct imports. Type information for the entire transitive +// closure of imports is provided (lazily) by the DAG. +// +// No promises are made about the encoding other than that it can be decoded by +// the same version of IIExportShallow. If you plan to save export data in the +// file system, be sure to include a cryptographic digest of the executable in +// the key to avoid version skew. +// +// If the provided reportf func is non-nil, it is used for reporting +// bugs (e.g. recovered panics) encountered during export, enabling us +// to obtain via telemetry the stack that would otherwise be lost by +// merely returning an error. +func IExportShallow(fset *token.FileSet, pkg *types.Package, reportf ReportFunc) ([]byte, error) { + // In principle this operation can only fail if out.Write fails, + // but that's impossible for bytes.Buffer---and as a matter of + // fact iexportCommon doesn't even check for I/O errors. + // TODO(adonovan): handle I/O errors properly. + // TODO(adonovan): use byte slices throughout, avoiding copying. + const bundle, shallow = false, true + var out bytes.Buffer + err := iexportCommon(&out, fset, bundle, shallow, iexportVersion, []*types.Package{pkg}, reportf) + return out.Bytes(), err +} + +// IImportShallow decodes "shallow" types.Package data encoded by +// [IExportShallow] in the same executable. This function cannot import data +// from cmd/compile or gcexportdata.Write. +// +// The importer calls getPackages to obtain package symbols for all +// packages mentioned in the export data, including the one being +// decoded. +// +// If the provided reportf func is non-nil, it will be used for reporting bugs +// encountered during import. +// TODO(rfindley): remove reportf when we are confident enough in the new +// objectpath encoding. +func IImportShallow(fset *token.FileSet, getPackages GetPackagesFunc, data []byte, path string, reportf ReportFunc) (*types.Package, error) { + const bundle = false + const shallow = true + pkgs, err := iimportCommon(fset, getPackages, data, bundle, path, shallow, reportf) + if err != nil { + return nil, err + } + return pkgs[0], nil +} + +// ReportFunc is the type of a function used to report formatted bugs. +type ReportFunc = func(string, ...any) + +// Current bundled export format version. Increase with each format change. +// 0: initial implementation +const bundleVersion = 0 + +// IExportData writes indexed export data for pkg to out. +// +// If no file set is provided, position info will be missing. +// The package path of the top-level package will not be recorded, +// so that calls to IImportData can override with a provided package path. +func IExportData(out io.Writer, fset *token.FileSet, pkg *types.Package) error { + const bundle, shallow = false, false + return iexportCommon(out, fset, bundle, shallow, iexportVersion, []*types.Package{pkg}, nil) +} + +// IExportBundle writes an indexed export bundle for pkgs to out. +func IExportBundle(out io.Writer, fset *token.FileSet, pkgs []*types.Package) error { + const bundle, shallow = true, false + return iexportCommon(out, fset, bundle, shallow, iexportVersion, pkgs, nil) +} + +func iexportCommon(out io.Writer, fset *token.FileSet, bundle, shallow bool, version int, pkgs []*types.Package, reportf ReportFunc) (err error) { + if !debug { + defer func() { + if e := recover(); e != nil { + // Report the stack via telemetry (see #71067). + if reportf != nil { + reportf("panic in exporter") + } + if ierr, ok := e.(internalError); ok { + // internalError usually means we exported a + // bad go/types data structure: a violation + // of an implicit precondition of Export. + err = ierr + return + } + // Not an internal error; panic again. + panic(e) + } + }() + } + + p := iexporter{ + fset: fset, + version: version, + shallow: shallow, + allPkgs: map[*types.Package]bool{}, + stringIndex: map[string]uint64{}, + declIndex: map[types.Object]uint64{}, + tparamNames: map[types.Object]string{}, + typIndex: map[types.Type]uint64{}, + } + if !bundle { + p.localpkg = pkgs[0] + } + + for i, pt := range predeclared() { + p.typIndex[pt] = uint64(i) + } + if len(p.typIndex) > predeclReserved { + panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved)) + } + + // Initialize work queue with exported declarations. + for _, pkg := range pkgs { + scope := pkg.Scope() + for _, name := range scope.Names() { + if token.IsExported(name) { + p.pushDecl(scope.Lookup(name)) + } + } + + if bundle { + // Ensure pkg and its imports are included in the index. + p.allPkgs[pkg] = true + for _, imp := range pkg.Imports() { + p.allPkgs[imp] = true + } + } + } + + // Loop until no more work. + for !p.declTodo.empty() { + p.doDecl(p.declTodo.popHead()) + } + + // Produce index of offset of each file record in files. + var files intWriter + var fileOffset []uint64 // fileOffset[i] is offset in files of file encoded as i + if p.shallow { + fileOffset = make([]uint64, len(p.fileInfos)) + for i, info := range p.fileInfos { + fileOffset[i] = uint64(files.Len()) + p.encodeFile(&files, info.file, info.needed) + } + } + + // Append indices to data0 section. + dataLen := uint64(p.data0.Len()) + w := p.newWriter() + w.writeIndex(p.declIndex) + + if bundle { + w.uint64(uint64(len(pkgs))) + for _, pkg := range pkgs { + w.pkg(pkg) + imps := pkg.Imports() + w.uint64(uint64(len(imps))) + for _, imp := range imps { + w.pkg(imp) + } + } + } + w.flush() + + // Assemble header. + var hdr intWriter + if bundle { + hdr.uint64(bundleVersion) + } + hdr.uint64(uint64(p.version)) + hdr.uint64(uint64(p.strings.Len())) + if p.shallow { + hdr.uint64(uint64(files.Len())) + hdr.uint64(uint64(len(fileOffset))) + for _, offset := range fileOffset { + hdr.uint64(offset) + } + } + hdr.uint64(dataLen) + + // Flush output. + io.Copy(out, &hdr) + io.Copy(out, &p.strings) + if p.shallow { + io.Copy(out, &files) + } + io.Copy(out, &p.data0) + + return nil +} + +// encodeFile writes to w a representation of the file sufficient to +// faithfully restore position information about all needed offsets. +// Mutates the needed array. +func (p *iexporter) encodeFile(w *intWriter, file *token.File, needed []uint64) { + _ = needed[0] // precondition: needed is non-empty + + w.uint64(p.stringOff(file.Name())) + + size := uint64(file.Size()) + w.uint64(size) + + // Sort the set of needed offsets. Duplicates are harmless. + slices.Sort(needed) + + lines := file.Lines() // byte offset of each line start + w.uint64(uint64(len(lines))) + + // Rather than record the entire array of line start offsets, + // we save only a sparse list of (index, offset) pairs for + // the start of each line that contains a needed position. + var sparse [][2]int // (index, offset) pairs +outer: + for i, lineStart := range lines { + lineEnd := size + if i < len(lines)-1 { + lineEnd = uint64(lines[i+1]) + } + // Does this line contains a needed offset? + if needed[0] < lineEnd { + sparse = append(sparse, [2]int{i, lineStart}) + for needed[0] < lineEnd { + needed = needed[1:] + if len(needed) == 0 { + break outer + } + } + } + } + + // Delta-encode the columns. + w.uint64(uint64(len(sparse))) + var prev [2]int + for _, pair := range sparse { + w.uint64(uint64(pair[0] - prev[0])) + w.uint64(uint64(pair[1] - prev[1])) + prev = pair + } +} + +// writeIndex writes out an object index. mainIndex indicates whether +// we're writing out the main index, which is also read by +// non-compiler tools and includes a complete package description +// (i.e., name and height). +func (w *exportWriter) writeIndex(index map[types.Object]uint64) { + type pkgObj struct { + obj types.Object + name string // qualified name; differs from obj.Name for type params + } + // Build a map from packages to objects from that package. + pkgObjs := map[*types.Package][]pkgObj{} + + // For the main index, make sure to include every package that + // we reference, even if we're not exporting (or reexporting) + // any symbols from it. + if w.p.localpkg != nil { + pkgObjs[w.p.localpkg] = nil + } + for pkg := range w.p.allPkgs { + pkgObjs[pkg] = nil + } + + for obj := range index { + name := w.p.exportName(obj) + pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], pkgObj{obj, name}) + } + + var pkgs []*types.Package + for pkg, objs := range pkgObjs { + pkgs = append(pkgs, pkg) + + sort.Slice(objs, func(i, j int) bool { + return objs[i].name < objs[j].name + }) + } + + sort.Slice(pkgs, func(i, j int) bool { + return w.exportPath(pkgs[i]) < w.exportPath(pkgs[j]) + }) + + w.uint64(uint64(len(pkgs))) + for _, pkg := range pkgs { + w.string(w.exportPath(pkg)) + w.string(pkg.Name()) + w.uint64(uint64(0)) // package height is not needed for go/types + + objs := pkgObjs[pkg] + w.uint64(uint64(len(objs))) + for _, obj := range objs { + w.string(obj.name) + w.uint64(index[obj.obj]) + } + } +} + +// exportName returns the 'exported' name of an object. It differs from +// obj.Name() only for type parameters (see tparamExportName for details). +func (p *iexporter) exportName(obj types.Object) (res string) { + if name := p.tparamNames[obj]; name != "" { + return name + } + return obj.Name() +} + +type iexporter struct { + fset *token.FileSet + out *bytes.Buffer + version int + + shallow bool // don't put types from other packages in the index + objEncoder *objectpath.Encoder // encodes objects from other packages in shallow mode; lazily allocated + localpkg *types.Package // (nil in bundle mode) + + // allPkgs tracks all packages that have been referenced by + // the export data, so we can ensure to include them in the + // main index. + allPkgs map[*types.Package]bool + + declTodo objQueue + + strings intWriter + stringIndex map[string]uint64 + + // In shallow mode, object positions are encoded as (file, offset). + // Each file is recorded as a line-number table. + // Only the lines of needed positions are saved faithfully. + fileInfo map[*token.File]uint64 // value is index in fileInfos + fileInfos []*filePositions + + data0 intWriter + declIndex map[types.Object]uint64 + tparamNames map[types.Object]string // typeparam->exported name + typIndex map[types.Type]uint64 + + indent int // for tracing support +} + +type filePositions struct { + file *token.File + needed []uint64 // unordered list of needed file offsets +} + +func (p *iexporter) trace(format string, args ...any) { + if !trace { + // Call sites should also be guarded, but having this check here allows + // easily enabling/disabling debug trace statements. + return + } + fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...) +} + +// objectpathEncoder returns the lazily allocated objectpath.Encoder to use +// when encoding objects in other packages during shallow export. +// +// Using a shared Encoder amortizes some of cost of objectpath search. +func (p *iexporter) objectpathEncoder() *objectpath.Encoder { + if p.objEncoder == nil { + p.objEncoder = new(objectpath.Encoder) + } + return p.objEncoder +} + +// stringOff returns the offset of s within the string section. +// If not already present, it's added to the end. +func (p *iexporter) stringOff(s string) uint64 { + off, ok := p.stringIndex[s] + if !ok { + off = uint64(p.strings.Len()) + p.stringIndex[s] = off + + p.strings.uint64(uint64(len(s))) + p.strings.WriteString(s) + } + return off +} + +// fileIndexAndOffset returns the index of the token.File and the byte offset of pos within it. +func (p *iexporter) fileIndexAndOffset(file *token.File, pos token.Pos) (uint64, uint64) { + index, ok := p.fileInfo[file] + if !ok { + index = uint64(len(p.fileInfo)) + p.fileInfos = append(p.fileInfos, &filePositions{file: file}) + if p.fileInfo == nil { + p.fileInfo = make(map[*token.File]uint64) + } + p.fileInfo[file] = index + } + // Record each needed offset. + info := p.fileInfos[index] + offset := uint64(file.Offset(pos)) + info.needed = append(info.needed, offset) + + return index, offset +} + +// pushDecl adds n to the declaration work queue, if not already present. +func (p *iexporter) pushDecl(obj types.Object) { + // Package unsafe is known to the compiler and predeclared. + // Caller should not ask us to do export it. + if obj.Pkg() == types.Unsafe { + panic("cannot export package unsafe") + } + + // Shallow export data: don't index decls from other packages. + if p.shallow && obj.Pkg() != p.localpkg { + return + } + + if _, ok := p.declIndex[obj]; ok { + return + } + + p.declIndex[obj] = ^uint64(0) // mark obj present in work queue + p.declTodo.pushTail(obj) +} + +// exportWriter handles writing out individual data section chunks. +type exportWriter struct { + p *iexporter + + data intWriter + prevFile string + prevLine int64 + prevColumn int64 +} + +func (w *exportWriter) exportPath(pkg *types.Package) string { + if pkg == w.p.localpkg { + return "" + } + return pkg.Path() +} + +func (p *iexporter) doDecl(obj types.Object) { + if trace { + p.trace("exporting decl %v (%T)", obj, obj) + p.indent++ + defer func() { + p.indent-- + p.trace("=> %s", obj) + }() + } + w := p.newWriter() + + switch obj := obj.(type) { + case *types.Var: + w.tag(varTag) + w.pos(obj.Pos()) + w.typ(obj.Type(), obj.Pkg()) + + case *types.Func: + sig, _ := obj.Type().(*types.Signature) + if sig.Recv() != nil { + // We shouldn't see methods in the package scope, + // but the type checker may repair "func () F() {}" + // to "func (Invalid) F()" and then treat it like "func F()", + // so allow that. See golang/go#57729. + if sig.Recv().Type() != types.Typ[types.Invalid] { + panic(internalErrorf("unexpected method: %v", sig)) + } + } + + // Function. + if sig.TypeParams().Len() == 0 { + w.tag(funcTag) + } else { + w.tag(genericFuncTag) + } + w.pos(obj.Pos()) + // The tparam list of the function type is the declaration of the type + // params. So, write out the type params right now. Then those type params + // will be referenced via their type offset (via typOff) in all other + // places in the signature and function where they are used. + // + // While importing the type parameters, tparamList computes and records + // their export name, so that it can be later used when writing the index. + if tparams := sig.TypeParams(); tparams.Len() > 0 { + w.tparamList(obj.Name(), tparams, obj.Pkg()) + } + w.signature(sig) + + case *types.Const: + w.tag(constTag) + w.pos(obj.Pos()) + w.value(obj.Type(), obj.Val()) + + case *types.TypeName: + t := obj.Type() + + if tparam, ok := types.Unalias(t).(*types.TypeParam); ok { + w.tag(typeParamTag) + w.pos(obj.Pos()) + constraint := tparam.Constraint() + if p.version >= iexportVersionGo1_18 { + implicit := false + if iface, _ := types.Unalias(constraint).(*types.Interface); iface != nil { + implicit = iface.IsImplicit() + } + w.bool(implicit) + } + w.typ(constraint, obj.Pkg()) + break + } + + if obj.IsAlias() { + alias, materialized := t.(*types.Alias) // may fail when aliases are not enabled + + var tparams *types.TypeParamList + if materialized { + tparams = aliases.TypeParams(alias) + } + if tparams.Len() == 0 { + w.tag(aliasTag) + } else { + w.tag(genericAliasTag) + } + w.pos(obj.Pos()) + if tparams.Len() > 0 { + w.tparamList(obj.Name(), tparams, obj.Pkg()) + } + if materialized { + // Preserve materialized aliases, + // even of non-exported types. + t = aliases.Rhs(alias) + } + w.typ(t, obj.Pkg()) + break + } + + // Defined type. + named, ok := t.(*types.Named) + if !ok { + panic(internalErrorf("%s is not a defined type", t)) + } + + if named.TypeParams().Len() == 0 { + w.tag(typeTag) + } else { + w.tag(genericTypeTag) + } + w.pos(obj.Pos()) + + if named.TypeParams().Len() > 0 { + // While importing the type parameters, tparamList computes and records + // their export name, so that it can be later used when writing the index. + w.tparamList(obj.Name(), named.TypeParams(), obj.Pkg()) + } + + underlying := named.Underlying() + w.typ(underlying, obj.Pkg()) + + if types.IsInterface(t) { + break + } + + n := named.NumMethods() + w.uint64(uint64(n)) + for i := range n { + m := named.Method(i) + w.pos(m.Pos()) + w.string(m.Name()) + sig, _ := m.Type().(*types.Signature) + + // Receiver type parameters are type arguments of the receiver type, so + // their name must be qualified before exporting recv. + if rparams := sig.RecvTypeParams(); rparams.Len() > 0 { + prefix := obj.Name() + "." + m.Name() + for i := 0; i < rparams.Len(); i++ { + rparam := rparams.At(i) + name := tparamExportName(prefix, rparam) + w.p.tparamNames[rparam.Obj()] = name + } + } + w.param(sig.Recv()) + w.signature(sig) + } + + default: + panic(internalErrorf("unexpected object: %v", obj)) + } + + p.declIndex[obj] = w.flush() +} + +func (w *exportWriter) tag(tag byte) { + w.data.WriteByte(tag) +} + +func (w *exportWriter) pos(pos token.Pos) { + if w.p.shallow { + w.posV2(pos) + } else if w.p.version >= iexportVersionPosCol { + w.posV1(pos) + } else { + w.posV0(pos) + } +} + +// posV2 encoding (used only in shallow mode) records positions as +// (file, offset), where file is the index in the token.File table +// (which records the file name and newline offsets) and offset is a +// byte offset. It effectively ignores //line directives. +func (w *exportWriter) posV2(pos token.Pos) { + if pos == token.NoPos { + w.uint64(0) + return + } + file := w.p.fset.File(pos) // fset must be non-nil + index, offset := w.p.fileIndexAndOffset(file, pos) + w.uint64(1 + index) + w.uint64(offset) +} + +func (w *exportWriter) posV1(pos token.Pos) { + if w.p.fset == nil { + w.int64(0) + return + } + + p := w.p.fset.Position(pos) + file := p.Filename + line := int64(p.Line) + column := int64(p.Column) + + deltaColumn := (column - w.prevColumn) << 1 + deltaLine := (line - w.prevLine) << 1 + + if file != w.prevFile { + deltaLine |= 1 + } + if deltaLine != 0 { + deltaColumn |= 1 + } + + w.int64(deltaColumn) + if deltaColumn&1 != 0 { + w.int64(deltaLine) + if deltaLine&1 != 0 { + w.string(file) + } + } + + w.prevFile = file + w.prevLine = line + w.prevColumn = column +} + +func (w *exportWriter) posV0(pos token.Pos) { + if w.p.fset == nil { + w.int64(0) + return + } + + p := w.p.fset.Position(pos) + file := p.Filename + line := int64(p.Line) + + // When file is the same as the last position (common case), + // we can save a few bytes by delta encoding just the line + // number. + // + // Note: Because data objects may be read out of order (or not + // at all), we can only apply delta encoding within a single + // object. This is handled implicitly by tracking prevFile and + // prevLine as fields of exportWriter. + + if file == w.prevFile { + delta := line - w.prevLine + w.int64(delta) + if delta == deltaNewFile { + w.int64(-1) + } + } else { + w.int64(deltaNewFile) + w.int64(line) // line >= 0 + w.string(file) + w.prevFile = file + } + w.prevLine = line +} + +func (w *exportWriter) pkg(pkg *types.Package) { + // Ensure any referenced packages are declared in the main index. + w.p.allPkgs[pkg] = true + + w.string(w.exportPath(pkg)) +} + +func (w *exportWriter) qualifiedType(obj *types.TypeName) { + name := w.p.exportName(obj) + + // Ensure any referenced declarations are written out too. + w.p.pushDecl(obj) + w.string(name) + w.pkg(obj.Pkg()) +} + +// TODO(rfindley): what does 'pkg' even mean here? It would be better to pass +// it in explicitly into signatures and structs that may use it for +// constructing fields. +func (w *exportWriter) typ(t types.Type, pkg *types.Package) { + w.data.uint64(w.p.typOff(t, pkg)) +} + +func (p *iexporter) newWriter() *exportWriter { + return &exportWriter{p: p} +} + +func (w *exportWriter) flush() uint64 { + off := uint64(w.p.data0.Len()) + io.Copy(&w.p.data0, &w.data) + return off +} + +func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 { + off, ok := p.typIndex[t] + if !ok { + w := p.newWriter() + w.doTyp(t, pkg) + off = predeclReserved + w.flush() + p.typIndex[t] = off + } + return off +} + +func (w *exportWriter) startType(k itag) { + w.data.uint64(uint64(k)) +} + +func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { + if trace { + w.p.trace("exporting type %s (%T)", t, t) + w.p.indent++ + defer func() { + w.p.indent-- + w.p.trace("=> %s", t) + }() + } + switch t := t.(type) { + case *types.Alias: + if targs := aliases.TypeArgs(t); targs.Len() > 0 { + w.startType(instanceType) + w.pos(t.Obj().Pos()) + w.typeList(targs, pkg) + w.typ(aliases.Origin(t), pkg) + return + } + w.startType(aliasType) + w.qualifiedType(t.Obj()) + + case *types.Named: + if targs := t.TypeArgs(); targs.Len() > 0 { + w.startType(instanceType) + // TODO(rfindley): investigate if this position is correct, and if it + // matters. + w.pos(t.Obj().Pos()) + w.typeList(targs, pkg) + w.typ(t.Origin(), pkg) + return + } + w.startType(definedType) + w.qualifiedType(t.Obj()) + + case *types.TypeParam: + w.startType(typeParamType) + w.qualifiedType(t.Obj()) + + case *types.Pointer: + w.startType(pointerType) + w.typ(t.Elem(), pkg) + + case *types.Slice: + w.startType(sliceType) + w.typ(t.Elem(), pkg) + + case *types.Array: + w.startType(arrayType) + w.uint64(uint64(t.Len())) + w.typ(t.Elem(), pkg) + + case *types.Chan: + w.startType(chanType) + // 1 RecvOnly; 2 SendOnly; 3 SendRecv + var dir uint64 + switch t.Dir() { + case types.RecvOnly: + dir = 1 + case types.SendOnly: + dir = 2 + case types.SendRecv: + dir = 3 + } + w.uint64(dir) + w.typ(t.Elem(), pkg) + + case *types.Map: + w.startType(mapType) + w.typ(t.Key(), pkg) + w.typ(t.Elem(), pkg) + + case *types.Signature: + w.startType(signatureType) + w.pkg(pkg) + w.signature(t) + + case *types.Struct: + w.startType(structType) + n := t.NumFields() + // Even for struct{} we must emit some qualifying package, because that's + // what the compiler does, and thus that's what the importer expects. + fieldPkg := pkg + if n > 0 { + fieldPkg = t.Field(0).Pkg() + } + if fieldPkg == nil { + // TODO(rfindley): improve this very hacky logic. + // + // The importer expects a package to be set for all struct types, even + // those with no fields. A better encoding might be to set NumFields + // before pkg. setPkg panics with a nil package, which may be possible + // to reach with invalid packages (and perhaps valid packages, too?), so + // (arbitrarily) set the localpkg if available. + // + // Alternatively, we may be able to simply guarantee that pkg != nil, by + // reconsidering the encoding of constant values. + if w.p.shallow { + fieldPkg = w.p.localpkg + } else { + panic(internalErrorf("no package to set for empty struct")) + } + } + w.pkg(fieldPkg) + w.uint64(uint64(n)) + + for i := range n { + f := t.Field(i) + if w.p.shallow { + w.objectPath(f) + } + w.pos(f.Pos()) + w.string(f.Name()) // unexported fields implicitly qualified by prior setPkg + w.typ(f.Type(), fieldPkg) + w.bool(f.Anonymous()) + w.string(t.Tag(i)) // note (or tag) + } + + case *types.Interface: + w.startType(interfaceType) + w.pkg(pkg) + + n := t.NumEmbeddeds() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + ft := t.EmbeddedType(i) + tPkg := pkg + if named, _ := types.Unalias(ft).(*types.Named); named != nil { + w.pos(named.Obj().Pos()) + } else { + w.pos(token.NoPos) + } + w.typ(ft, tPkg) + } + + // See comment for struct fields. In shallow mode we change the encoding + // for interface methods that are promoted from other packages. + + n = t.NumExplicitMethods() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + m := t.ExplicitMethod(i) + if w.p.shallow { + w.objectPath(m) + } + w.pos(m.Pos()) + w.string(m.Name()) + sig, _ := m.Type().(*types.Signature) + w.signature(sig) + } + + case *types.Union: + w.startType(unionType) + nt := t.Len() + w.uint64(uint64(nt)) + for i := range nt { + term := t.Term(i) + w.bool(term.Tilde()) + w.typ(term.Type(), pkg) + } + + default: + panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t))) + } +} + +// objectPath writes the package and objectPath to use to look up obj in a +// different package, when encoding in "shallow" mode. +// +// When doing a shallow import, the importer creates only the local package, +// and requests package symbols for dependencies from the client. +// However, certain types defined in the local package may hold objects defined +// (perhaps deeply) within another package. +// +// For example, consider the following: +// +// package a +// func F() chan * map[string] struct { X int } +// +// package b +// import "a" +// var B = a.F() +// +// In this example, the type of b.B holds fields defined in package a. +// In order to have the correct canonical objects for the field defined in the +// type of B, they are encoded as objectPaths and later looked up in the +// importer. The same problem applies to interface methods. +func (w *exportWriter) objectPath(obj types.Object) { + if obj.Pkg() == nil || obj.Pkg() == w.p.localpkg { + // obj.Pkg() may be nil for the builtin error.Error. + // In this case, or if obj is declared in the local package, no need to + // encode. + w.string("") + return + } + objectPath, err := w.p.objectpathEncoder().For(obj) + if err != nil { + // Fall back to the empty string, which will cause the importer to create a + // new object, which matches earlier behavior. Creating a new object is + // sufficient for many purposes (such as type checking), but causes certain + // references algorithms to fail (golang/go#60819). However, we didn't + // notice this problem during months of gopls@v0.12.0 testing. + // + // TODO(golang/go#61674): this workaround is insufficient, as in the case + // where the field forwarded from an instantiated type that may not appear + // in the export data of the original package: + // + // // package a + // type A[P any] struct{ F P } + // + // // package b + // type B a.A[int] + // + // We need to update references algorithms not to depend on this + // de-duplication, at which point we may want to simply remove the + // workaround here. + w.string("") + return + } + w.string(string(objectPath)) + w.pkg(obj.Pkg()) +} + +func (w *exportWriter) signature(sig *types.Signature) { + w.paramList(sig.Params()) + w.paramList(sig.Results()) + if sig.Params().Len() > 0 { + w.bool(sig.Variadic()) + } +} + +func (w *exportWriter) typeList(ts *types.TypeList, pkg *types.Package) { + w.uint64(uint64(ts.Len())) + for i := 0; i < ts.Len(); i++ { + w.typ(ts.At(i), pkg) + } +} + +func (w *exportWriter) tparamList(prefix string, list *types.TypeParamList, pkg *types.Package) { + ll := uint64(list.Len()) + w.uint64(ll) + for i := 0; i < list.Len(); i++ { + tparam := list.At(i) + // Set the type parameter exportName before exporting its type. + exportName := tparamExportName(prefix, tparam) + w.p.tparamNames[tparam.Obj()] = exportName + w.typ(list.At(i), pkg) + } +} + +const blankMarker = "$" + +// tparamExportName returns the 'exported' name of a type parameter, which +// differs from its actual object name: it is prefixed with a qualifier, and +// blank type parameter names are disambiguated by their index in the type +// parameter list. +func tparamExportName(prefix string, tparam *types.TypeParam) string { + assert(prefix != "") + name := tparam.Obj().Name() + if name == "_" { + name = blankMarker + strconv.Itoa(tparam.Index()) + } + return prefix + "." + name +} + +// tparamName returns the real name of a type parameter, after stripping its +// qualifying prefix and reverting blank-name encoding. See tparamExportName +// for details. +func tparamName(exportName string) string { + // Remove the "path" from the type param name that makes it unique. + ix := strings.LastIndex(exportName, ".") + if ix < 0 { + errorf("malformed type parameter export name %s: missing prefix", exportName) + } + name := exportName[ix+1:] + if strings.HasPrefix(name, blankMarker) { + return "_" + } + return name +} + +func (w *exportWriter) paramList(tup *types.Tuple) { + n := tup.Len() + w.uint64(uint64(n)) + for i := range n { + w.param(tup.At(i)) + } +} + +func (w *exportWriter) param(obj types.Object) { + w.pos(obj.Pos()) + w.localIdent(obj) + w.typ(obj.Type(), obj.Pkg()) +} + +func (w *exportWriter) value(typ types.Type, v constant.Value) { + w.typ(typ, nil) + if w.p.version >= iexportVersionGo1_18 { + w.int64(int64(v.Kind())) + } + + if v.Kind() == constant.Unknown { + // golang/go#60605: treat unknown constant values as if they have invalid type + // + // This loses some fidelity over the package type-checked from source, but that + // is acceptable. + // + // TODO(rfindley): we should switch on the recorded constant kind rather + // than the constant type + return + } + + switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType { + case types.IsBoolean: + w.bool(constant.BoolVal(v)) + case types.IsInteger: + var i big.Int + if i64, exact := constant.Int64Val(v); exact { + i.SetInt64(i64) + } else if ui64, exact := constant.Uint64Val(v); exact { + i.SetUint64(ui64) + } else { + i.SetString(v.ExactString(), 10) + } + w.mpint(&i, typ) + case types.IsFloat: + f := constantToFloat(v) + w.mpfloat(f, typ) + case types.IsComplex: + w.mpfloat(constantToFloat(constant.Real(v)), typ) + w.mpfloat(constantToFloat(constant.Imag(v)), typ) + case types.IsString: + w.string(constant.StringVal(v)) + default: + if b.Kind() == types.Invalid { + // package contains type errors + break + } + panic(internalErrorf("unexpected type %v (%v)", typ, typ.Underlying())) + } +} + +// constantToFloat converts a constant.Value with kind constant.Float to a +// big.Float. +func constantToFloat(x constant.Value) *big.Float { + x = constant.ToFloat(x) + // Use the same floating-point precision (512) as cmd/compile + // (see Mpprec in cmd/compile/internal/gc/mpfloat.go). + const mpprec = 512 + var f big.Float + f.SetPrec(mpprec) + if v, exact := constant.Float64Val(x); exact { + // float64 + f.SetFloat64(v) + } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int { + // TODO(gri): add big.Rat accessor to constant.Value. + n := valueToRat(num) + d := valueToRat(denom) + f.SetRat(n.Quo(n, d)) + } else { + // Value too large to represent as a fraction => inaccessible. + // TODO(gri): add big.Float accessor to constant.Value. + _, ok := f.SetString(x.ExactString()) + assert(ok) + } + return &f +} + +func valueToRat(x constant.Value) *big.Rat { + // Convert little-endian to big-endian. + // I can't believe this is necessary. + bytes := constant.Bytes(x) + for i := 0; i < len(bytes)/2; i++ { + bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i] + } + return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes)) +} + +// mpint exports a multi-precision integer. +// +// For unsigned types, small values are written out as a single +// byte. Larger values are written out as a length-prefixed big-endian +// byte string, where the length prefix is encoded as its complement. +// For example, bytes 0, 1, and 2 directly represent the integer +// values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-, +// 2-, and 3-byte big-endian string follow. +// +// Encoding for signed types use the same general approach as for +// unsigned types, except small values use zig-zag encoding and the +// bottom bit of length prefix byte for large values is reserved as a +// sign bit. +// +// The exact boundary between small and large encodings varies +// according to the maximum number of bytes needed to encode a value +// of type typ. As a special case, 8-bit types are always encoded as a +// single byte. +// +// TODO(mdempsky): Is this level of complexity really worthwhile? +func (w *exportWriter) mpint(x *big.Int, typ types.Type) { + basic, ok := typ.Underlying().(*types.Basic) + if !ok { + panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying())) + } + + signed, maxBytes := intSize(basic) + + negative := x.Sign() < 0 + if !signed && negative { + panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x)) + } + + b := x.Bytes() + if len(b) > 0 && b[0] == 0 { + panic(internalErrorf("leading zeros")) + } + if uint(len(b)) > maxBytes { + panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x)) + } + + maxSmall := 256 - maxBytes + if signed { + maxSmall = 256 - 2*maxBytes + } + if maxBytes == 1 { + maxSmall = 256 + } + + // Check if x can use small value encoding. + if len(b) <= 1 { + var ux uint + if len(b) == 1 { + ux = uint(b[0]) + } + if signed { + ux <<= 1 + if negative { + ux-- + } + } + if ux < maxSmall { + w.data.WriteByte(byte(ux)) + return + } + } + + n := 256 - uint(len(b)) + if signed { + n = 256 - 2*uint(len(b)) + if negative { + n |= 1 + } + } + if n < maxSmall || n >= 256 { + panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n)) + } + + w.data.WriteByte(byte(n)) + w.data.Write(b) +} + +// mpfloat exports a multi-precision floating point number. +// +// The number's value is decomposed into mantissa × 2**exponent, where +// mantissa is an integer. The value is written out as mantissa (as a +// multi-precision integer) and then the exponent, except exponent is +// omitted if mantissa is zero. +func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) { + if f.IsInf() { + panic("infinite constant") + } + + // Break into f = mant × 2**exp, with 0.5 <= mant < 1. + var mant big.Float + exp := int64(f.MantExp(&mant)) + + // Scale so that mant is an integer. + prec := mant.MinPrec() + mant.SetMantExp(&mant, int(prec)) + exp -= int64(prec) + + manti, acc := mant.Int(nil) + if acc != big.Exact { + panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc)) + } + w.mpint(manti, typ) + if manti.Sign() != 0 { + w.int64(exp) + } +} + +func (w *exportWriter) bool(b bool) bool { + var x uint64 + if b { + x = 1 + } + w.uint64(x) + return b +} + +func (w *exportWriter) int64(x int64) { w.data.int64(x) } +func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) } +func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) } + +func (w *exportWriter) localIdent(obj types.Object) { + // Anonymous parameters. + if obj == nil { + w.string("") + return + } + + name := obj.Name() + if name == "_" { + w.string("_") + return + } + + w.string(name) +} + +type intWriter struct { + bytes.Buffer +} + +func (w *intWriter) int64(x int64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutVarint(buf[:], x) + w.Write(buf[:n]) +} + +func (w *intWriter) uint64(x uint64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutUvarint(buf[:], x) + w.Write(buf[:n]) +} + +func assert(cond bool) { + if !cond { + panic("internal error: assertion failed") + } +} + +// The below is copied from go/src/cmd/compile/internal/gc/syntax.go. + +// objQueue is a FIFO queue of types.Object. The zero value of objQueue is +// a ready-to-use empty queue. +type objQueue struct { + ring []types.Object + head, tail int +} + +// empty returns true if q contains no Nodes. +func (q *objQueue) empty() bool { + return q.head == q.tail +} + +// pushTail appends n to the tail of the queue. +func (q *objQueue) pushTail(obj types.Object) { + if len(q.ring) == 0 { + q.ring = make([]types.Object, 16) + } else if q.head+len(q.ring) == q.tail { + // Grow the ring. + nring := make([]types.Object, len(q.ring)*2) + // Copy the old elements. + part := q.ring[q.head%len(q.ring):] + if q.tail-q.head <= len(part) { + part = part[:q.tail-q.head] + copy(nring, part) + } else { + pos := copy(nring, part) + copy(nring[pos:], q.ring[:q.tail%len(q.ring)]) + } + q.ring, q.head, q.tail = nring, 0, q.tail-q.head + } + + q.ring[q.tail%len(q.ring)] = obj + q.tail++ +} + +// popHead pops a node from the head of the queue. It panics if q is empty. +func (q *objQueue) popHead() types.Object { + if q.empty() { + panic("dequeue empty") + } + obj := q.ring[q.head%len(q.ring)] + q.head++ + return obj +} + +// internalError represents an error generated inside this package. +type internalError string + +func (e internalError) Error() string { return "gcimporter: " + string(e) } + +// TODO(adonovan): make this call panic, so that it's symmetric with errorf. +// Otherwise it's easy to forget to do anything with the error. +// +// TODO(adonovan): also, consider switching the names "errorf" and +// "internalErrorf" as the former is used for bugs, whose cause is +// internal inconsistency, whereas the latter is used for ordinary +// situations like bad input, whose cause is external. +func internalErrorf(format string, args ...any) error { + return internalError(fmt.Sprintf(format, args...)) +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go new file mode 100644 index 000000000..82e6c9d2d --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go @@ -0,0 +1,1120 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Indexed package import. +// See iexport.go for the export data format. + +package gcimporter + +import ( + "bytes" + "encoding/binary" + "fmt" + "go/constant" + "go/token" + "go/types" + "io" + "math/big" + "slices" + "sort" + "strings" + + "golang.org/x/tools/go/types/objectpath" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/typesinternal" +) + +type intReader struct { + *bytes.Reader + path string +} + +func (r *intReader) int64() int64 { + i, err := binary.ReadVarint(r.Reader) + if err != nil { + errorf("import %q: read varint error: %v", r.path, err) + } + return i +} + +func (r *intReader) uint64() uint64 { + i, err := binary.ReadUvarint(r.Reader) + if err != nil { + errorf("import %q: read varint error: %v", r.path, err) + } + return i +} + +// Keep this in sync with constants in iexport.go. +const ( + iexportVersionGo1_11 = 0 + iexportVersionPosCol = 1 + iexportVersionGo1_18 = 2 + iexportVersionGenerics = 2 + iexportVersion = iexportVersionGenerics + + iexportVersionCurrent = 2 +) + +type ident struct { + pkg *types.Package + name string +} + +const predeclReserved = 32 + +type itag uint64 + +const ( + // Types + definedType itag = iota + pointerType + sliceType + arrayType + chanType + mapType + signatureType + structType + interfaceType + typeParamType + instanceType + unionType + aliasType +) + +// Object tags +const ( + varTag = 'V' + funcTag = 'F' + genericFuncTag = 'G' + constTag = 'C' + aliasTag = 'A' + genericAliasTag = 'B' + typeParamTag = 'P' + typeTag = 'T' + genericTypeTag = 'U' +) + +// IImportData imports a package from the serialized package data +// and returns 0 and a reference to the package. +// If the export data version is not recognized or the format is otherwise +// compromised, an error is returned. +func IImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (int, *types.Package, error) { + pkgs, err := iimportCommon(fset, GetPackagesFromMap(imports), data, false, path, false, nil) + if err != nil { + return 0, nil, err + } + return 0, pkgs[0], nil +} + +// IImportBundle imports a set of packages from the serialized package bundle. +func IImportBundle(fset *token.FileSet, imports map[string]*types.Package, data []byte) ([]*types.Package, error) { + return iimportCommon(fset, GetPackagesFromMap(imports), data, true, "", false, nil) +} + +// A GetPackagesFunc function obtains the non-nil symbols for a set of +// packages, creating and recursively importing them as needed. An +// implementation should store each package symbol is in the Pkg +// field of the items array. +// +// Any error causes importing to fail. This can be used to quickly read +// the import manifest of an export data file without fully decoding it. +type GetPackagesFunc = func(items []GetPackagesItem) error + +// A GetPackagesItem is a request from the importer for the package +// symbol of the specified name and path. +type GetPackagesItem struct { + Name, Path string + Pkg *types.Package // to be filled in by GetPackagesFunc call + + // private importer state + pathOffset uint64 + nameIndex map[string]uint64 +} + +// GetPackagesFromMap returns a GetPackagesFunc that retrieves +// packages from the given map of package path to package. +// +// The returned function may mutate m: each requested package that is not +// found is created with types.NewPackage and inserted into m. +func GetPackagesFromMap(m map[string]*types.Package) GetPackagesFunc { + return func(items []GetPackagesItem) error { + for i, item := range items { + pkg, ok := m[item.Path] + if !ok { + pkg = types.NewPackage(item.Path, item.Name) + m[item.Path] = pkg + } + items[i].Pkg = pkg + } + return nil + } +} + +func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte, bundle bool, path string, shallow bool, reportf ReportFunc) (pkgs []*types.Package, err error) { + const currentVersion = iexportVersionCurrent + version := int64(-1) + if !debug { + defer func() { + if e := recover(); e != nil { + if bundle { + err = fmt.Errorf("%v", e) + } else if version > currentVersion { + err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) + } else { + err = fmt.Errorf("internal error while importing %q (%v); please report an issue", path, e) + } + } + }() + } + + r := &intReader{bytes.NewReader(data), path} + + if bundle { + if v := r.uint64(); v != bundleVersion { + errorf("unknown bundle format version %d", v) + } + } + + version = int64(r.uint64()) + switch version { + case iexportVersionGo1_18, iexportVersionPosCol, iexportVersionGo1_11: + default: + if version > iexportVersionGo1_18 { + errorf("unstable iexport format version %d, just rebuild compiler and std library", version) + } else { + errorf("unknown iexport format version %d", version) + } + } + + sLen := int64(r.uint64()) + var fLen int64 + var fileOffset []uint64 + if shallow { + // Shallow mode uses a different position encoding. + fLen = int64(r.uint64()) + fileOffset = make([]uint64, r.uint64()) + for i := range fileOffset { + fileOffset[i] = r.uint64() + } + } + dLen := int64(r.uint64()) + + whence, _ := r.Seek(0, io.SeekCurrent) + stringData := data[whence : whence+sLen] + fileData := data[whence+sLen : whence+sLen+fLen] + declData := data[whence+sLen+fLen : whence+sLen+fLen+dLen] + r.Seek(sLen+fLen+dLen, io.SeekCurrent) + + p := iimporter{ + version: int(version), + ipath: path, + aliases: aliases.Enabled(), + shallow: shallow, + reportf: reportf, + + stringData: stringData, + stringCache: make(map[uint64]string), + fileOffset: fileOffset, + fileData: fileData, + fileCache: make([]*token.File, len(fileOffset)), + pkgCache: make(map[uint64]*types.Package), + + declData: declData, + pkgIndex: make(map[*types.Package]map[string]uint64), + typCache: make(map[uint64]types.Type), + // Separate map for typeparams, keyed by their package and unique + // name. + tparamIndex: make(map[ident]types.Type), + + fake: fakeFileSet{ + fset: fset, + files: make(map[string]*fileInfo), + }, + } + defer p.fake.setLines() // set lines for files in fset + + for i, pt := range predeclared() { + p.typCache[uint64(i)] = pt + } + + // Gather the relevant packages from the manifest. + items := make([]GetPackagesItem, r.uint64()) + uniquePkgPaths := make(map[string]bool) + for i := range items { + pkgPathOff := r.uint64() + pkgPath := p.stringAt(pkgPathOff) + pkgName := p.stringAt(r.uint64()) + _ = r.uint64() // package height; unused by go/types + + if pkgPath == "" { + pkgPath = path + } + items[i].Name = pkgName + items[i].Path = pkgPath + items[i].pathOffset = pkgPathOff + + // Read index for package. + nameIndex := make(map[string]uint64) + nSyms := r.uint64() + // In shallow mode, only the current package (i=0) has an index. + assert(!(shallow && i > 0 && nSyms != 0)) + for ; nSyms > 0; nSyms-- { + name := p.stringAt(r.uint64()) + nameIndex[name] = r.uint64() + } + + items[i].nameIndex = nameIndex + + uniquePkgPaths[pkgPath] = true + } + // Debugging #63822; hypothesis: there are duplicate PkgPaths. + if len(uniquePkgPaths) != len(items) { + reportf("found duplicate PkgPaths while reading export data manifest: %v", items) + } + + // Request packages all at once from the client, + // enabling a parallel implementation. + if err := getPackages(items); err != nil { + return nil, err // don't wrap this error + } + + // Check the results and complete the index. + pkgList := make([]*types.Package, len(items)) + for i, item := range items { + pkg := item.Pkg + if pkg == nil { + errorf("internal error: getPackages returned nil package for %q", item.Path) + } else if pkg.Path() != item.Path { + errorf("internal error: getPackages returned wrong path %q, want %q", pkg.Path(), item.Path) + } else if pkg.Name() != item.Name { + errorf("internal error: getPackages returned wrong name %s for package %q, want %s", pkg.Name(), item.Path, item.Name) + } + p.pkgCache[item.pathOffset] = pkg + p.pkgIndex[pkg] = item.nameIndex + pkgList[i] = pkg + } + + if bundle { + pkgs = make([]*types.Package, r.uint64()) + for i := range pkgs { + pkg := p.pkgAt(r.uint64()) + imps := make([]*types.Package, r.uint64()) + for j := range imps { + imps[j] = p.pkgAt(r.uint64()) + } + pkg.SetImports(imps) + pkgs[i] = pkg + } + } else { + if len(pkgList) == 0 { + errorf("no packages found for %s", path) + panic("unreachable") + } + pkgs = pkgList[:1] + + // record all referenced packages as imports + list := slices.Clone(pkgList[1:]) + sort.Sort(byPath(list)) + pkgs[0].SetImports(list) + } + + for _, pkg := range pkgs { + if pkg.Complete() { + continue + } + + names := make([]string, 0, len(p.pkgIndex[pkg])) + for name := range p.pkgIndex[pkg] { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + p.doDecl(pkg, name) + } + + // package was imported completely and without errors + pkg.MarkComplete() + } + + // SetConstraint can't be called if the constraint type is not yet complete. + // When type params are created in the typeParamTag case of (*importReader).obj(), + // the associated constraint type may not be complete due to recursion. + // Therefore, we defer calling SetConstraint there, and call it here instead + // after all types are complete. + for _, d := range p.later { + d.t.SetConstraint(d.constraint) + } + + for _, typ := range p.interfaceList { + typ.Complete() + } + + // Workaround for golang/go#61561. See the doc for instanceList for details. + for _, typ := range p.instanceList { + if iface, _ := typ.Underlying().(*types.Interface); iface != nil { + iface.Complete() + } + } + + return pkgs, nil +} + +type setConstraintArgs struct { + t *types.TypeParam + constraint types.Type +} + +type iimporter struct { + version int + ipath string + + aliases bool + shallow bool + reportf ReportFunc // if non-nil, used to report bugs + + stringData []byte + stringCache map[uint64]string + fileOffset []uint64 // fileOffset[i] is offset in fileData for info about file encoded as i + fileData []byte + fileCache []*token.File // memoized decoding of file encoded as i + pkgCache map[uint64]*types.Package + + declData []byte + pkgIndex map[*types.Package]map[string]uint64 + typCache map[uint64]types.Type + tparamIndex map[ident]types.Type + + fake fakeFileSet + interfaceList []*types.Interface + + // Workaround for the go/types bug golang/go#61561: instances produced during + // instantiation may contain incomplete interfaces. Here we only complete the + // underlying type of the instance, which is the most common case but doesn't + // handle parameterized interface literals defined deeper in the type. + instanceList []types.Type // instances for later completion (see golang/go#61561) + + // Arguments for calls to SetConstraint that are deferred due to recursive types + later []setConstraintArgs + + indent int // for tracing support +} + +func (p *iimporter) trace(format string, args ...any) { + if !trace { + // Call sites should also be guarded, but having this check here allows + // easily enabling/disabling debug trace statements. + return + } + fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...) +} + +func (p *iimporter) doDecl(pkg *types.Package, name string) { + if debug { + p.trace("import decl %s", name) + p.indent++ + defer func() { + p.indent-- + p.trace("=> %s", name) + }() + } + // See if we've already imported this declaration. + if obj := pkg.Scope().Lookup(name); obj != nil { + return + } + + off, ok := p.pkgIndex[pkg][name] + if !ok { + // In deep mode, the index should be complete. In shallow + // mode, we should have already recursively loaded necessary + // dependencies so the above Lookup succeeds. + errorf("%v.%v not in index", pkg, name) + } + + r := &importReader{p: p, currPkg: pkg} + r.declReader.Reset(p.declData[off:]) + + r.obj(name) +} + +func (p *iimporter) stringAt(off uint64) string { + if s, ok := p.stringCache[off]; ok { + return s + } + + slen, n := binary.Uvarint(p.stringData[off:]) + if n <= 0 { + errorf("varint failed") + } + spos := off + uint64(n) + s := string(p.stringData[spos : spos+slen]) + p.stringCache[off] = s + return s +} + +func (p *iimporter) fileAt(index uint64) *token.File { + file := p.fileCache[index] + if file == nil { + off := p.fileOffset[index] + file = p.decodeFile(intReader{bytes.NewReader(p.fileData[off:]), p.ipath}) + p.fileCache[index] = file + } + return file +} + +func (p *iimporter) decodeFile(rd intReader) *token.File { + filename := p.stringAt(rd.uint64()) + size := int(rd.uint64()) + file := p.fake.fset.AddFile(filename, -1, size) + + // SetLines requires a nondecreasing sequence. + // Because it is common for clients to derive the interval + // [start, start+len(name)] from a start position, and we + // want to ensure that the end offset is on the same line, + // we fill in the gaps of the sparse encoding with values + // that strictly increase by the largest possible amount. + // This allows us to avoid having to record the actual end + // offset of each needed line. + + lines := make([]int, int(rd.uint64())) + var index, offset int + for i, n := 0, int(rd.uint64()); i < n; i++ { + index += int(rd.uint64()) + offset += int(rd.uint64()) + lines[index] = offset + + // Ensure monotonicity between points. + for j := index - 1; j > 0 && lines[j] == 0; j-- { + lines[j] = lines[j+1] - 1 + } + } + + // Ensure monotonicity after last point. + for j := len(lines) - 1; j > 0 && lines[j] == 0; j-- { + size-- + lines[j] = size + } + + if !file.SetLines(lines) { + errorf("SetLines failed: %d", lines) // can't happen + } + return file +} + +func (p *iimporter) pkgAt(off uint64) *types.Package { + if pkg, ok := p.pkgCache[off]; ok { + return pkg + } + path := p.stringAt(off) + errorf("missing package %q in %q", path, p.ipath) + return nil +} + +func (p *iimporter) typAt(off uint64, base *types.Named) types.Type { + if t, ok := p.typCache[off]; ok && canReuse(base, t) { + return t + } + + if off < predeclReserved { + errorf("predeclared type missing from cache: %v", off) + } + + r := &importReader{p: p} + r.declReader.Reset(p.declData[off-predeclReserved:]) + t := r.doType(base) + + if canReuse(base, t) { + p.typCache[off] = t + } + return t +} + +// canReuse reports whether the type rhs on the RHS of the declaration for def +// may be re-used. +// +// Specifically, if def is non-nil and rhs is an interface type with methods, it +// may not be re-used because we have a convention of setting the receiver type +// for interface methods to def. +func canReuse(def *types.Named, rhs types.Type) bool { + if def == nil { + return true + } + iface, _ := types.Unalias(rhs).(*types.Interface) + if iface == nil { + return true + } + // Don't use iface.Empty() here as iface may not be complete. + return iface.NumEmbeddeds() == 0 && iface.NumExplicitMethods() == 0 +} + +type importReader struct { + p *iimporter + declReader bytes.Reader + currPkg *types.Package + prevFile string + prevLine int64 + prevColumn int64 +} + +// markBlack is redefined in iimport_go123.go, to work around golang/go#69912. +// +// If TypeNames are not marked black (in the sense of go/types cycle +// detection), they may be mutated when dot-imported. Fix this by punching a +// hole through the type, when compiling with Go 1.23. (The bug has been fixed +// for 1.24, but the fix was not worth back-porting). +var markBlack = func(name *types.TypeName) {} + +func (r *importReader) obj(name string) { + tag := r.byte() + pos := r.pos() + + switch tag { + case aliasTag, genericAliasTag: + var tparams []*types.TypeParam + if tag == genericAliasTag { + tparams = r.tparamList() + } + typ := r.typ() + obj := aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ, tparams) + markBlack(obj) // workaround for golang/go#69912 + r.declare(obj) + + case constTag: + typ, val := r.value() + + r.declare(types.NewConst(pos, r.currPkg, name, typ, val)) + + case funcTag, genericFuncTag: + var tparams []*types.TypeParam + if tag == genericFuncTag { + tparams = r.tparamList() + } + sig := r.signature(nil, nil, tparams) + r.declare(types.NewFunc(pos, r.currPkg, name, sig)) + + case typeTag, genericTypeTag: + // Types can be recursive. We need to setup a stub + // declaration before recursing. + obj := types.NewTypeName(pos, r.currPkg, name, nil) + named := types.NewNamed(obj, nil, nil) + + markBlack(obj) // workaround for golang/go#69912 + + // Declare obj before calling r.tparamList, so the new type name is recognized + // if used in the constraint of one of its own typeparams (see #48280). + r.declare(obj) + if tag == genericTypeTag { + tparams := r.tparamList() + named.SetTypeParams(tparams) + } + + underlying := r.p.typAt(r.uint64(), named).Underlying() + named.SetUnderlying(underlying) + + if !isInterface(underlying) { + for n := r.uint64(); n > 0; n-- { + mpos := r.pos() + mname := r.ident() + recv := r.param() + + // If the receiver has any targs, set those as the + // rparams of the method (since those are the + // typeparams being used in the method sig/body). + _, recvNamed := typesinternal.ReceiverNamed(recv) + targs := recvNamed.TypeArgs() + var rparams []*types.TypeParam + if targs.Len() > 0 { + rparams = make([]*types.TypeParam, targs.Len()) + for i := range rparams { + rparams[i] = types.Unalias(targs.At(i)).(*types.TypeParam) + } + } + msig := r.signature(recv, rparams, nil) + + named.AddMethod(types.NewFunc(mpos, r.currPkg, mname, msig)) + } + } + + case typeParamTag: + // We need to "declare" a typeparam in order to have a name that + // can be referenced recursively (if needed) in the type param's + // bound. + if r.p.version < iexportVersionGenerics { + errorf("unexpected type param type") + } + name0 := tparamName(name) + tn := types.NewTypeName(pos, r.currPkg, name0, nil) + t := types.NewTypeParam(tn, nil) + + // To handle recursive references to the typeparam within its + // bound, save the partial type in tparamIndex before reading the bounds. + id := ident{r.currPkg, name} + r.p.tparamIndex[id] = t + var implicit bool + if r.p.version >= iexportVersionGo1_18 { + implicit = r.bool() + } + constraint := r.typ() + if implicit { + iface, _ := types.Unalias(constraint).(*types.Interface) + if iface == nil { + errorf("non-interface constraint marked implicit") + } + iface.MarkImplicit() + } + // The constraint type may not be complete, if we + // are in the middle of a type recursion involving type + // constraints. So, we defer SetConstraint until we have + // completely set up all types in ImportData. + r.p.later = append(r.p.later, setConstraintArgs{t: t, constraint: constraint}) + + case varTag: + typ := r.typ() + + v := types.NewVar(pos, r.currPkg, name, typ) + typesinternal.SetVarKind(v, typesinternal.PackageVar) + r.declare(v) + + default: + errorf("unexpected tag: %v", tag) + } +} + +func (r *importReader) declare(obj types.Object) { + obj.Pkg().Scope().Insert(obj) +} + +func (r *importReader) value() (typ types.Type, val constant.Value) { + typ = r.typ() + if r.p.version >= iexportVersionGo1_18 { + // TODO: add support for using the kind. + _ = constant.Kind(r.int64()) + } + + switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType { + case types.IsBoolean: + val = constant.MakeBool(r.bool()) + + case types.IsString: + val = constant.MakeString(r.string()) + + case types.IsInteger: + var x big.Int + r.mpint(&x, b) + val = constant.Make(&x) + + case types.IsFloat: + val = r.mpfloat(b) + + case types.IsComplex: + re := r.mpfloat(b) + im := r.mpfloat(b) + val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) + + default: + if b.Kind() == types.Invalid { + val = constant.MakeUnknown() + return + } + errorf("unexpected type %v", typ) // panics + panic("unreachable") + } + + return +} + +func intSize(b *types.Basic) (signed bool, maxBytes uint) { + if (b.Info() & types.IsUntyped) != 0 { + return true, 64 + } + + switch b.Kind() { + case types.Float32, types.Complex64: + return true, 3 + case types.Float64, types.Complex128: + return true, 7 + } + + signed = (b.Info() & types.IsUnsigned) == 0 + switch b.Kind() { + case types.Int8, types.Uint8: + maxBytes = 1 + case types.Int16, types.Uint16: + maxBytes = 2 + case types.Int32, types.Uint32: + maxBytes = 4 + default: + maxBytes = 8 + } + + return +} + +func (r *importReader) mpint(x *big.Int, typ *types.Basic) { + signed, maxBytes := intSize(typ) + + maxSmall := 256 - maxBytes + if signed { + maxSmall = 256 - 2*maxBytes + } + if maxBytes == 1 { + maxSmall = 256 + } + + n, _ := r.declReader.ReadByte() + if uint(n) < maxSmall { + v := int64(n) + if signed { + v >>= 1 + if n&1 != 0 { + v = ^v + } + } + x.SetInt64(v) + return + } + + v := -n + if signed { + v = -(n &^ 1) >> 1 + } + if v < 1 || uint(v) > maxBytes { + errorf("weird decoding: %v, %v => %v", n, signed, v) + } + b := make([]byte, v) + io.ReadFull(&r.declReader, b) + x.SetBytes(b) + if signed && n&1 != 0 { + x.Neg(x) + } +} + +func (r *importReader) mpfloat(typ *types.Basic) constant.Value { + var mant big.Int + r.mpint(&mant, typ) + var f big.Float + f.SetInt(&mant) + if f.Sign() != 0 { + f.SetMantExp(&f, int(r.int64())) + } + return constant.Make(&f) +} + +func (r *importReader) ident() string { + return r.string() +} + +func (r *importReader) qualifiedIdent() (*types.Package, string) { + name := r.string() + pkg := r.pkg() + return pkg, name +} + +func (r *importReader) pos() token.Pos { + if r.p.shallow { + // precise offsets are encoded only in shallow mode + return r.posv2() + } + if r.p.version >= iexportVersionPosCol { + r.posv1() + } else { + r.posv0() + } + + if r.prevFile == "" && r.prevLine == 0 && r.prevColumn == 0 { + return token.NoPos + } + return r.p.fake.pos(r.prevFile, int(r.prevLine), int(r.prevColumn)) +} + +func (r *importReader) posv0() { + delta := r.int64() + if delta != deltaNewFile { + r.prevLine += delta + } else if l := r.int64(); l == -1 { + r.prevLine += deltaNewFile + } else { + r.prevFile = r.string() + r.prevLine = l + } +} + +func (r *importReader) posv1() { + delta := r.int64() + r.prevColumn += delta >> 1 + if delta&1 != 0 { + delta = r.int64() + r.prevLine += delta >> 1 + if delta&1 != 0 { + r.prevFile = r.string() + } + } +} + +func (r *importReader) posv2() token.Pos { + file := r.uint64() + if file == 0 { + return token.NoPos + } + tf := r.p.fileAt(file - 1) + return tf.Pos(int(r.uint64())) +} + +func (r *importReader) typ() types.Type { + return r.p.typAt(r.uint64(), nil) +} + +func isInterface(t types.Type) bool { + _, ok := types.Unalias(t).(*types.Interface) + return ok +} + +func (r *importReader) pkg() *types.Package { return r.p.pkgAt(r.uint64()) } +func (r *importReader) string() string { return r.p.stringAt(r.uint64()) } + +func (r *importReader) doType(base *types.Named) (res types.Type) { + k := r.kind() + if debug { + r.p.trace("importing type %d (base: %v)", k, base) + r.p.indent++ + defer func() { + r.p.indent-- + r.p.trace("=> %s", res) + }() + } + switch k { + default: + errorf("unexpected kind tag in %q: %v", r.p.ipath, k) + return nil + + case aliasType, definedType: + pkg, name := r.qualifiedIdent() + r.p.doDecl(pkg, name) + return pkg.Scope().Lookup(name).(*types.TypeName).Type() + case pointerType: + return types.NewPointer(r.typ()) + case sliceType: + return types.NewSlice(r.typ()) + case arrayType: + n := r.uint64() + return types.NewArray(r.typ(), int64(n)) + case chanType: + dir := chanDir(int(r.uint64())) + return types.NewChan(dir, r.typ()) + case mapType: + return types.NewMap(r.typ(), r.typ()) + case signatureType: + r.currPkg = r.pkg() + return r.signature(nil, nil, nil) + + case structType: + r.currPkg = r.pkg() + + fields := make([]*types.Var, r.uint64()) + tags := make([]string, len(fields)) + for i := range fields { + var field *types.Var + if r.p.shallow { + field, _ = r.objectPathObject().(*types.Var) + } + + fpos := r.pos() + fname := r.ident() + ftyp := r.typ() + emb := r.bool() + tag := r.string() + + // Either this is not a shallow import, the field is local, or the + // encoded objectPath failed to produce an object (a bug). + // + // Even in this last, buggy case, fall back on creating a new field. As + // discussed in iexport.go, this is not correct, but mostly works and is + // preferable to failing (for now at least). + if field == nil { + field = types.NewField(fpos, r.currPkg, fname, ftyp, emb) + } + + fields[i] = field + tags[i] = tag + } + return types.NewStruct(fields, tags) + + case interfaceType: + r.currPkg = r.pkg() + + embeddeds := make([]types.Type, r.uint64()) + for i := range embeddeds { + _ = r.pos() + embeddeds[i] = r.typ() + } + + methods := make([]*types.Func, r.uint64()) + for i := range methods { + var method *types.Func + if r.p.shallow { + method, _ = r.objectPathObject().(*types.Func) + } + + mpos := r.pos() + mname := r.ident() + + // TODO(mdempsky): Matches bimport.go, but I + // don't agree with this. + var recv *types.Var + if base != nil { + recv = types.NewVar(token.NoPos, r.currPkg, "", base) + } + msig := r.signature(recv, nil, nil) + + if method == nil { + method = types.NewFunc(mpos, r.currPkg, mname, msig) + } + methods[i] = method + } + + typ := types.NewInterfaceType(methods, embeddeds) + r.p.interfaceList = append(r.p.interfaceList, typ) + return typ + + case typeParamType: + if r.p.version < iexportVersionGenerics { + errorf("unexpected type param type") + } + pkg, name := r.qualifiedIdent() + id := ident{pkg, name} + if t, ok := r.p.tparamIndex[id]; ok { + // We're already in the process of importing this typeparam. + return t + } + // Otherwise, import the definition of the typeparam now. + r.p.doDecl(pkg, name) + return r.p.tparamIndex[id] + + case instanceType: + if r.p.version < iexportVersionGenerics { + errorf("unexpected instantiation type") + } + // pos does not matter for instances: they are positioned on the original + // type. + _ = r.pos() + len := r.uint64() + targs := make([]types.Type, len) + for i := range targs { + targs[i] = r.typ() + } + baseType := r.typ() + // The imported instantiated type doesn't include any methods, so + // we must always use the methods of the base (orig) type. + // TODO provide a non-nil *Environment + t, _ := types.Instantiate(nil, baseType, targs, false) + + // Workaround for golang/go#61561. See the doc for instanceList for details. + r.p.instanceList = append(r.p.instanceList, t) + return t + + case unionType: + if r.p.version < iexportVersionGenerics { + errorf("unexpected instantiation type") + } + terms := make([]*types.Term, r.uint64()) + for i := range terms { + terms[i] = types.NewTerm(r.bool(), r.typ()) + } + return types.NewUnion(terms) + } +} + +func (r *importReader) kind() itag { + return itag(r.uint64()) +} + +// objectPathObject is the inverse of exportWriter.objectPath. +// +// In shallow mode, certain fields and methods may need to be looked up in an +// imported package. See the doc for exportWriter.objectPath for a full +// explanation. +func (r *importReader) objectPathObject() types.Object { + objPath := objectpath.Path(r.string()) + if objPath == "" { + return nil + } + pkg := r.pkg() + obj, err := objectpath.Object(pkg, objPath) + if err != nil { + if r.p.reportf != nil { + r.p.reportf("failed to find object for objectPath %q: %v", objPath, err) + } + } + return obj +} + +func (r *importReader) signature(recv *types.Var, rparams []*types.TypeParam, tparams []*types.TypeParam) *types.Signature { + params := r.paramList() + results := r.paramList() + variadic := params.Len() > 0 && r.bool() + return types.NewSignatureType(recv, rparams, tparams, params, results, variadic) +} + +func (r *importReader) tparamList() []*types.TypeParam { + n := r.uint64() + if n == 0 { + return nil + } + xs := make([]*types.TypeParam, n) + for i := range xs { + // Note: the standard library importer is tolerant of nil types here, + // though would panic in SetTypeParams. + xs[i] = types.Unalias(r.typ()).(*types.TypeParam) + } + return xs +} + +func (r *importReader) paramList() *types.Tuple { + xs := make([]*types.Var, r.uint64()) + for i := range xs { + xs[i] = r.param() + } + return types.NewTuple(xs...) +} + +func (r *importReader) param() *types.Var { + pos := r.pos() + name := r.ident() + typ := r.typ() + return types.NewParam(pos, r.currPkg, name, typ) +} + +func (r *importReader) bool() bool { + return r.uint64() != 0 +} + +func (r *importReader) int64() int64 { + n, err := binary.ReadVarint(&r.declReader) + if err != nil { + errorf("readVarint: %v", err) + } + return n +} + +func (r *importReader) uint64() uint64 { + n, err := binary.ReadUvarint(&r.declReader) + if err != nil { + errorf("readUvarint: %v", err) + } + return n +} + +func (r *importReader) byte() byte { + x, err := r.declReader.ReadByte() + if err != nil { + errorf("declReader.ReadByte: %v", err) + } + return x +} + +type byPath []*types.Package + +func (a byPath) Len() int { return len(a) } +func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go new file mode 100644 index 000000000..7586bfaca --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go @@ -0,0 +1,53 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.22 && !go1.24 + +package gcimporter + +import ( + "go/token" + "go/types" + "unsafe" +) + +// TODO(rfindley): delete this workaround once go1.24 is assured. + +func init() { + // Update markBlack so that it correctly sets the color + // of imported TypeNames. + // + // See the doc comment for markBlack for details. + + type color uint32 + const ( + white color = iota + black + grey + ) + type object struct { + _ *types.Scope + _ token.Pos + _ *types.Package + _ string + _ types.Type + _ uint32 + color_ color + _ token.Pos + } + type typeName struct { + object + } + + // If the size of types.TypeName changes, this will fail to compile. + const delta = int64(unsafe.Sizeof(typeName{})) - int64(unsafe.Sizeof(types.TypeName{})) + var _ [-delta * delta]int + + markBlack = func(obj *types.TypeName) { + type uP = unsafe.Pointer + var ptr *typeName + *(*uP)(uP(&ptr)) = uP(obj) + ptr.color_ = black + } +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go b/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go new file mode 100644 index 000000000..907c8557a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go @@ -0,0 +1,91 @@ +// Copyright 2024 The Go 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 gcimporter + +import ( + "go/types" + "sync" +) + +// predecl is a cache for the predeclared types in types.Universe. +// +// Cache a distinct result based on the runtime value of any. +// The pointer value of the any type varies based on GODEBUG settings. +var predeclMu sync.Mutex +var predecl map[types.Type][]types.Type + +func predeclared() []types.Type { + anyt := types.Universe.Lookup("any").Type() + + predeclMu.Lock() + defer predeclMu.Unlock() + + if pre, ok := predecl[anyt]; ok { + return pre + } + + if predecl == nil { + predecl = make(map[types.Type][]types.Type) + } + + decls := []types.Type{ // basic types + types.Typ[types.Bool], + types.Typ[types.Int], + types.Typ[types.Int8], + types.Typ[types.Int16], + types.Typ[types.Int32], + types.Typ[types.Int64], + types.Typ[types.Uint], + types.Typ[types.Uint8], + types.Typ[types.Uint16], + types.Typ[types.Uint32], + types.Typ[types.Uint64], + types.Typ[types.Uintptr], + types.Typ[types.Float32], + types.Typ[types.Float64], + types.Typ[types.Complex64], + types.Typ[types.Complex128], + types.Typ[types.String], + + // basic type aliases + types.Universe.Lookup("byte").Type(), + types.Universe.Lookup("rune").Type(), + + // error + types.Universe.Lookup("error").Type(), + + // untyped types + types.Typ[types.UntypedBool], + types.Typ[types.UntypedInt], + types.Typ[types.UntypedRune], + types.Typ[types.UntypedFloat], + types.Typ[types.UntypedComplex], + types.Typ[types.UntypedString], + types.Typ[types.UntypedNil], + + // package unsafe + types.Typ[types.UnsafePointer], + + // invalid type + types.Typ[types.Invalid], // only appears in packages with errors + + // used internally by gc; never used by this package or in .a files + anyType{}, + + // comparable + types.Universe.Lookup("comparable").Type(), + + // any + anyt, + } + + predecl[anyt] = decls + return decls +} + +type anyType struct{} + +func (t anyType) Underlying() types.Type { return t } +func (t anyType) String() string { return "any" } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/support.go b/vendor/golang.org/x/tools/internal/gcimporter/support.go new file mode 100644 index 000000000..4af810dc4 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/support.go @@ -0,0 +1,30 @@ +// Copyright 2024 The Go 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 gcimporter + +import ( + "bufio" + "io" + "strconv" + "strings" +) + +// Copy of $GOROOT/src/cmd/internal/archive.ReadHeader. +func readArchiveHeader(b *bufio.Reader, name string) int { + // architecture-independent object file output + const HeaderSize = 60 + + var buf [HeaderSize]byte + if _, err := io.ReadFull(b, buf[:]); err != nil { + return -1 + } + aname := strings.Trim(string(buf[0:16]), " ") + if !strings.HasPrefix(aname, name) { + return -1 + } + asize := strings.Trim(string(buf[48:58]), " ") + i, _ := strconv.Atoi(asize) + return i +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go new file mode 100644 index 000000000..37b4a39e9 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go @@ -0,0 +1,761 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Derived from go/internal/gcimporter/ureader.go + +package gcimporter + +import ( + "fmt" + "go/token" + "go/types" + "sort" + + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/pkgbits" + "golang.org/x/tools/internal/typesinternal" +) + +// A pkgReader holds the shared state for reading a unified IR package +// description. +type pkgReader struct { + pkgbits.PkgDecoder + + fake fakeFileSet + + ctxt *types.Context + imports map[string]*types.Package // previously imported packages, indexed by path + aliases bool // create types.Alias nodes + + // lazily initialized arrays corresponding to the unified IR + // PosBase, Pkg, and Type sections, respectively. + posBases []string // position bases (i.e., file names) + pkgs []*types.Package + typs []types.Type + + // laterFns holds functions that need to be invoked at the end of + // import reading. + laterFns []func() + // laterFors is used in case of 'type A B' to ensure that B is processed before A. + laterFors map[types.Type]int + + // ifaces holds a list of constructed Interfaces, which need to have + // Complete called after importing is done. + ifaces []*types.Interface +} + +// later adds a function to be invoked at the end of import reading. +func (pr *pkgReader) later(fn func()) { + pr.laterFns = append(pr.laterFns, fn) +} + +// See cmd/compile/internal/noder.derivedInfo. +type derivedInfo struct { + idx pkgbits.Index +} + +// See cmd/compile/internal/noder.typeInfo. +type typeInfo struct { + idx pkgbits.Index + derived bool +} + +func UImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { + if !debug { + defer func() { + if x := recover(); x != nil { + err = fmt.Errorf("internal error in importing %q (%v); please report an issue", path, x) + } + }() + } + + s := string(data) + input := pkgbits.NewPkgDecoder(path, s) + pkg = readUnifiedPackage(fset, nil, imports, input) + return +} + +// laterFor adds a function to be invoked at the end of import reading, and records the type that function is finishing. +func (pr *pkgReader) laterFor(t types.Type, fn func()) { + if pr.laterFors == nil { + pr.laterFors = make(map[types.Type]int) + } + pr.laterFors[t] = len(pr.laterFns) + pr.laterFns = append(pr.laterFns, fn) +} + +// readUnifiedPackage reads a package description from the given +// unified IR export data decoder. +func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[string]*types.Package, input pkgbits.PkgDecoder) *types.Package { + pr := pkgReader{ + PkgDecoder: input, + + fake: fakeFileSet{ + fset: fset, + files: make(map[string]*fileInfo), + }, + + ctxt: ctxt, + imports: imports, + aliases: aliases.Enabled(), + + posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)), + pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)), + typs: make([]types.Type, input.NumElems(pkgbits.RelocType)), + } + defer pr.fake.setLines() + + r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic) + pkg := r.pkg() + if r.Version().Has(pkgbits.HasInit) { + r.Bool() + } + + for i, n := 0, r.Len(); i < n; i++ { + // As if r.obj(), but avoiding the Scope.Lookup call, + // to avoid eager loading of imports. + r.Sync(pkgbits.SyncObject) + if r.Version().Has(pkgbits.DerivedFuncInstance) { + assert(!r.Bool()) + } + r.p.objIdx(r.Reloc(pkgbits.RelocObj)) + assert(r.Len() == 0) + } + + r.Sync(pkgbits.SyncEOF) + + for _, fn := range pr.laterFns { + fn() + } + + for _, iface := range pr.ifaces { + iface.Complete() + } + + // Imports() of pkg are all of the transitive packages that were loaded. + var imps []*types.Package + for _, imp := range pr.pkgs { + if imp != nil && imp != pkg { + imps = append(imps, imp) + } + } + sort.Sort(byPath(imps)) + pkg.SetImports(imps) + + pkg.MarkComplete() + return pkg +} + +// A reader holds the state for reading a single unified IR element +// within a package. +type reader struct { + pkgbits.Decoder + + p *pkgReader + + dict *readerDict +} + +// A readerDict holds the state for type parameters that parameterize +// the current unified IR element. +type readerDict struct { + // bounds is a slice of typeInfos corresponding to the underlying + // bounds of the element's type parameters. + bounds []typeInfo + + // tparams is a slice of the constructed TypeParams for the element. + tparams []*types.TypeParam + + // derived is a slice of types derived from tparams, which may be + // instantiated while reading the current element. + derived []derivedInfo + derivedTypes []types.Type // lazily instantiated from derived +} + +func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader { + return &reader{ + Decoder: pr.NewDecoder(k, idx, marker), + p: pr, + } +} + +func (pr *pkgReader) tempReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader { + return &reader{ + Decoder: pr.TempDecoder(k, idx, marker), + p: pr, + } +} + +func (pr *pkgReader) retireReader(r *reader) { + pr.RetireDecoder(&r.Decoder) +} + +// @@@ Positions + +func (r *reader) pos() token.Pos { + r.Sync(pkgbits.SyncPos) + if !r.Bool() { + return token.NoPos + } + + // TODO(mdempsky): Delta encoding. + posBase := r.posBase() + line := r.Uint() + col := r.Uint() + return r.p.fake.pos(posBase, int(line), int(col)) +} + +func (r *reader) posBase() string { + return r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase)) +} + +func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) string { + if b := pr.posBases[idx]; b != "" { + return b + } + + var filename string + { + r := pr.tempReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase) + + // Within types2, position bases have a lot more details (e.g., + // keeping track of where //line directives appeared exactly). + // + // For go/types, we just track the file name. + + filename = r.String() + + if r.Bool() { // file base + // Was: "b = token.NewTrimmedFileBase(filename, true)" + } else { // line base + pos := r.pos() + line := r.Uint() + col := r.Uint() + + // Was: "b = token.NewLineBase(pos, filename, true, line, col)" + _, _, _ = pos, line, col + } + pr.retireReader(r) + } + b := filename + pr.posBases[idx] = b + return b +} + +// @@@ Packages + +func (r *reader) pkg() *types.Package { + r.Sync(pkgbits.SyncPkg) + return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg)) +} + +func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package { + // TODO(mdempsky): Consider using some non-nil pointer to indicate + // the universe scope, so we don't need to keep re-reading it. + if pkg := pr.pkgs[idx]; pkg != nil { + return pkg + } + + pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg() + pr.pkgs[idx] = pkg + return pkg +} + +func (r *reader) doPkg() *types.Package { + path := r.String() + switch path { + // cmd/compile emits path="main" for main packages because + // that's the linker symbol prefix it used; but we need + // the package's path as it would be reported by go list, + // hence "main" below. + // See test at go/packages.TestMainPackagePathInModeTypes. + case "", "main": + path = r.p.PkgPath() + case "builtin": + return nil // universe + case "unsafe": + return types.Unsafe + } + + if pkg := r.p.imports[path]; pkg != nil { + return pkg + } + + name := r.String() + + pkg := types.NewPackage(path, name) + r.p.imports[path] = pkg + + return pkg +} + +// @@@ Types + +func (r *reader) typ() types.Type { + return r.p.typIdx(r.typInfo(), r.dict) +} + +func (r *reader) typInfo() typeInfo { + r.Sync(pkgbits.SyncType) + if r.Bool() { + return typeInfo{idx: pkgbits.Index(r.Len()), derived: true} + } + return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false} +} + +func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict) types.Type { + idx := info.idx + var where *types.Type + if info.derived { + where = &dict.derivedTypes[idx] + idx = dict.derived[idx].idx + } else { + where = &pr.typs[idx] + } + + if typ := *where; typ != nil { + return typ + } + + var typ types.Type + { + r := pr.tempReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx) + r.dict = dict + + typ = r.doTyp() + assert(typ != nil) + pr.retireReader(r) + } + // See comment in pkgReader.typIdx explaining how this happens. + if prev := *where; prev != nil { + return prev + } + + *where = typ + return typ +} + +func (r *reader) doTyp() (res types.Type) { + switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag { + default: + errorf("unhandled type tag: %v", tag) + panic("unreachable") + + case pkgbits.TypeBasic: + return types.Typ[r.Len()] + + case pkgbits.TypeNamed: + obj, targs := r.obj() + name := obj.(*types.TypeName) + if len(targs) != 0 { + t, _ := types.Instantiate(r.p.ctxt, name.Type(), targs, false) + return t + } + return name.Type() + + case pkgbits.TypeTypeParam: + return r.dict.tparams[r.Len()] + + case pkgbits.TypeArray: + len := int64(r.Uint64()) + return types.NewArray(r.typ(), len) + case pkgbits.TypeChan: + dir := types.ChanDir(r.Len()) + return types.NewChan(dir, r.typ()) + case pkgbits.TypeMap: + return types.NewMap(r.typ(), r.typ()) + case pkgbits.TypePointer: + return types.NewPointer(r.typ()) + case pkgbits.TypeSignature: + return r.signature(nil, nil, nil) + case pkgbits.TypeSlice: + return types.NewSlice(r.typ()) + case pkgbits.TypeStruct: + return r.structType() + case pkgbits.TypeInterface: + return r.interfaceType() + case pkgbits.TypeUnion: + return r.unionType() + } +} + +func (r *reader) structType() *types.Struct { + fields := make([]*types.Var, r.Len()) + var tags []string + for i := range fields { + pos := r.pos() + pkg, name := r.selector() + ftyp := r.typ() + tag := r.String() + embedded := r.Bool() + + fields[i] = types.NewField(pos, pkg, name, ftyp, embedded) + if tag != "" { + for len(tags) < i { + tags = append(tags, "") + } + tags = append(tags, tag) + } + } + return types.NewStruct(fields, tags) +} + +func (r *reader) unionType() *types.Union { + terms := make([]*types.Term, r.Len()) + for i := range terms { + terms[i] = types.NewTerm(r.Bool(), r.typ()) + } + return types.NewUnion(terms) +} + +func (r *reader) interfaceType() *types.Interface { + methods := make([]*types.Func, r.Len()) + embeddeds := make([]types.Type, r.Len()) + implicit := len(methods) == 0 && len(embeddeds) == 1 && r.Bool() + + for i := range methods { + pos := r.pos() + pkg, name := r.selector() + mtyp := r.signature(nil, nil, nil) + methods[i] = types.NewFunc(pos, pkg, name, mtyp) + } + + for i := range embeddeds { + embeddeds[i] = r.typ() + } + + iface := types.NewInterfaceType(methods, embeddeds) + if implicit { + iface.MarkImplicit() + } + + // We need to call iface.Complete(), but if there are any embedded + // defined types, then we may not have set their underlying + // interface type yet. So we need to defer calling Complete until + // after we've called SetUnderlying everywhere. + // + // TODO(mdempsky): After CL 424876 lands, it should be safe to call + // iface.Complete() immediately. + r.p.ifaces = append(r.p.ifaces, iface) + + return iface +} + +func (r *reader) signature(recv *types.Var, rtparams, tparams []*types.TypeParam) *types.Signature { + r.Sync(pkgbits.SyncSignature) + + params := r.params() + results := r.params() + variadic := r.Bool() + + return types.NewSignatureType(recv, rtparams, tparams, params, results, variadic) +} + +func (r *reader) params() *types.Tuple { + r.Sync(pkgbits.SyncParams) + + params := make([]*types.Var, r.Len()) + for i := range params { + params[i] = r.param() + } + + return types.NewTuple(params...) +} + +func (r *reader) param() *types.Var { + r.Sync(pkgbits.SyncParam) + + pos := r.pos() + pkg, name := r.localIdent() + typ := r.typ() + + return types.NewParam(pos, pkg, name, typ) +} + +// @@@ Objects + +func (r *reader) obj() (types.Object, []types.Type) { + r.Sync(pkgbits.SyncObject) + + if r.Version().Has(pkgbits.DerivedFuncInstance) { + assert(!r.Bool()) + } + + pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj)) + obj := pkgScope(pkg).Lookup(name) + + targs := make([]types.Type, r.Len()) + for i := range targs { + targs[i] = r.typ() + } + + return obj, targs +} + +func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { + + var objPkg *types.Package + var objName string + var tag pkgbits.CodeObj + { + rname := pr.tempReader(pkgbits.RelocName, idx, pkgbits.SyncObject1) + + objPkg, objName = rname.qualifiedIdent() + assert(objName != "") + + tag = pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj)) + pr.retireReader(rname) + } + + if tag == pkgbits.ObjStub { + assert(objPkg == nil || objPkg == types.Unsafe) + return objPkg, objName + } + + // Ignore local types promoted to global scope (#55110). + if _, suffix := splitVargenSuffix(objName); suffix != "" { + return objPkg, objName + } + + if objPkg.Scope().Lookup(objName) == nil { + dict := pr.objDictIdx(idx) + + r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1) + r.dict = dict + + declare := func(obj types.Object) { + objPkg.Scope().Insert(obj) + } + + switch tag { + default: + panic("weird") + + case pkgbits.ObjAlias: + pos := r.pos() + var tparams []*types.TypeParam + if r.Version().Has(pkgbits.AliasTypeParamNames) { + tparams = r.typeParamNames() + } + typ := r.typ() + declare(aliases.NewAlias(r.p.aliases, pos, objPkg, objName, typ, tparams)) + + case pkgbits.ObjConst: + pos := r.pos() + typ := r.typ() + val := r.Value() + declare(types.NewConst(pos, objPkg, objName, typ, val)) + + case pkgbits.ObjFunc: + pos := r.pos() + tparams := r.typeParamNames() + sig := r.signature(nil, nil, tparams) + declare(types.NewFunc(pos, objPkg, objName, sig)) + + case pkgbits.ObjType: + pos := r.pos() + + obj := types.NewTypeName(pos, objPkg, objName, nil) + named := types.NewNamed(obj, nil, nil) + declare(obj) + + named.SetTypeParams(r.typeParamNames()) + + setUnderlying := func(underlying types.Type) { + // If the underlying type is an interface, we need to + // duplicate its methods so we can replace the receiver + // parameter's type (#49906). + if iface, ok := types.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 { + methods := make([]*types.Func, iface.NumExplicitMethods()) + for i := range methods { + fn := iface.ExplicitMethod(i) + sig := fn.Type().(*types.Signature) + + recv := types.NewVar(fn.Pos(), fn.Pkg(), "", named) + typesinternal.SetVarKind(recv, typesinternal.RecvVar) + methods[i] = types.NewFunc(fn.Pos(), fn.Pkg(), fn.Name(), types.NewSignatureType(recv, nil, nil, sig.Params(), sig.Results(), sig.Variadic())) + } + + embeds := make([]types.Type, iface.NumEmbeddeds()) + for i := range embeds { + embeds[i] = iface.EmbeddedType(i) + } + + newIface := types.NewInterfaceType(methods, embeds) + r.p.ifaces = append(r.p.ifaces, newIface) + underlying = newIface + } + + named.SetUnderlying(underlying) + } + + // Since go.dev/cl/455279, we can assume rhs.Underlying() will + // always be non-nil. However, to temporarily support users of + // older snapshot releases, we continue to fallback to the old + // behavior for now. + // + // TODO(mdempsky): Remove fallback code and simplify after + // allowing time for snapshot users to upgrade. + rhs := r.typ() + if underlying := rhs.Underlying(); underlying != nil { + setUnderlying(underlying) + } else { + pk := r.p + pk.laterFor(named, func() { + // First be sure that the rhs is initialized, if it needs to be initialized. + delete(pk.laterFors, named) // prevent cycles + if i, ok := pk.laterFors[rhs]; ok { + f := pk.laterFns[i] + pk.laterFns[i] = func() {} // function is running now, so replace it with a no-op + f() // initialize RHS + } + setUnderlying(rhs.Underlying()) + }) + } + + for i, n := 0, r.Len(); i < n; i++ { + named.AddMethod(r.method()) + } + + case pkgbits.ObjVar: + pos := r.pos() + typ := r.typ() + v := types.NewVar(pos, objPkg, objName, typ) + typesinternal.SetVarKind(v, typesinternal.PackageVar) + declare(v) + } + } + + return objPkg, objName +} + +func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict { + + var dict readerDict + + { + r := pr.tempReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1) + if implicits := r.Len(); implicits != 0 { + errorf("unexpected object with %v implicit type parameter(s)", implicits) + } + + dict.bounds = make([]typeInfo, r.Len()) + for i := range dict.bounds { + dict.bounds[i] = r.typInfo() + } + + dict.derived = make([]derivedInfo, r.Len()) + dict.derivedTypes = make([]types.Type, len(dict.derived)) + for i := range dict.derived { + dict.derived[i] = derivedInfo{idx: r.Reloc(pkgbits.RelocType)} + if r.Version().Has(pkgbits.DerivedInfoNeeded) { + assert(!r.Bool()) + } + } + + pr.retireReader(r) + } + // function references follow, but reader doesn't need those + + return &dict +} + +func (r *reader) typeParamNames() []*types.TypeParam { + r.Sync(pkgbits.SyncTypeParamNames) + + // Note: This code assumes it only processes objects without + // implement type parameters. This is currently fine, because + // reader is only used to read in exported declarations, which are + // always package scoped. + + if len(r.dict.bounds) == 0 { + return nil + } + + // Careful: Type parameter lists may have cycles. To allow for this, + // we construct the type parameter list in two passes: first we + // create all the TypeNames and TypeParams, then we construct and + // set the bound type. + + r.dict.tparams = make([]*types.TypeParam, len(r.dict.bounds)) + for i := range r.dict.bounds { + pos := r.pos() + pkg, name := r.localIdent() + + tname := types.NewTypeName(pos, pkg, name, nil) + r.dict.tparams[i] = types.NewTypeParam(tname, nil) + } + + typs := make([]types.Type, len(r.dict.bounds)) + for i, bound := range r.dict.bounds { + typs[i] = r.p.typIdx(bound, r.dict) + } + + // TODO(mdempsky): This is subtle, elaborate further. + // + // We have to save tparams outside of the closure, because + // typeParamNames() can be called multiple times with the same + // dictionary instance. + // + // Also, this needs to happen later to make sure SetUnderlying has + // been called. + // + // TODO(mdempsky): Is it safe to have a single "later" slice or do + // we need to have multiple passes? See comments on CL 386002 and + // go.dev/issue/52104. + tparams := r.dict.tparams + r.p.later(func() { + for i, typ := range typs { + tparams[i].SetConstraint(typ) + } + }) + + return r.dict.tparams +} + +func (r *reader) method() *types.Func { + r.Sync(pkgbits.SyncMethod) + pos := r.pos() + pkg, name := r.selector() + + rparams := r.typeParamNames() + sig := r.signature(r.param(), rparams, nil) + + _ = r.pos() // TODO(mdempsky): Remove; this is a hacker for linker.go. + return types.NewFunc(pos, pkg, name, sig) +} + +func (r *reader) qualifiedIdent() (*types.Package, string) { return r.ident(pkgbits.SyncSym) } +func (r *reader) localIdent() (*types.Package, string) { return r.ident(pkgbits.SyncLocalIdent) } +func (r *reader) selector() (*types.Package, string) { return r.ident(pkgbits.SyncSelector) } + +func (r *reader) ident(marker pkgbits.SyncMarker) (*types.Package, string) { + r.Sync(marker) + return r.pkg(), r.String() +} + +// pkgScope returns pkg.Scope(). +// If pkg is nil, it returns types.Universe instead. +// +// TODO(mdempsky): Remove after x/tools can depend on Go 1.19. +func pkgScope(pkg *types.Package) *types.Scope { + if pkg != nil { + return pkg.Scope() + } + return types.Universe +} + +// See cmd/compile/internal/types.SplitVargenSuffix. +func splitVargenSuffix(name string) (base, suffix string) { + i := len(name) + for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' { + i-- + } + const dot = "·" + if i >= len(dot) && name[i-len(dot):i] == dot { + i -= len(dot) + return name[:i], name[i:] + } + return name, "" +} diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke.go b/vendor/golang.org/x/tools/internal/gocommand/invoke.go new file mode 100644 index 000000000..58721202d --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -0,0 +1,567 @@ +// Copyright 2020 The Go 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 gocommand is a helper for calling the go command. +package gocommand + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/tools/internal/event" + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" +) + +// A Runner will run go command invocations and serialize +// them if it sees a concurrency error. +type Runner struct { + // once guards the runner initialization. + once sync.Once + + // inFlight tracks available workers. + inFlight chan struct{} + + // serialized guards the ability to run a go command serially, + // to avoid deadlocks when claiming workers. + serialized chan struct{} +} + +const maxInFlight = 10 + +func (runner *Runner) initialize() { + runner.once.Do(func() { + runner.inFlight = make(chan struct{}, maxInFlight) + runner.serialized = make(chan struct{}, 1) + }) +} + +// 1.13: go: updates to go.mod needed, but contents have changed +// 1.14: go: updating go.mod: existing contents have changed since last read +var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`) + +// event keys for go command invocations +var ( + verb = keys.NewString("verb", "go command verb") + directory = keys.NewString("directory", "") +) + +func invLabels(inv Invocation) []label.Label { + return []label.Label{verb.Of(inv.Verb), directory.Of(inv.WorkingDir)} +} + +// Run is a convenience wrapper around RunRaw. +// It returns only stdout and a "friendly" error. +func (runner *Runner) Run(ctx context.Context, inv Invocation) (*bytes.Buffer, error) { + ctx, done := event.Start(ctx, "gocommand.Runner.Run", invLabels(inv)...) + defer done() + + stdout, _, friendly, _ := runner.RunRaw(ctx, inv) + return stdout, friendly +} + +// RunPiped runs the invocation serially, always waiting for any concurrent +// invocations to complete first. +func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) error { + ctx, done := event.Start(ctx, "gocommand.Runner.RunPiped", invLabels(inv)...) + defer done() + + _, err := runner.runPiped(ctx, inv, stdout, stderr) + return err +} + +// RunRaw runs the invocation, serializing requests only if they fight over +// go.mod changes. +// Postcondition: both error results have same nilness. +func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { + ctx, done := event.Start(ctx, "gocommand.Runner.RunRaw", invLabels(inv)...) + defer done() + // Make sure the runner is always initialized. + runner.initialize() + + // First, try to run the go command concurrently. + stdout, stderr, friendlyErr, err := runner.runConcurrent(ctx, inv) + + // If we encounter a load concurrency error, we need to retry serially. + if friendlyErr != nil && modConcurrencyError.MatchString(friendlyErr.Error()) { + event.Error(ctx, "Load concurrency error, will retry serially", err) + + // Run serially by calling runPiped. + stdout.Reset() + stderr.Reset() + friendlyErr, err = runner.runPiped(ctx, inv, stdout, stderr) + } + + return stdout, stderr, friendlyErr, err +} + +// Postcondition: both error results have same nilness. +func (runner *Runner) runConcurrent(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { + // Wait for 1 worker to become available. + select { + case <-ctx.Done(): + return nil, nil, ctx.Err(), ctx.Err() + case runner.inFlight <- struct{}{}: + defer func() { <-runner.inFlight }() + } + + stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} + friendlyErr, err := inv.runWithFriendlyError(ctx, stdout, stderr) + return stdout, stderr, friendlyErr, err +} + +// Postcondition: both error results have same nilness. +func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) (error, error) { + // Make sure the runner is always initialized. + runner.initialize() + + // Acquire the serialization lock. This avoids deadlocks between two + // runPiped commands. + select { + case <-ctx.Done(): + return ctx.Err(), ctx.Err() + case runner.serialized <- struct{}{}: + defer func() { <-runner.serialized }() + } + + // Wait for all in-progress go commands to return before proceeding, + // to avoid load concurrency errors. + for range maxInFlight { + select { + case <-ctx.Done(): + return ctx.Err(), ctx.Err() + case runner.inFlight <- struct{}{}: + // Make sure we always "return" any workers we took. + defer func() { <-runner.inFlight }() + } + } + + return inv.runWithFriendlyError(ctx, stdout, stderr) +} + +// An Invocation represents a call to the go command. +type Invocation struct { + Verb string + Args []string + BuildFlags []string + + // If ModFlag is set, the go command is invoked with -mod=ModFlag. + // TODO(rfindley): remove, in favor of Args. + ModFlag string + + // If ModFile is set, the go command is invoked with -modfile=ModFile. + // TODO(rfindley): remove, in favor of Args. + ModFile string + + // Overlay is the name of the JSON overlay file that describes + // unsaved editor buffers; see [WriteOverlays]. + // If set, the go command is invoked with -overlay=Overlay. + // TODO(rfindley): remove, in favor of Args. + Overlay string + + // If CleanEnv is set, the invocation will run only with the environment + // in Env, not starting with os.Environ. + CleanEnv bool + Env []string + WorkingDir string + Logf func(format string, args ...any) +} + +// Postcondition: both error results have same nilness. +func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io.Writer) (friendlyError error, rawError error) { + rawError = i.run(ctx, stdout, stderr) + if rawError != nil { + friendlyError = rawError + // Check for 'go' executable not being found. + if ee, ok := rawError.(*exec.Error); ok && ee.Err == exec.ErrNotFound { + friendlyError = fmt.Errorf("go command required, not found: %v", ee) + } + if ctx.Err() != nil { + friendlyError = ctx.Err() + } + friendlyError = fmt.Errorf("err: %v: stderr: %s", friendlyError, stderr) + } + return +} + +// logf logs if i.Logf is non-nil. +func (i *Invocation) logf(format string, args ...any) { + if i.Logf != nil { + i.Logf(format, args...) + } +} + +func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { + goArgs := []string{i.Verb} + + appendModFile := func() { + if i.ModFile != "" { + goArgs = append(goArgs, "-modfile="+i.ModFile) + } + } + appendModFlag := func() { + if i.ModFlag != "" { + goArgs = append(goArgs, "-mod="+i.ModFlag) + } + } + appendOverlayFlag := func() { + if i.Overlay != "" { + goArgs = append(goArgs, "-overlay="+i.Overlay) + } + } + + switch i.Verb { + case "env", "version": + goArgs = append(goArgs, i.Args...) + case "mod": + // mod needs the sub-verb before flags. + goArgs = append(goArgs, i.Args[0]) + appendModFile() + goArgs = append(goArgs, i.Args[1:]...) + case "get": + goArgs = append(goArgs, i.BuildFlags...) + appendModFile() + goArgs = append(goArgs, i.Args...) + + default: // notably list and build. + goArgs = append(goArgs, i.BuildFlags...) + appendModFile() + appendModFlag() + appendOverlayFlag() + goArgs = append(goArgs, i.Args...) + } + cmd := exec.Command("go", goArgs...) + cmd.Stdout = stdout + cmd.Stderr = stderr + + // https://go.dev/issue/59541: don't wait forever copying stderr + // after the command has exited. + // After CL 484741 we copy stdout manually, so we we'll stop reading that as + // soon as ctx is done. However, we also don't want to wait around forever + // for stderr. Give a much-longer-than-reasonable delay and then assume that + // something has wedged in the kernel or runtime. + cmd.WaitDelay = 30 * time.Second + + // The cwd gets resolved to the real path. On Darwin, where + // /tmp is a symlink, this breaks anything that expects the + // working directory to keep the original path, including the + // go command when dealing with modules. + // + // os.Getwd has a special feature where if the cwd and the PWD + // are the same node then it trusts the PWD, so by setting it + // in the env for the child process we fix up all the paths + // returned by the go command. + if !i.CleanEnv { + cmd.Env = os.Environ() + } + cmd.Env = append(cmd.Env, i.Env...) + if i.WorkingDir != "" { + cmd.Env = append(cmd.Env, "PWD="+i.WorkingDir) + cmd.Dir = i.WorkingDir + } + + debugStr := cmdDebugStr(cmd) + i.logf("starting %v", debugStr) + start := time.Now() + defer func() { + i.logf("%s for %v", time.Since(start), debugStr) + }() + + return runCmdContext(ctx, cmd) +} + +// DebugHangingGoCommands may be set by tests to enable additional +// instrumentation (including panics) for debugging hanging Go commands. +// +// See golang/go#54461 for details. +var DebugHangingGoCommands = false + +// runCmdContext is like exec.CommandContext except it sends os.Interrupt +// before os.Kill. +func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) { + // If cmd.Stdout is not an *os.File, the exec package will create a pipe and + // copy it to the Writer in a goroutine until the process has finished and + // either the pipe reaches EOF or command's WaitDelay expires. + // + // However, the output from 'go list' can be quite large, and we don't want to + // keep reading (and allocating buffers) if we've already decided we don't + // care about the output. We don't want to wait for the process to finish, and + // we don't wait to wait for the WaitDelay to expire either. + // + // Instead, if cmd.Stdout requires a copying goroutine we explicitly replace + // it with a pipe (which is an *os.File), which we can close in order to stop + // copying output as soon as we realize we don't care about it. + var stdoutW *os.File + if cmd.Stdout != nil { + if _, ok := cmd.Stdout.(*os.File); !ok { + var stdoutR *os.File + stdoutR, stdoutW, err = os.Pipe() + if err != nil { + return err + } + prevStdout := cmd.Stdout + cmd.Stdout = stdoutW + + stdoutErr := make(chan error, 1) + go func() { + _, err := io.Copy(prevStdout, stdoutR) + if err != nil { + err = fmt.Errorf("copying stdout: %w", err) + } + stdoutErr <- err + }() + defer func() { + // We started a goroutine to copy a stdout pipe. + // Wait for it to finish, or terminate it if need be. + var err2 error + select { + case err2 = <-stdoutErr: + stdoutR.Close() + case <-ctx.Done(): + stdoutR.Close() + // Per https://pkg.go.dev/os#File.Close, the call to stdoutR.Close + // should cause the Read call in io.Copy to unblock and return + // immediately, but we still need to receive from stdoutErr to confirm + // that it has happened. + <-stdoutErr + err2 = ctx.Err() + } + if err == nil { + err = err2 + } + }() + + // Per https://pkg.go.dev/os/exec#Cmd, “If Stdout and Stderr are the + // same writer, and have a type that can be compared with ==, at most + // one goroutine at a time will call Write.” + // + // Since we're starting a goroutine that writes to cmd.Stdout, we must + // also update cmd.Stderr so that it still holds. + func() { + defer func() { recover() }() + if cmd.Stderr == prevStdout { + cmd.Stderr = cmd.Stdout + } + }() + } + } + + startTime := time.Now() + err = cmd.Start() + if stdoutW != nil { + // The child process has inherited the pipe file, + // so close the copy held in this process. + stdoutW.Close() + stdoutW = nil + } + if err != nil { + return err + } + + resChan := make(chan error, 1) + go func() { + resChan <- cmd.Wait() + }() + + // If we're interested in debugging hanging Go commands, stop waiting after a + // minute and panic with interesting information. + debug := DebugHangingGoCommands + if debug { + timer := time.NewTimer(1 * time.Minute) + defer timer.Stop() + select { + case err := <-resChan: + return err + case <-timer.C: + // HandleHangingGoCommand terminates this process. + // Pass off resChan in case we can collect the command error. + handleHangingGoCommand(startTime, cmd, resChan) + case <-ctx.Done(): + } + } else { + select { + case err := <-resChan: + return err + case <-ctx.Done(): + } + } + + // Cancelled. Interrupt and see if it ends voluntarily. + if err := cmd.Process.Signal(os.Interrupt); err == nil { + // (We used to wait only 1s but this proved + // fragile on loaded builder machines.) + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + select { + case err := <-resChan: + return err + case <-timer.C: + } + } + + // Didn't shut down in response to interrupt. Kill it hard. + if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) && debug { + log.Printf("error killing the Go command: %v", err) + } + + return <-resChan +} + +// handleHangingGoCommand outputs debugging information to help diagnose the +// cause of a hanging Go command, and then exits with log.Fatalf. +func handleHangingGoCommand(start time.Time, cmd *exec.Cmd, resChan chan error) { + switch runtime.GOOS { + case "linux", "darwin", "freebsd", "netbsd", "openbsd": + fmt.Fprintln(os.Stderr, `DETECTED A HANGING GO COMMAND + + The gopls test runner has detected a hanging go command. In order to debug + this, the output of ps and lsof/fstat is printed below. + + See golang/go#54461 for more details.`) + + fmt.Fprintln(os.Stderr, "\nps axo ppid,pid,command:") + fmt.Fprintln(os.Stderr, "-------------------------") + psCmd := exec.Command("ps", "axo", "ppid,pid,command") + psCmd.Stdout = os.Stderr + psCmd.Stderr = os.Stderr + if err := psCmd.Run(); err != nil { + log.Printf("Handling hanging Go command: running ps: %v", err) + } + + listFiles := "lsof" + if runtime.GOOS == "freebsd" || runtime.GOOS == "netbsd" { + listFiles = "fstat" + } + + fmt.Fprintln(os.Stderr, "\n"+listFiles+":") + fmt.Fprintln(os.Stderr, "-----") + listFilesCmd := exec.Command(listFiles) + listFilesCmd.Stdout = os.Stderr + listFilesCmd.Stderr = os.Stderr + if err := listFilesCmd.Run(); err != nil { + log.Printf("Handling hanging Go command: running %s: %v", listFiles, err) + } + // Try to extract information about the slow go process by issuing a SIGQUIT. + if err := cmd.Process.Signal(sigStuckProcess); err == nil { + select { + case err := <-resChan: + stderr := "not a bytes.Buffer" + if buf, _ := cmd.Stderr.(*bytes.Buffer); buf != nil { + stderr = buf.String() + } + log.Printf("Quit hanging go command:\n\terr:%v\n\tstderr:\n%v\n\n", err, stderr) + case <-time.After(5 * time.Second): + } + } else { + log.Printf("Sending signal %d to hanging go command: %v", sigStuckProcess, err) + } + } + log.Fatalf("detected hanging go command (golang/go#54461); waited %s\n\tcommand:%s\n\tpid:%d", time.Since(start), cmd, cmd.Process.Pid) +} + +func cmdDebugStr(cmd *exec.Cmd) string { + env := make(map[string]string) + for _, kv := range cmd.Env { + split := strings.SplitN(kv, "=", 2) + if len(split) == 2 { + k, v := split[0], split[1] + env[k] = v + } + } + + var args []string + for _, arg := range cmd.Args { + quoted := strconv.Quote(arg) + if quoted[1:len(quoted)-1] != arg || strings.Contains(arg, " ") { + args = append(args, quoted) + } else { + args = append(args, arg) + } + } + return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " ")) +} + +// WriteOverlays writes each value in the overlay (see the Overlay +// field of go/packages.Config) to a temporary file and returns the name +// of a JSON file describing the mapping that is suitable for the "go +// list -overlay" flag. +// +// On success, the caller must call the cleanup function exactly once +// when the files are no longer needed. +func WriteOverlays(overlay map[string][]byte) (filename string, cleanup func(), err error) { + // Do nothing if there are no overlays in the config. + if len(overlay) == 0 { + return "", func() {}, nil + } + + dir, err := os.MkdirTemp("", "gocommand-*") + if err != nil { + return "", nil, err + } + + // The caller must clean up this directory, + // unless this function returns an error. + // (The cleanup operand of each return + // statement below is ignored.) + defer func() { + cleanup = func() { + os.RemoveAll(dir) + } + if err != nil { + cleanup() + cleanup = nil + } + }() + + // Write each map entry to a temporary file. + overlays := make(map[string]string) + for k, v := range overlay { + // Use a unique basename for each file (001-foo.go), + // to avoid creating nested directories. + base := fmt.Sprintf("%d-%s", 1+len(overlays), filepath.Base(k)) + filename := filepath.Join(dir, base) + err := os.WriteFile(filename, v, 0666) + if err != nil { + return "", nil, err + } + overlays[k] = filename + } + + // Write the JSON overlay file that maps logical file names to temp files. + // + // OverlayJSON is the format overlay files are expected to be in. + // The Replace map maps from overlaid paths to replacement paths: + // the Go command will forward all reads trying to open + // each overlaid path to its replacement path, or consider the overlaid + // path not to exist if the replacement path is empty. + // + // From golang/go#39958. + type OverlayJSON struct { + Replace map[string]string `json:"replace,omitempty"` + } + b, err := json.Marshal(OverlayJSON{Replace: overlays}) + if err != nil { + return "", nil, err + } + filename = filepath.Join(dir, "overlay.json") + if err := os.WriteFile(filename, b, 0666); err != nil { + return "", nil, err + } + + return filename, nil, nil +} diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke_notunix.go b/vendor/golang.org/x/tools/internal/gocommand/invoke_notunix.go new file mode 100644 index 000000000..469c648e4 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke_notunix.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !unix + +package gocommand + +import "os" + +// sigStuckProcess is the signal to send to kill a hanging subprocess. +// On Unix we send SIGQUIT, but on non-Unix we only have os.Kill. +var sigStuckProcess = os.Kill diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke_unix.go b/vendor/golang.org/x/tools/internal/gocommand/invoke_unix.go new file mode 100644 index 000000000..169d37c8e --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke_unix.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package gocommand + +import "syscall" + +// Sigstuckprocess is the signal to send to kill a hanging subprocess. +// Send SIGQUIT to get a stack trace. +var sigStuckProcess = syscall.SIGQUIT diff --git a/vendor/golang.org/x/tools/internal/gocommand/vendor.go b/vendor/golang.org/x/tools/internal/gocommand/vendor.go new file mode 100644 index 000000000..e38d1fb48 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/vendor.go @@ -0,0 +1,163 @@ +// Copyright 2020 The Go 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 gocommand + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "golang.org/x/mod/semver" +) + +// ModuleJSON holds information about a module. +type ModuleJSON struct { + Path string // module path + Version string // module version + Versions []string // available module versions (with -versions) + Replace *ModuleJSON // replaced by this module + Time *time.Time // time version was created + Update *ModuleJSON // available update, if any (with -u) + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file used when loading this module, if any + GoVersion string // go version used in module +} + +var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`) + +// VendorEnabled reports whether vendoring is enabled. It takes a *Runner to execute Go commands +// with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, +// of which only Verb and Args are modified to run the appropriate Go command. +// Inspired by setDefaultBuildMod in modload/init.go +func VendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, *ModuleJSON, error) { + mainMod, go114, err := getMainModuleAnd114(ctx, inv, r) + if err != nil { + return false, nil, err + } + + // We check the GOFLAGS to see if there is anything overridden or not. + inv.Verb = "env" + inv.Args = []string{"GOFLAGS"} + stdout, err := r.Run(ctx, inv) + if err != nil { + return false, nil, err + } + goflags := string(bytes.TrimSpace(stdout.Bytes())) + matches := modFlagRegexp.FindStringSubmatch(goflags) + var modFlag string + if len(matches) != 0 { + modFlag = matches[1] + } + // Don't override an explicit '-mod=' argument. + if modFlag == "vendor" { + return true, mainMod, nil + } else if modFlag != "" { + return false, nil, nil + } + if mainMod == nil || !go114 { + return false, nil, nil + } + // Check 1.14's automatic vendor mode. + if fi, err := os.Stat(filepath.Join(mainMod.Dir, "vendor")); err == nil && fi.IsDir() { + if mainMod.GoVersion != "" && semver.Compare("v"+mainMod.GoVersion, "v1.14") >= 0 { + // The Go version is at least 1.14, and a vendor directory exists. + // Set -mod=vendor by default. + return true, mainMod, nil + } + } + return false, nil, nil +} + +// getMainModuleAnd114 gets one of the main modules' information and whether the +// go command in use is 1.14+. This is the information needed to figure out +// if vendoring should be enabled. +func getMainModuleAnd114(ctx context.Context, inv Invocation, r *Runner) (*ModuleJSON, bool, error) { + const format = `{{.Path}} +{{.Dir}} +{{.GoMod}} +{{.GoVersion}} +{{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}} +` + inv.Verb = "list" + inv.Args = []string{"-m", "-f", format} + stdout, err := r.Run(ctx, inv) + if err != nil { + return nil, false, err + } + + lines := strings.Split(stdout.String(), "\n") + if len(lines) < 5 { + return nil, false, fmt.Errorf("unexpected stdout: %q", stdout.String()) + } + mod := &ModuleJSON{ + Path: lines[0], + Dir: lines[1], + GoMod: lines[2], + GoVersion: lines[3], + Main: true, + } + return mod, lines[4] == "go1.14", nil +} + +// WorkspaceVendorEnabled reports whether workspace vendoring is enabled. It takes a *Runner to execute Go commands +// with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, +// of which only Verb and Args are modified to run the appropriate Go command. +// Inspired by setDefaultBuildMod in modload/init.go +func WorkspaceVendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, []*ModuleJSON, error) { + inv.Verb = "env" + inv.Args = []string{"GOWORK"} + stdout, err := r.Run(ctx, inv) + if err != nil { + return false, nil, err + } + goWork := string(bytes.TrimSpace(stdout.Bytes())) + if fi, err := os.Stat(filepath.Join(filepath.Dir(goWork), "vendor")); err == nil && fi.IsDir() { + mainMods, err := getWorkspaceMainModules(ctx, inv, r) + if err != nil { + return false, nil, err + } + return true, mainMods, nil + } + return false, nil, nil +} + +// getWorkspaceMainModules gets the main modules' information. +// This is the information needed to figure out if vendoring should be enabled. +func getWorkspaceMainModules(ctx context.Context, inv Invocation, r *Runner) ([]*ModuleJSON, error) { + const format = `{{.Path}} +{{.Dir}} +{{.GoMod}} +{{.GoVersion}} +` + inv.Verb = "list" + inv.Args = []string{"-m", "-f", format} + stdout, err := r.Run(ctx, inv) + if err != nil { + return nil, err + } + + lines := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n") + if len(lines) < 4 { + return nil, fmt.Errorf("unexpected stdout: %q", stdout.String()) + } + mods := make([]*ModuleJSON, 0, len(lines)/4) + for i := 0; i < len(lines); i += 4 { + mods = append(mods, &ModuleJSON{ + Path: lines[i], + Dir: lines[i+1], + GoMod: lines[i+2], + GoVersion: lines[i+3], + Main: true, + }) + } + return mods, nil +} diff --git a/vendor/golang.org/x/tools/internal/gocommand/version.go b/vendor/golang.org/x/tools/internal/gocommand/version.go new file mode 100644 index 000000000..446c5846a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/version.go @@ -0,0 +1,71 @@ +// Copyright 2020 The Go 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 gocommand + +import ( + "context" + "fmt" + "regexp" + "strings" +) + +// GoVersion reports the minor version number of the highest release +// tag built into the go command on the PATH. +// +// Note that this may be higher than the version of the go tool used +// to build this application, and thus the versions of the standard +// go/{scanner,parser,ast,types} packages that are linked into it. +// In that case, callers should either downgrade to the version of +// go used to build the application, or report an error that the +// application is too old to use the go command on the PATH. +func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) { + inv.Verb = "list" + inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`} + inv.BuildFlags = nil // This is not a build command. + inv.ModFlag = "" + inv.ModFile = "" + inv.Env = append(inv.Env[:len(inv.Env):len(inv.Env)], "GO111MODULE=off") + + stdoutBytes, err := r.Run(ctx, inv) + if err != nil { + return 0, err + } + stdout := stdoutBytes.String() + if len(stdout) < 3 { + return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout) + } + // Split up "[go1.1 go1.15]" and return highest go1.X value. + tags := strings.Fields(stdout[1 : len(stdout)-2]) + for i := len(tags) - 1; i >= 0; i-- { + var version int + if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil { + continue + } + return version, nil + } + return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags) +} + +// GoVersionOutput returns the complete output of the go version command. +func GoVersionOutput(ctx context.Context, inv Invocation, r *Runner) (string, error) { + inv.Verb = "version" + goVersion, err := r.Run(ctx, inv) + if err != nil { + return "", err + } + return goVersion.String(), nil +} + +// ParseGoVersionOutput extracts the Go version string +// from the output of the "go version" command. +// Given an unrecognized form, it returns an empty string. +func ParseGoVersionOutput(data string) string { + re := regexp.MustCompile(`^go version (go\S+|devel \S+)`) + m := re.FindStringSubmatch(data) + if len(m) != 2 { + return "" // unrecognized version + } + return m[1] +} diff --git a/vendor/golang.org/x/tools/internal/gopathwalk/walk.go b/vendor/golang.org/x/tools/internal/gopathwalk/walk.go new file mode 100644 index 000000000..5252144d0 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gopathwalk/walk.go @@ -0,0 +1,336 @@ +// Copyright 2018 The Go 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 gopathwalk is like filepath.Walk but specialized for finding Go +// packages, particularly in $GOPATH and $GOROOT. +package gopathwalk + +import ( + "bufio" + "bytes" + "io" + "io/fs" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "time" +) + +// Options controls the behavior of a Walk call. +type Options struct { + // If Logf is non-nil, debug logging is enabled through this function. + Logf func(format string, args ...any) + + // Search module caches. Also disables legacy goimports ignore rules. + ModulesEnabled bool + + // Maximum number of concurrent calls to user-provided callbacks, + // or 0 for GOMAXPROCS. + Concurrency int +} + +// RootType indicates the type of a Root. +type RootType int + +const ( + RootUnknown RootType = iota + RootGOROOT + RootGOPATH + RootCurrentModule + RootModuleCache + RootOther +) + +// A Root is a starting point for a Walk. +type Root struct { + Path string + Type RootType +} + +// Walk concurrently walks Go source directories ($GOROOT, $GOPATH, etc) to find packages. +// +// For each package found, add will be called with the absolute +// paths of the containing source directory and the package directory. +// +// Unlike filepath.WalkDir, Walk follows symbolic links +// (while guarding against cycles). +func Walk(roots []Root, add func(root Root, dir string), opts Options) { + WalkSkip(roots, add, func(Root, string) bool { return false }, opts) +} + +// WalkSkip concurrently walks Go source directories ($GOROOT, $GOPATH, etc) to +// find packages. +// +// For each package found, add will be called with the absolute +// paths of the containing source directory and the package directory. +// For each directory that will be scanned, skip will be called +// with the absolute paths of the containing source directory and the directory. +// If skip returns false on a directory it will be processed. +// +// Unlike filepath.WalkDir, WalkSkip follows symbolic links +// (while guarding against cycles). +func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root, dir string) bool, opts Options) { + for _, root := range roots { + walkDir(root, add, skip, opts) + } +} + +// walkDir creates a walker and starts fastwalk with this walker. +func walkDir(root Root, add func(Root, string), skip func(root Root, dir string) bool, opts Options) { + if opts.Logf == nil { + opts.Logf = func(format string, args ...any) {} + } + if _, err := os.Stat(root.Path); os.IsNotExist(err) { + opts.Logf("skipping nonexistent directory: %v", root.Path) + return + } + start := time.Now() + opts.Logf("scanning %s", root.Path) + + concurrency := opts.Concurrency + if concurrency == 0 { + // The walk be either CPU-bound or I/O-bound, depending on what the + // caller-supplied add function does and the details of the user's platform + // and machine. Rather than trying to fine-tune the concurrency level for a + // specific environment, we default to GOMAXPROCS: it is likely to be a good + // choice for a CPU-bound add function, and if it is instead I/O-bound, then + // dealing with I/O saturation is arguably the job of the kernel and/or + // runtime. (Oversaturating I/O seems unlikely to harm performance as badly + // as failing to saturate would.) + concurrency = runtime.GOMAXPROCS(0) + } + w := &walker{ + root: root, + add: add, + skip: skip, + opts: opts, + sem: make(chan struct{}, concurrency), + } + w.init() + + w.sem <- struct{}{} + path := root.Path + if path == "" { + path = "." + } + if fi, err := os.Lstat(path); err == nil { + w.walk(path, nil, fs.FileInfoToDirEntry(fi)) + } else { + w.opts.Logf("scanning directory %v: %v", root.Path, err) + } + <-w.sem + w.walking.Wait() + + opts.Logf("scanned %s in %v", root.Path, time.Since(start)) +} + +// walker is the callback for fastwalk.Walk. +type walker struct { + root Root // The source directory to scan. + add func(Root, string) // The callback that will be invoked for every possible Go package dir. + skip func(Root, string) bool // The callback that will be invoked for every dir. dir is skipped if it returns true. + opts Options // Options passed to Walk by the user. + + walking sync.WaitGroup + sem chan struct{} // Channel of semaphore tokens; send to acquire, receive to release. + ignoredDirs []string + + added sync.Map // map[string]bool +} + +// A symlinkList is a linked list of os.FileInfos for parent directories +// reached via symlinks. +type symlinkList struct { + info os.FileInfo + prev *symlinkList +} + +// init initializes the walker based on its Options +func (w *walker) init() { + var ignoredPaths []string + if w.root.Type == RootModuleCache { + ignoredPaths = []string{"cache"} + } + if !w.opts.ModulesEnabled && w.root.Type == RootGOPATH { + ignoredPaths = w.getIgnoredDirs(w.root.Path) + ignoredPaths = append(ignoredPaths, "v", "mod") + } + + for _, p := range ignoredPaths { + full := filepath.Join(w.root.Path, p) + w.ignoredDirs = append(w.ignoredDirs, full) + w.opts.Logf("Directory added to ignore list: %s", full) + } +} + +// getIgnoredDirs reads an optional config file at /.goimportsignore +// of relative directories to ignore when scanning for go files. +// The provided path is one of the $GOPATH entries with "src" appended. +func (w *walker) getIgnoredDirs(path string) []string { + file := filepath.Join(path, ".goimportsignore") + slurp, err := os.ReadFile(file) + if err != nil { + w.opts.Logf("%v", err) + } else { + w.opts.Logf("Read %s", file) + } + if err != nil { + return nil + } + + var ignoredDirs []string + bs := bufio.NewScanner(bytes.NewReader(slurp)) + for bs.Scan() { + line := strings.TrimSpace(bs.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + ignoredDirs = append(ignoredDirs, line) + } + return ignoredDirs +} + +// shouldSkipDir reports whether the file should be skipped or not. +func (w *walker) shouldSkipDir(dir string) bool { + if slices.Contains(w.ignoredDirs, dir) { + return true + } + if w.skip != nil { + // Check with the user specified callback. + return w.skip(w.root, dir) + } + return false +} + +// walk walks through the given path. +// +// Errors are logged if w.opts.Logf is non-nil, but otherwise ignored. +func (w *walker) walk(path string, pathSymlinks *symlinkList, d fs.DirEntry) { + if d.Type()&os.ModeSymlink != 0 { + // Walk the symlink's target rather than the symlink itself. + // + // (Note that os.Stat, unlike the lower-lever os.Readlink, + // follows arbitrarily many layers of symlinks, so it will eventually + // reach either a non-symlink or a nonexistent target.) + // + // TODO(bcmills): 'go list all' itself ignores symlinks within GOROOT/src + // and GOPATH/src. Do we really need to traverse them here? If so, why? + + fi, err := os.Stat(path) + if err != nil { + w.opts.Logf("%v", err) + return + } + + // Avoid walking symlink cycles: if we have already followed a symlink to + // this directory as a parent of itself, don't follow it again. + // + // This doesn't catch the first time through a cycle, but it also minimizes + // the number of extra stat calls we make if we *don't* encounter a cycle. + // Since we don't actually expect to encounter symlink cycles in practice, + // this seems like the right tradeoff. + for parent := pathSymlinks; parent != nil; parent = parent.prev { + if os.SameFile(fi, parent.info) { + return + } + } + + pathSymlinks = &symlinkList{ + info: fi, + prev: pathSymlinks, + } + d = fs.FileInfoToDirEntry(fi) + } + + if d.Type().IsRegular() { + if !strings.HasSuffix(path, ".go") { + return + } + + dir := filepath.Dir(path) + if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) { + // Doesn't make sense to have regular files + // directly in your $GOPATH/src or $GOROOT/src. + // + // TODO(bcmills): there are many levels of directory within + // RootModuleCache where this also wouldn't make sense, + // Can we generalize this to any directory without a corresponding + // import path? + return + } + + if _, dup := w.added.LoadOrStore(dir, true); !dup { + w.add(w.root, dir) + } + } + + if !d.IsDir() { + return + } + + base := filepath.Base(path) + if base == "" || base[0] == '.' || base[0] == '_' || + base == "testdata" || + (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") || + (!w.opts.ModulesEnabled && base == "node_modules") || + w.shouldSkipDir(path) { + return + } + + // Read the directory and walk its entries. + + f, err := os.Open(path) + if err != nil { + w.opts.Logf("%v", err) + return + } + defer f.Close() + + for { + // We impose an arbitrary limit on the number of ReadDir results per + // directory to limit the amount of memory consumed for stale or upcoming + // directory entries. The limit trades off CPU (number of syscalls to read + // the whole directory) against RAM (reachable directory entries other than + // the one currently being processed). + // + // Since we process the directories recursively, we will end up maintaining + // a slice of entries for each level of the directory tree. + // (Compare https://go.dev/issue/36197.) + ents, err := f.ReadDir(1024) + if err != nil { + if err != io.EOF { + w.opts.Logf("%v", err) + } + break + } + + for _, d := range ents { + nextPath := filepath.Join(path, d.Name()) + if d.IsDir() { + select { + case w.sem <- struct{}{}: + // Got a new semaphore token, so we can traverse the directory concurrently. + d := d + w.walking.Add(1) + go func() { + defer func() { + <-w.sem + w.walking.Done() + }() + w.walk(nextPath, pathSymlinks, d) + }() + continue + + default: + // No tokens available, so traverse serially. + } + } + + w.walk(nextPath, pathSymlinks, d) + } + } +} diff --git a/vendor/golang.org/x/tools/internal/imports/fix.go b/vendor/golang.org/x/tools/internal/imports/fix.go new file mode 100644 index 000000000..89b96381c --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/fix.go @@ -0,0 +1,1897 @@ +// Copyright 2013 The Go 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 imports + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "go/ast" + "go/build" + "go/parser" + "go/token" + "go/types" + "io/fs" + "io/ioutil" + "os" + "path" + "path/filepath" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "unicode" + "unicode/utf8" + + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/internal/event" + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" + "maps" +) + +// importToGroup is a list of functions which map from an import path to +// a group number. +var importToGroup = []func(localPrefix, importPath string) (num int, ok bool){ + func(localPrefix, importPath string) (num int, ok bool) { + if localPrefix == "" { + return + } + for _, p := range strings.Split(localPrefix, ",") { + if strings.HasPrefix(importPath, p) || strings.TrimSuffix(p, "/") == importPath { + return 3, true + } + } + return + }, + func(_, importPath string) (num int, ok bool) { + if strings.HasPrefix(importPath, "appengine") { + return 2, true + } + return + }, + func(_, importPath string) (num int, ok bool) { + firstComponent := strings.Split(importPath, "/")[0] + if strings.Contains(firstComponent, ".") { + return 1, true + } + return + }, +} + +func importGroup(localPrefix, importPath string) int { + for _, fn := range importToGroup { + if n, ok := fn(localPrefix, importPath); ok { + return n + } + } + return 0 +} + +type ImportFixType int + +const ( + AddImport ImportFixType = iota + DeleteImport + SetImportName +) + +type ImportFix struct { + // StmtInfo represents the import statement this fix will add, remove, or change. + StmtInfo ImportInfo + // IdentName is the identifier that this fix will add or remove. + IdentName string + // FixType is the type of fix this is (AddImport, DeleteImport, SetImportName). + FixType ImportFixType + Relevance float64 // see pkg +} + +// parseOtherFiles parses all the Go files in srcDir except filename, including +// test files if filename looks like a test. +// +// It returns an error only if ctx is cancelled. Files with parse errors are +// ignored. +func parseOtherFiles(ctx context.Context, fset *token.FileSet, srcDir, filename string) ([]*ast.File, error) { + // This could use go/packages but it doesn't buy much, and it fails + // with https://golang.org/issue/26296 in LoadFiles mode in some cases. + considerTests := strings.HasSuffix(filename, "_test.go") + + fileBase := filepath.Base(filename) + packageFileInfos, err := os.ReadDir(srcDir) + if err != nil { + return nil, ctx.Err() + } + + var files []*ast.File + for _, fi := range packageFileInfos { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if fi.Name() == fileBase || !strings.HasSuffix(fi.Name(), ".go") { + continue + } + if !considerTests && strings.HasSuffix(fi.Name(), "_test.go") { + continue + } + + f, err := parser.ParseFile(fset, filepath.Join(srcDir, fi.Name()), nil, parser.SkipObjectResolution) + if err != nil { + continue + } + + files = append(files, f) + } + + return files, ctx.Err() +} + +// addGlobals puts the names of package vars into the provided map. +func addGlobals(f *ast.File, globals map[string]bool) { + for _, decl := range f.Decls { + genDecl, ok := decl.(*ast.GenDecl) + if !ok { + continue + } + + for _, spec := range genDecl.Specs { + valueSpec, ok := spec.(*ast.ValueSpec) + if !ok { + continue + } + globals[valueSpec.Names[0].Name] = true + } + } +} + +// collectReferences builds a map of selector expressions, from +// left hand side (X) to a set of right hand sides (Sel). +func collectReferences(f *ast.File) References { + refs := References{} + + var visitor visitFn + visitor = func(node ast.Node) ast.Visitor { + if node == nil { + return visitor + } + switch v := node.(type) { + case *ast.SelectorExpr: + xident, ok := v.X.(*ast.Ident) + if !ok { + break + } + if xident.Obj != nil { + // If the parser can resolve it, it's not a package ref. + break + } + if !ast.IsExported(v.Sel.Name) { + // Whatever this is, it's not exported from a package. + break + } + pkgName := xident.Name + r := refs[pkgName] + if r == nil { + r = make(map[string]bool) + refs[pkgName] = r + } + r[v.Sel.Name] = true + } + return visitor + } + ast.Walk(visitor, f) + return refs +} + +// collectImports returns all the imports in f. +// Unnamed imports (., _) and "C" are ignored. +func collectImports(f *ast.File) []*ImportInfo { + var imports []*ImportInfo + for _, imp := range f.Imports { + var name string + if imp.Name != nil { + name = imp.Name.Name + } + if imp.Path.Value == `"C"` || name == "_" || name == "." { + continue + } + path := strings.Trim(imp.Path.Value, `"`) + imports = append(imports, &ImportInfo{ + Name: name, + ImportPath: path, + }) + } + return imports +} + +// findMissingImport searches pass's candidates for an import that provides +// pkg, containing all of syms. +func (p *pass) findMissingImport(pkg string, syms map[string]bool) *ImportInfo { + for _, candidate := range p.candidates { + pkgInfo, ok := p.knownPackages[candidate.ImportPath] + if !ok { + continue + } + if p.importIdentifier(candidate) != pkg { + continue + } + + allFound := true + for right := range syms { + if !pkgInfo.Exports[right] { + allFound = false + break + } + } + + if allFound { + return candidate + } + } + return nil +} + +// A pass contains all the inputs and state necessary to fix a file's imports. +// It can be modified in some ways during use; see comments below. +type pass struct { + // Inputs. These must be set before a call to load, and not modified after. + fset *token.FileSet // fset used to parse f and its siblings. + f *ast.File // the file being fixed. + srcDir string // the directory containing f. + logf func(string, ...any) + source Source // the environment to use for go commands, etc. + loadRealPackageNames bool // if true, load package names from disk rather than guessing them. + otherFiles []*ast.File // sibling files. + goroot string + + // Intermediate state, generated by load. + existingImports map[string][]*ImportInfo + allRefs References + missingRefs References + + // Inputs to fix. These can be augmented between successive fix calls. + lastTry bool // indicates that this is the last call and fix should clean up as best it can. + candidates []*ImportInfo // candidate imports in priority order. + knownPackages map[string]*PackageInfo // information about all known packages. +} + +// loadPackageNames saves the package names for everything referenced by imports. +func (p *pass) loadPackageNames(ctx context.Context, imports []*ImportInfo) error { + if p.logf != nil { + p.logf("loading package names for %v packages", len(imports)) + defer func() { + p.logf("done loading package names for %v packages", len(imports)) + }() + } + var unknown []string + for _, imp := range imports { + if _, ok := p.knownPackages[imp.ImportPath]; ok { + continue + } + unknown = append(unknown, imp.ImportPath) + } + + names, err := p.source.LoadPackageNames(ctx, p.srcDir, unknown) + if err != nil { + return err + } + + // TODO(rfindley): revisit this. Why do we need to store known packages with + // no exports? The inconsistent data is confusing. + for path, name := range names { + p.knownPackages[path] = &PackageInfo{ + Name: name, + Exports: map[string]bool{}, + } + } + return nil +} + +// if there is a trailing major version, remove it +func withoutVersion(nm string) string { + if v := path.Base(nm); len(v) > 0 && v[0] == 'v' { + if _, err := strconv.Atoi(v[1:]); err == nil { + // this is, for instance, called with rand/v2 and returns rand + if len(v) < len(nm) { + xnm := nm[:len(nm)-len(v)-1] + return path.Base(xnm) + } + } + } + return nm +} + +// importIdentifier returns the identifier that imp will introduce. It will +// guess if the package name has not been loaded, e.g. because the source +// is not available. +func (p *pass) importIdentifier(imp *ImportInfo) string { + if imp.Name != "" { + return imp.Name + } + known := p.knownPackages[imp.ImportPath] + if known != nil && known.Name != "" { + return withoutVersion(known.Name) + } + return ImportPathToAssumedName(imp.ImportPath) +} + +// load reads in everything necessary to run a pass, and reports whether the +// file already has all the imports it needs. It fills in p.missingRefs with the +// file's missing symbols, if any, or removes unused imports if not. +func (p *pass) load(ctx context.Context) ([]*ImportFix, bool) { + p.knownPackages = map[string]*PackageInfo{} + p.missingRefs = References{} + p.existingImports = map[string][]*ImportInfo{} + + // Load basic information about the file in question. + p.allRefs = collectReferences(p.f) + + // Load stuff from other files in the same package: + // global variables so we know they don't need resolving, and imports + // that we might want to mimic. + globals := map[string]bool{} + for _, otherFile := range p.otherFiles { + // Don't load globals from files that are in the same directory + // but a different package. Using them to suggest imports is OK. + if p.f.Name.Name == otherFile.Name.Name { + addGlobals(otherFile, globals) + } + p.candidates = append(p.candidates, collectImports(otherFile)...) + } + + // Resolve all the import paths we've seen to package names, and store + // f's imports by the identifier they introduce. + imports := collectImports(p.f) + if p.loadRealPackageNames { + err := p.loadPackageNames(ctx, append(imports, p.candidates...)) + if err != nil { + if p.logf != nil { + p.logf("loading package names: %v", err) + } + return nil, false + } + } + for _, imp := range imports { + p.existingImports[p.importIdentifier(imp)] = append(p.existingImports[p.importIdentifier(imp)], imp) + } + + // Find missing references. + for left, rights := range p.allRefs { + if globals[left] { + continue + } + _, ok := p.existingImports[left] + if !ok { + p.missingRefs[left] = rights + continue + } + } + if len(p.missingRefs) != 0 { + return nil, false + } + + return p.fix() +} + +// fix attempts to satisfy missing imports using p.candidates. If it finds +// everything, or if p.lastTry is true, it updates fixes to add the imports it found, +// delete anything unused, and update import names, and returns true. +func (p *pass) fix() ([]*ImportFix, bool) { + // Find missing imports. + var selected []*ImportInfo + for left, rights := range p.missingRefs { + if imp := p.findMissingImport(left, rights); imp != nil { + selected = append(selected, imp) + } + } + + if !p.lastTry && len(selected) != len(p.missingRefs) { + return nil, false + } + + // Found everything, or giving up. Add the new imports and remove any unused. + var fixes []*ImportFix + for _, identifierImports := range p.existingImports { + for _, imp := range identifierImports { + // We deliberately ignore globals here, because we can't be sure + // they're in the same package. People do things like put multiple + // main packages in the same directory, and we don't want to + // remove imports if they happen to have the same name as a var in + // a different package. + if _, ok := p.allRefs[p.importIdentifier(imp)]; !ok { + fixes = append(fixes, &ImportFix{ + StmtInfo: *imp, + IdentName: p.importIdentifier(imp), + FixType: DeleteImport, + }) + continue + } + + // An existing import may need to update its import name to be correct. + if name := p.importSpecName(imp); name != imp.Name { + fixes = append(fixes, &ImportFix{ + StmtInfo: ImportInfo{ + Name: name, + ImportPath: imp.ImportPath, + }, + IdentName: p.importIdentifier(imp), + FixType: SetImportName, + }) + } + } + } + // Collecting fixes involved map iteration, so sort for stability. See + // golang/go#59976. + sortFixes(fixes) + + // collect selected fixes in a separate slice, so that it can be sorted + // separately. Note that these fixes must occur after fixes to existing + // imports. TODO(rfindley): figure out why. + var selectedFixes []*ImportFix + for _, imp := range selected { + selectedFixes = append(selectedFixes, &ImportFix{ + StmtInfo: ImportInfo{ + Name: p.importSpecName(imp), + ImportPath: imp.ImportPath, + }, + IdentName: p.importIdentifier(imp), + FixType: AddImport, + }) + } + sortFixes(selectedFixes) + + return append(fixes, selectedFixes...), true +} + +func sortFixes(fixes []*ImportFix) { + sort.Slice(fixes, func(i, j int) bool { + fi, fj := fixes[i], fixes[j] + if fi.StmtInfo.ImportPath != fj.StmtInfo.ImportPath { + return fi.StmtInfo.ImportPath < fj.StmtInfo.ImportPath + } + if fi.StmtInfo.Name != fj.StmtInfo.Name { + return fi.StmtInfo.Name < fj.StmtInfo.Name + } + if fi.IdentName != fj.IdentName { + return fi.IdentName < fj.IdentName + } + return fi.FixType < fj.FixType + }) +} + +// importSpecName gets the import name of imp in the import spec. +// +// When the import identifier matches the assumed import name, the import name does +// not appear in the import spec. +func (p *pass) importSpecName(imp *ImportInfo) string { + // If we did not load the real package names, or the name is already set, + // we just return the existing name. + if !p.loadRealPackageNames || imp.Name != "" { + return imp.Name + } + + ident := p.importIdentifier(imp) + if ident == ImportPathToAssumedName(imp.ImportPath) { + return "" // ident not needed since the assumed and real names are the same. + } + return ident +} + +// apply will perform the fixes on f in order. +func apply(fset *token.FileSet, f *ast.File, fixes []*ImportFix) { + for _, fix := range fixes { + switch fix.FixType { + case DeleteImport: + astutil.DeleteNamedImport(fset, f, fix.StmtInfo.Name, fix.StmtInfo.ImportPath) + case AddImport: + astutil.AddNamedImport(fset, f, fix.StmtInfo.Name, fix.StmtInfo.ImportPath) + case SetImportName: + // Find the matching import path and change the name. + for _, spec := range f.Imports { + path := strings.Trim(spec.Path.Value, `"`) + if path == fix.StmtInfo.ImportPath { + spec.Name = &ast.Ident{ + Name: fix.StmtInfo.Name, + NamePos: spec.Pos(), + } + } + } + } + } +} + +// assumeSiblingImportsValid assumes that siblings' use of packages is valid, +// adding the exports they use. +func (p *pass) assumeSiblingImportsValid() { + for _, f := range p.otherFiles { + refs := collectReferences(f) + imports := collectImports(f) + importsByName := map[string]*ImportInfo{} + for _, imp := range imports { + importsByName[p.importIdentifier(imp)] = imp + } + for left, rights := range refs { + if imp, ok := importsByName[left]; ok { + if m, ok := stdlib.PackageSymbols[imp.ImportPath]; ok { + // We have the stdlib in memory; no need to guess. + rights = symbolNameSet(m) + } + // TODO(rfindley): we should set package name here, for consistency. + p.addCandidate(imp, &PackageInfo{ + // no name; we already know it. + Exports: rights, + }) + } + } + } +} + +// addCandidate adds a candidate import to p, and merges in the information +// in pkg. +func (p *pass) addCandidate(imp *ImportInfo, pkg *PackageInfo) { + p.candidates = append(p.candidates, imp) + if existing, ok := p.knownPackages[imp.ImportPath]; ok { + if existing.Name == "" { + existing.Name = pkg.Name + } + for export := range pkg.Exports { + existing.Exports[export] = true + } + } else { + p.knownPackages[imp.ImportPath] = pkg + } +} + +// fixImports adds and removes imports from f so that all its references are +// satisfied and there are no unused imports. +// +// This is declared as a variable rather than a function so goimports can +// easily be extended by adding a file with an init function. +// +// DO NOT REMOVE: used internally at Google. +var fixImports = fixImportsDefault + +func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) error { + fixes, err := getFixes(context.Background(), fset, f, filename, env) + if err != nil { + return err + } + apply(fset, f, fixes) + return nil +} + +// getFixes gets the import fixes that need to be made to f in order to fix the imports. +// It does not modify the ast. +func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) ([]*ImportFix, error) { + source, err := NewProcessEnvSource(env, filename, f.Name.Name) + if err != nil { + return nil, err + } + goEnv, err := env.goEnv() + if err != nil { + return nil, err + } + return getFixesWithSource(ctx, fset, f, filename, goEnv["GOROOT"], env.logf, source) +} + +func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, goroot string, logf func(string, ...any), source Source) ([]*ImportFix, error) { + // This logic is defensively duplicated from getFixes. + abs, err := filepath.Abs(filename) + if err != nil { + return nil, err + } + srcDir := filepath.Dir(abs) + + if logf != nil { + logf("fixImports(filename=%q), srcDir=%q ...", filename, srcDir) + } + + // First pass: looking only at f, and using the naive algorithm to + // derive package names from import paths, see if the file is already + // complete. We can't add any imports yet, because we don't know + // if missing references are actually package vars. + p := &pass{ + fset: fset, + f: f, + srcDir: srcDir, + logf: logf, + goroot: goroot, + source: source, + } + if fixes, done := p.load(ctx); done { + return fixes, nil + } + + otherFiles, err := parseOtherFiles(ctx, fset, srcDir, filename) + if err != nil { + return nil, err + } + + // Second pass: add information from other files in the same package, + // like their package vars and imports. + p.otherFiles = otherFiles + if fixes, done := p.load(ctx); done { + return fixes, nil + } + + // Now we can try adding imports from the stdlib. + p.assumeSiblingImportsValid() + addStdlibCandidates(p, p.missingRefs) + if fixes, done := p.fix(); done { + return fixes, nil + } + + // Third pass: get real package names where we had previously used + // the naive algorithm. + p = &pass{ + fset: fset, + f: f, + srcDir: srcDir, + logf: logf, + goroot: goroot, + source: p.source, // safe to reuse, as it's just a wrapper around env + } + p.loadRealPackageNames = true + p.otherFiles = otherFiles + if fixes, done := p.load(ctx); done { + return fixes, nil + } + + if err := addStdlibCandidates(p, p.missingRefs); err != nil { + return nil, err + } + p.assumeSiblingImportsValid() + if fixes, done := p.fix(); done { + return fixes, nil + } + + // Go look for candidates in $GOPATH, etc. We don't necessarily load + // the real exports of sibling imports, so keep assuming their contents. + if err := addExternalCandidates(ctx, p, p.missingRefs, filename); err != nil { + return nil, err + } + + p.lastTry = true + fixes, _ := p.fix() + return fixes, nil +} + +// MaxRelevance is the highest relevance, used for the standard library. +// Chosen arbitrarily to match pre-existing gopls code. +const MaxRelevance = 7.0 + +// getCandidatePkgs works with the passed callback to find all acceptable packages. +// It deduplicates by import path, and uses a cached stdlib rather than reading +// from disk. +func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filename, filePkg string, env *ProcessEnv) error { + notSelf := func(p *pkg) bool { + return p.packageName != filePkg || p.dir != filepath.Dir(filename) + } + goenv, err := env.goEnv() + if err != nil { + return err + } + + var mu sync.Mutex // to guard asynchronous access to dupCheck + dupCheck := map[string]struct{}{} + + // Start off with the standard library. + for importPath, symbols := range stdlib.PackageSymbols { + p := &pkg{ + dir: filepath.Join(goenv["GOROOT"], "src", importPath), + importPathShort: importPath, + packageName: path.Base(importPath), + relevance: MaxRelevance, + } + dupCheck[importPath] = struct{}{} + if notSelf(p) && wrappedCallback.dirFound(p) && wrappedCallback.packageNameLoaded(p) { + var exports []stdlib.Symbol + for _, sym := range symbols { + switch sym.Kind { + case stdlib.Func, stdlib.Type, stdlib.Var, stdlib.Const: + exports = append(exports, sym) + } + } + wrappedCallback.exportsLoaded(p, exports) + } + } + + scanFilter := &scanCallback{ + rootFound: func(root gopathwalk.Root) bool { + // Exclude goroot results -- getting them is relatively expensive, not cached, + // and generally redundant with the in-memory version. + return root.Type != gopathwalk.RootGOROOT && wrappedCallback.rootFound(root) + }, + dirFound: wrappedCallback.dirFound, + packageNameLoaded: func(pkg *pkg) bool { + mu.Lock() + defer mu.Unlock() + if _, ok := dupCheck[pkg.importPathShort]; ok { + return false + } + dupCheck[pkg.importPathShort] = struct{}{} + return notSelf(pkg) && wrappedCallback.packageNameLoaded(pkg) + }, + exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) { + // If we're an x_test, load the package under test's test variant. + if strings.HasSuffix(filePkg, "_test") && pkg.dir == filepath.Dir(filename) { + var err error + _, exports, err = loadExportsFromFiles(ctx, env, pkg.dir, true) + if err != nil { + return + } + } + wrappedCallback.exportsLoaded(pkg, exports) + }, + } + resolver, err := env.GetResolver() + if err != nil { + return err + } + return resolver.scan(ctx, scanFilter) +} + +func ScoreImportPaths(ctx context.Context, env *ProcessEnv, paths []string) (map[string]float64, error) { + result := make(map[string]float64) + resolver, err := env.GetResolver() + if err != nil { + return nil, err + } + for _, path := range paths { + result[path] = resolver.scoreImportPath(ctx, path) + } + return result, nil +} + +func PrimeCache(ctx context.Context, resolver Resolver) error { + // Fully scan the disk for directories, but don't actually read any Go files. + callback := &scanCallback{ + rootFound: func(root gopathwalk.Root) bool { + // See getCandidatePkgs: walking GOROOT is apparently expensive and + // unnecessary. + return root.Type != gopathwalk.RootGOROOT + }, + dirFound: func(pkg *pkg) bool { + return false + }, + // packageNameLoaded and exportsLoaded must never be called. + } + + return resolver.scan(ctx, callback) +} + +func candidateImportName(pkg *pkg) string { + if ImportPathToAssumedName(pkg.importPathShort) != pkg.packageName { + return pkg.packageName + } + return "" +} + +// GetAllCandidates calls wrapped for each package whose name starts with +// searchPrefix, and can be imported from filename with the package name filePkg. +// +// Beware that the wrapped function may be called multiple times concurrently. +// TODO(adonovan): encapsulate the concurrency. +func GetAllCandidates(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error { + callback := &scanCallback{ + rootFound: func(gopathwalk.Root) bool { + return true + }, + dirFound: func(pkg *pkg) bool { + if !CanUse(filename, pkg.dir) { + return false + } + // Try the assumed package name first, then a simpler path match + // in case of packages named vN, which are not uncommon. + return strings.HasPrefix(ImportPathToAssumedName(pkg.importPathShort), searchPrefix) || + strings.HasPrefix(path.Base(pkg.importPathShort), searchPrefix) + }, + packageNameLoaded: func(pkg *pkg) bool { + if !strings.HasPrefix(pkg.packageName, searchPrefix) { + return false + } + wrapped(ImportFix{ + StmtInfo: ImportInfo{ + ImportPath: pkg.importPathShort, + Name: candidateImportName(pkg), + }, + IdentName: pkg.packageName, + FixType: AddImport, + Relevance: pkg.relevance, + }) + return false + }, + } + return getCandidatePkgs(ctx, callback, filename, filePkg, env) +} + +// GetImportPaths calls wrapped for each package whose import path starts with +// searchPrefix, and can be imported from filename with the package name filePkg. +func GetImportPaths(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error { + callback := &scanCallback{ + rootFound: func(gopathwalk.Root) bool { + return true + }, + dirFound: func(pkg *pkg) bool { + if !CanUse(filename, pkg.dir) { + return false + } + return strings.HasPrefix(pkg.importPathShort, searchPrefix) + }, + packageNameLoaded: func(pkg *pkg) bool { + wrapped(ImportFix{ + StmtInfo: ImportInfo{ + ImportPath: pkg.importPathShort, + Name: candidateImportName(pkg), + }, + IdentName: pkg.packageName, + FixType: AddImport, + Relevance: pkg.relevance, + }) + return false + }, + } + return getCandidatePkgs(ctx, callback, filename, filePkg, env) +} + +// A PackageExport is a package and its exports. +type PackageExport struct { + Fix *ImportFix + Exports []stdlib.Symbol +} + +// GetPackageExports returns all known packages with name pkg and their exports. +func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchPkg, filename, filePkg string, env *ProcessEnv) error { + callback := &scanCallback{ + rootFound: func(gopathwalk.Root) bool { + return true + }, + dirFound: func(pkg *pkg) bool { + return pkgIsCandidate(filename, References{searchPkg: nil}, pkg) + }, + packageNameLoaded: func(pkg *pkg) bool { + return pkg.packageName == searchPkg + }, + exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) { + sortSymbols(exports) + wrapped(PackageExport{ + Fix: &ImportFix{ + StmtInfo: ImportInfo{ + ImportPath: pkg.importPathShort, + Name: candidateImportName(pkg), + }, + IdentName: pkg.packageName, + FixType: AddImport, + Relevance: pkg.relevance, + }, + Exports: exports, + }) + }, + } + return getCandidatePkgs(ctx, callback, filename, filePkg, env) +} + +// TODO(rfindley): we should depend on GOOS and GOARCH, to provide accurate +// imports when doing cross-platform development. +var requiredGoEnvVars = []string{ + "GO111MODULE", + "GOFLAGS", + "GOINSECURE", + "GOMOD", + "GOMODCACHE", + "GONOPROXY", + "GONOSUMDB", + "GOPATH", + "GOPROXY", + "GOROOT", + "GOSUMDB", + "GOWORK", +} + +// ProcessEnv contains environment variables and settings that affect the use of +// the go command, the go/build package, etc. +// +// ...a ProcessEnv *also* overwrites its Env along with derived state in the +// form of the resolver. And because it is lazily initialized, an env may just +// be broken and unusable, but there is no way for the caller to detect that: +// all queries will just fail. +// +// TODO(rfindley): refactor this package so that this type (perhaps renamed to +// just Env or Config) is an immutable configuration struct, to be exchanged +// for an initialized object via a constructor that returns an error. Perhaps +// the signature should be `func NewResolver(*Env) (*Resolver, error)`, where +// resolver is a concrete type used for resolving imports. Via this +// refactoring, we can avoid the need to call ProcessEnv.init and +// ProcessEnv.GoEnv everywhere, and implicitly fix all the places where this +// these are misused. Also, we'd delegate the caller the decision of how to +// handle a broken environment. +type ProcessEnv struct { + GocmdRunner *gocommand.Runner + + BuildFlags []string + ModFlag string + + // SkipPathInScan returns true if the path should be skipped from scans of + // the RootCurrentModule root type. The function argument is a clean, + // absolute path. + SkipPathInScan func(string) bool + + // Env overrides the OS environment, and can be used to specify + // GOPROXY, GO111MODULE, etc. PATH cannot be set here, because + // exec.Command will not honor it. + // Specifying all of requiredGoEnvVars avoids a call to `go env`. + Env map[string]string + + WorkingDir string + + // If Logf is non-nil, debug logging is enabled through this function. + Logf func(format string, args ...any) + + // If set, ModCache holds a shared cache of directory info to use across + // multiple ProcessEnvs. + ModCache *DirInfoCache + + initialized bool // see TODO above + + // resolver and resolverErr are lazily evaluated (see GetResolver). + // This is unclean, but see the big TODO in the docstring for ProcessEnv + // above: for now, we can't be sure that the ProcessEnv is fully initialized. + resolver Resolver + resolverErr error +} + +func (e *ProcessEnv) goEnv() (map[string]string, error) { + if err := e.init(); err != nil { + return nil, err + } + return e.Env, nil +} + +func (e *ProcessEnv) matchFile(dir, name string) (bool, error) { + bctx, err := e.buildContext() + if err != nil { + return false, err + } + return bctx.MatchFile(dir, name) +} + +// CopyConfig copies the env's configuration into a new env. +func (e *ProcessEnv) CopyConfig() *ProcessEnv { + copy := &ProcessEnv{ + GocmdRunner: e.GocmdRunner, + initialized: e.initialized, + BuildFlags: e.BuildFlags, + Logf: e.Logf, + WorkingDir: e.WorkingDir, + resolver: nil, + Env: map[string]string{}, + } + maps.Copy(copy.Env, e.Env) + return copy +} + +func (e *ProcessEnv) init() error { + if e.initialized { + return nil + } + + foundAllRequired := true + for _, k := range requiredGoEnvVars { + if _, ok := e.Env[k]; !ok { + foundAllRequired = false + break + } + } + if foundAllRequired { + e.initialized = true + return nil + } + + if e.Env == nil { + e.Env = map[string]string{} + } + + goEnv := map[string]string{} + stdout, err := e.invokeGo(context.TODO(), "env", append([]string{"-json"}, requiredGoEnvVars...)...) + if err != nil { + return err + } + if err := json.Unmarshal(stdout.Bytes(), &goEnv); err != nil { + return err + } + maps.Copy(e.Env, goEnv) + e.initialized = true + return nil +} + +func (e *ProcessEnv) env() []string { + var env []string // the gocommand package will prepend os.Environ. + for k, v := range e.Env { + env = append(env, k+"="+v) + } + return env +} + +func (e *ProcessEnv) GetResolver() (Resolver, error) { + if err := e.init(); err != nil { + return nil, err + } + + if e.resolver == nil && e.resolverErr == nil { + // TODO(rfindley): we should only use a gopathResolver here if the working + // directory is actually *in* GOPATH. (I seem to recall an open gopls issue + // for this behavior, but I can't find it). + // + // For gopls, we can optionally explicitly choose a resolver type, since we + // already know the view type. + if e.Env["GOMOD"] == "" && (e.Env["GOWORK"] == "" || e.Env["GOWORK"] == "off") { + e.resolver = newGopathResolver(e) + e.logf("created gopath resolver") + } else if r, err := newModuleResolver(e, e.ModCache); err != nil { + e.resolverErr = err + e.logf("failed to create module resolver: %v", err) + } else { + e.resolver = Resolver(r) + e.logf("created module resolver") + } + } + + return e.resolver, e.resolverErr +} + +// logf logs if e.Logf is non-nil. +func (e *ProcessEnv) logf(format string, args ...any) { + if e.Logf != nil { + e.Logf(format, args...) + } +} + +// buildContext returns the build.Context to use for matching files. +// +// TODO(rfindley): support dynamic GOOS, GOARCH here, when doing cross-platform +// development. +func (e *ProcessEnv) buildContext() (*build.Context, error) { + ctx := build.Default + goenv, err := e.goEnv() + if err != nil { + return nil, err + } + ctx.GOROOT = goenv["GOROOT"] + ctx.GOPATH = goenv["GOPATH"] + + // As of Go 1.14, build.Context has a Dir field + // (see golang.org/issue/34860). + // Populate it only if present. + rc := reflect.ValueOf(&ctx).Elem() + dir := rc.FieldByName("Dir") + if dir.IsValid() && dir.Kind() == reflect.String { + dir.SetString(e.WorkingDir) + } + + // Since Go 1.11, go/build.Context.Import may invoke 'go list' depending on + // the value in GO111MODULE in the process's environment. We always want to + // run in GOPATH mode when calling Import, so we need to prevent this from + // happening. In Go 1.16, GO111MODULE defaults to "on", so this problem comes + // up more frequently. + // + // HACK: setting any of the Context I/O hooks prevents Import from invoking + // 'go list', regardless of GO111MODULE. This is undocumented, but it's + // unlikely to change before GOPATH support is removed. + ctx.ReadDir = ioutil.ReadDir + + return &ctx, nil +} + +func (e *ProcessEnv) invokeGo(ctx context.Context, verb string, args ...string) (*bytes.Buffer, error) { + inv := gocommand.Invocation{ + Verb: verb, + Args: args, + BuildFlags: e.BuildFlags, + Env: e.env(), + Logf: e.Logf, + WorkingDir: e.WorkingDir, + } + return e.GocmdRunner.Run(ctx, inv) +} + +func addStdlibCandidates(pass *pass, refs References) error { + localbase := func(nm string) string { + ans := path.Base(nm) + if ans[0] == 'v' { + // this is called, for instance, with math/rand/v2 and returns rand/v2 + if _, err := strconv.Atoi(ans[1:]); err == nil { + ix := strings.LastIndex(nm, ans) + more := path.Base(nm[:ix]) + ans = path.Join(more, ans) + } + } + return ans + } + add := func(pkg string) { + // Prevent self-imports. + if path.Base(pkg) == pass.f.Name.Name && filepath.Join(pass.goroot, "src", pkg) == pass.srcDir { + return + } + exports := symbolNameSet(stdlib.PackageSymbols[pkg]) + pass.addCandidate( + &ImportInfo{ImportPath: pkg}, + &PackageInfo{Name: localbase(pkg), Exports: exports}) + } + for left := range refs { + if left == "rand" { + // Make sure we try crypto/rand before any version of math/rand as both have Int() + // and our policy is to recommend crypto + add("crypto/rand") + // if the user's no later than go1.21, this should be "math/rand" + // but we have no way of figuring out what the user is using + // TODO: investigate using the toolchain version to disambiguate in the stdlib + add("math/rand/v2") + // math/rand has an overlapping API + // TestIssue66407 fails without this + add("math/rand") + continue + } + for importPath := range stdlib.PackageSymbols { + if path.Base(importPath) == left { + add(importPath) + } + } + } + return nil +} + +// A Resolver does the build-system-specific parts of goimports. +type Resolver interface { + // loadPackageNames loads the package names in importPaths. + loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) + + // scan works with callback to search for packages. See scanCallback for details. + scan(ctx context.Context, callback *scanCallback) error + + // loadExports returns the package name and set of exported symbols in the + // package at dir. loadExports may be called concurrently. + loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) + + // scoreImportPath returns the relevance for an import path. + scoreImportPath(ctx context.Context, path string) float64 + + // ClearForNewScan returns a new Resolver based on the receiver that has + // cleared its internal caches of directory contents. + // + // The new resolver should be primed and then set via + // [ProcessEnv.UpdateResolver]. + ClearForNewScan() Resolver +} + +// A scanCallback controls a call to scan and receives its results. +// In general, minor errors will be silently discarded; a user should not +// expect to receive a full series of calls for everything. +type scanCallback struct { + // rootFound is called before scanning a new root dir. If it returns true, + // the root will be scanned. Returning false will not necessarily prevent + // directories from that root making it to dirFound. + rootFound func(gopathwalk.Root) bool + // dirFound is called when a directory is found that is possibly a Go package. + // pkg will be populated with everything except packageName. + // If it returns true, the package's name will be loaded. + dirFound func(pkg *pkg) bool + // packageNameLoaded is called when a package is found and its name is loaded. + // If it returns true, the package's exports will be loaded. + packageNameLoaded func(pkg *pkg) bool + // exportsLoaded is called when a package's exports have been loaded. + exportsLoaded func(pkg *pkg, exports []stdlib.Symbol) +} + +func addExternalCandidates(ctx context.Context, pass *pass, refs References, filename string) error { + ctx, done := event.Start(ctx, "imports.addExternalCandidates") + defer done() + + results, err := pass.source.ResolveReferences(ctx, filename, refs) + if err != nil { + return err + } + + for _, result := range results { + if result == nil { + continue + } + // Don't offer completions that would shadow predeclared + // names, such as github.com/coreos/etcd/error. + if types.Universe.Lookup(result.Package.Name) != nil { // predeclared + // Ideally we would skip this candidate only + // if the predeclared name is actually + // referenced by the file, but that's a lot + // trickier to compute and would still create + // an import that is likely to surprise the + // user before long. + continue + } + pass.addCandidate(result.Import, result.Package) + } + return nil +} + +// notIdentifier reports whether ch is an invalid identifier character. +func notIdentifier(ch rune) bool { + return !('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || + '0' <= ch && ch <= '9' || + ch == '_' || + ch >= utf8.RuneSelf && (unicode.IsLetter(ch) || unicode.IsDigit(ch))) +} + +// ImportPathToAssumedName returns the assumed package name of an import path. +// It does this using only string parsing of the import path. +// It picks the last element of the path that does not look like a major +// version, and then picks the valid identifier off the start of that element. +// It is used to determine if a local rename should be added to an import for +// clarity. +// This function could be moved to a standard package and exported if we want +// for use in other tools. +func ImportPathToAssumedName(importPath string) string { + base := path.Base(importPath) + if strings.HasPrefix(base, "v") { + if _, err := strconv.Atoi(base[1:]); err == nil { + dir := path.Dir(importPath) + if dir != "." { + base = path.Base(dir) + } + } + } + base = strings.TrimPrefix(base, "go-") + if i := strings.IndexFunc(base, notIdentifier); i >= 0 { + base = base[:i] + } + return base +} + +// gopathResolver implements resolver for GOPATH workspaces. +type gopathResolver struct { + env *ProcessEnv + walked bool + cache *DirInfoCache + scanSema chan struct{} // scanSema prevents concurrent scans. +} + +func newGopathResolver(env *ProcessEnv) *gopathResolver { + r := &gopathResolver{ + env: env, + cache: NewDirInfoCache(), + scanSema: make(chan struct{}, 1), + } + r.scanSema <- struct{}{} + return r +} + +func (r *gopathResolver) ClearForNewScan() Resolver { + return newGopathResolver(r.env) +} + +func (r *gopathResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) { + names := map[string]string{} + bctx, err := r.env.buildContext() + if err != nil { + return nil, err + } + for _, path := range importPaths { + names[path] = importPathToName(bctx, path, srcDir) + } + return names, nil +} + +// importPathToName finds out the actual package name, as declared in its .go files. +func importPathToName(bctx *build.Context, importPath, srcDir string) string { + // Fast path for standard library without going to disk. + if stdlib.HasPackage(importPath) { + return path.Base(importPath) // stdlib packages always match their paths. + } + + buildPkg, err := bctx.Import(importPath, srcDir, build.FindOnly) + if err != nil { + return "" + } + pkgName, err := packageDirToName(buildPkg.Dir) + if err != nil { + return "" + } + return pkgName +} + +// packageDirToName is a faster version of build.Import if +// the only thing desired is the package name. Given a directory, +// packageDirToName then only parses one file in the package, +// trusting that the files in the directory are consistent. +func packageDirToName(dir string) (packageName string, err error) { + d, err := os.Open(dir) + if err != nil { + return "", err + } + names, err := d.Readdirnames(-1) + d.Close() + if err != nil { + return "", err + } + sort.Strings(names) // to have predictable behavior + var lastErr error + var nfile int + for _, name := range names { + if !strings.HasSuffix(name, ".go") { + continue + } + if strings.HasSuffix(name, "_test.go") { + continue + } + nfile++ + fullFile := filepath.Join(dir, name) + + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, fullFile, nil, parser.PackageClauseOnly) + if err != nil { + lastErr = err + continue + } + pkgName := f.Name.Name + if pkgName == "documentation" { + // Special case from go/build.ImportDir, not + // handled by ctx.MatchFile. + continue + } + if pkgName == "main" { + // Also skip package main, assuming it's a +build ignore generator or example. + // Since you can't import a package main anyway, there's no harm here. + continue + } + return pkgName, nil + } + if lastErr != nil { + return "", lastErr + } + return "", fmt.Errorf("no importable package found in %d Go files", nfile) +} + +type pkg struct { + dir string // absolute file path to pkg directory ("/usr/lib/go/src/net/http") + importPathShort string // vendorless import path ("net/http", "a/b") + packageName string // package name loaded from source if requested + relevance float64 // a weakly-defined score of how relevant a package is. 0 is most relevant. +} + +type pkgDistance struct { + pkg *pkg + distance int // relative distance to target +} + +// byDistanceOrImportPathShortLength sorts by relative distance breaking ties +// on the short import path length and then the import string itself. +type byDistanceOrImportPathShortLength []pkgDistance + +func (s byDistanceOrImportPathShortLength) Len() int { return len(s) } +func (s byDistanceOrImportPathShortLength) Less(i, j int) bool { + di, dj := s[i].distance, s[j].distance + if di == -1 { + return false + } + if dj == -1 { + return true + } + if di != dj { + return di < dj + } + + vi, vj := s[i].pkg.importPathShort, s[j].pkg.importPathShort + if len(vi) != len(vj) { + return len(vi) < len(vj) + } + return vi < vj +} +func (s byDistanceOrImportPathShortLength) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +func distance(basepath, targetpath string) int { + p, err := filepath.Rel(basepath, targetpath) + if err != nil { + return -1 + } + if p == "." { + return 0 + } + return strings.Count(p, string(filepath.Separator)) + 1 +} + +func (r *gopathResolver) scan(ctx context.Context, callback *scanCallback) error { + add := func(root gopathwalk.Root, dir string) { + // We assume cached directories have not changed. We can skip them and their + // children. + if _, ok := r.cache.Load(dir); ok { + return + } + + importpath := filepath.ToSlash(dir[len(root.Path)+len("/"):]) + info := directoryPackageInfo{ + status: directoryScanned, + dir: dir, + rootType: root.Type, + nonCanonicalImportPath: VendorlessPath(importpath), + } + r.cache.Store(dir, info) + } + processDir := func(info directoryPackageInfo) { + // Skip this directory if we were not able to get the package information successfully. + if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil { + return + } + + p := &pkg{ + importPathShort: info.nonCanonicalImportPath, + dir: info.dir, + relevance: MaxRelevance - 1, + } + if info.rootType == gopathwalk.RootGOROOT { + p.relevance = MaxRelevance + } + + if !callback.dirFound(p) { + return + } + var err error + p.packageName, err = r.cache.CachePackageName(info) + if err != nil { + return + } + + if !callback.packageNameLoaded(p) { + return + } + if _, exports, err := r.loadExports(ctx, p, false); err == nil { + callback.exportsLoaded(p, exports) + } + } + stop := r.cache.ScanAndListen(ctx, processDir) + defer stop() + + goenv, err := r.env.goEnv() + if err != nil { + return err + } + var roots []gopathwalk.Root + roots = append(roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "src"), Type: gopathwalk.RootGOROOT}) + for _, p := range filepath.SplitList(goenv["GOPATH"]) { + roots = append(roots, gopathwalk.Root{Path: filepath.Join(p, "src"), Type: gopathwalk.RootGOPATH}) + } + // The callback is not necessarily safe to use in the goroutine below. Process roots eagerly. + roots = filterRoots(roots, callback.rootFound) + // We can't cancel walks, because we need them to finish to have a usable + // cache. Instead, run them in a separate goroutine and detach. + scanDone := make(chan struct{}) + go func() { + select { + case <-ctx.Done(): + return + case <-r.scanSema: + } + defer func() { r.scanSema <- struct{}{} }() + gopathwalk.Walk(roots, add, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: false}) + close(scanDone) + }() + select { + case <-ctx.Done(): + case <-scanDone: + } + return nil +} + +func (r *gopathResolver) scoreImportPath(ctx context.Context, path string) float64 { + if stdlib.HasPackage(path) { + return MaxRelevance + } + return MaxRelevance - 1 +} + +func filterRoots(roots []gopathwalk.Root, include func(gopathwalk.Root) bool) []gopathwalk.Root { + var result []gopathwalk.Root + for _, root := range roots { + if !include(root) { + continue + } + result = append(result, root) + } + return result +} + +func (r *gopathResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) { + if info, ok := r.cache.Load(pkg.dir); ok && !includeTest { + return r.cache.CacheExports(ctx, r.env, info) + } + return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest) +} + +// VendorlessPath returns the devendorized version of the import path ipath. +// For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b". +func VendorlessPath(ipath string) string { + // Devendorize for use in import statement. + if i := strings.LastIndex(ipath, "/vendor/"); i >= 0 { + return ipath[i+len("/vendor/"):] + } + if strings.HasPrefix(ipath, "vendor/") { + return ipath[len("vendor/"):] + } + return ipath +} + +func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, includeTest bool) (string, []stdlib.Symbol, error) { + // Look for non-test, buildable .go files which could provide exports. + all, err := os.ReadDir(dir) + if err != nil { + return "", nil, err + } + var files []fs.DirEntry + for _, fi := range all { + name := fi.Name() + if !strings.HasSuffix(name, ".go") || (!includeTest && strings.HasSuffix(name, "_test.go")) { + continue + } + match, err := env.matchFile(dir, fi.Name()) + if err != nil || !match { + continue + } + files = append(files, fi) + } + + if len(files) == 0 { + return "", nil, fmt.Errorf("dir %v contains no buildable, non-test .go files", dir) + } + + var pkgName string + var exports []stdlib.Symbol + fset := token.NewFileSet() + for _, fi := range files { + select { + case <-ctx.Done(): + return "", nil, ctx.Err() + default: + } + + fullFile := filepath.Join(dir, fi.Name()) + // Legacy ast.Object resolution is needed here. + f, err := parser.ParseFile(fset, fullFile, nil, 0) + if err != nil { + env.logf("error parsing %v: %v", fullFile, err) + continue + } + if f.Name.Name == "documentation" { + // Special case from go/build.ImportDir, not + // handled by MatchFile above. + continue + } + if includeTest && strings.HasSuffix(f.Name.Name, "_test") { + // x_test package. We want internal test files only. + continue + } + pkgName = f.Name.Name + for name, obj := range f.Scope.Objects { + if ast.IsExported(name) { + var kind stdlib.Kind + switch obj.Kind { + case ast.Con: + kind = stdlib.Const + case ast.Typ: + kind = stdlib.Type + case ast.Var: + kind = stdlib.Var + case ast.Fun: + kind = stdlib.Func + } + exports = append(exports, stdlib.Symbol{ + Name: name, + Kind: kind, + Version: 0, // unknown; be permissive + }) + } + } + } + sortSymbols(exports) + + env.logf("loaded exports in dir %v (package %v): %v", dir, pkgName, exports) + return pkgName, exports, nil +} + +func sortSymbols(syms []stdlib.Symbol) { + sort.Slice(syms, func(i, j int) bool { + return syms[i].Name < syms[j].Name + }) +} + +// A symbolSearcher searches for a package with a set of symbols, among a set +// of candidates. See [symbolSearcher.search]. +// +// The search occurs within the scope of a single file, with context captured +// in srcDir and xtest. +type symbolSearcher struct { + logf func(string, ...any) + srcDir string // directory containing the file + xtest bool // if set, the file containing is an x_test file + loadExports func(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) +} + +// search searches the provided candidates for a package containing all +// exported symbols. +// +// If successful, returns the resulting package. +func (s *symbolSearcher) search(ctx context.Context, candidates []pkgDistance, pkgName string, symbols map[string]bool) (*pkg, error) { + // Sort the candidates by their import package length, + // assuming that shorter package names are better than long + // ones. Note that this sorts by the de-vendored name, so + // there's no "penalty" for vendoring. + sort.Sort(byDistanceOrImportPathShortLength(candidates)) + if s.logf != nil { + for i, c := range candidates { + s.logf("%s candidate %d/%d: %v in %v", pkgName, i+1, len(candidates), c.pkg.importPathShort, c.pkg.dir) + } + } + + // Arrange rescv so that we can we can await results in order of relevance + // and exit as soon as we find the first match. + // + // Search with bounded concurrency, returning as soon as the first result + // among rescv is non-nil. + rescv := make([]chan *pkg, len(candidates)) + for i := range candidates { + rescv[i] = make(chan *pkg, 1) + } + const maxConcurrentPackageImport = 4 + loadExportsSem := make(chan struct{}, maxConcurrentPackageImport) + + // Ensure that all work is completed at exit. + ctx, cancel := context.WithCancel(ctx) + var wg sync.WaitGroup + defer func() { + cancel() + wg.Wait() + }() + + // Start the search. + wg.Add(1) + go func() { + defer wg.Done() + for i, c := range candidates { + select { + case loadExportsSem <- struct{}{}: + case <-ctx.Done(): + return + } + + i := i + c := c + wg.Add(1) + go func() { + defer func() { + <-loadExportsSem + wg.Done() + }() + if s.logf != nil { + s.logf("loading exports in dir %s (seeking package %s)", c.pkg.dir, pkgName) + } + pkg, err := s.searchOne(ctx, c, symbols) + if err != nil { + if s.logf != nil && ctx.Err() == nil { + s.logf("loading exports in dir %s (seeking package %s): %v", c.pkg.dir, pkgName, err) + } + pkg = nil + } + rescv[i] <- pkg // may be nil + }() + } + }() + + // Await the first (best) result. + for _, resc := range rescv { + select { + case r := <-resc: + if r != nil { + return r, nil + } + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return nil, nil +} + +func (s *symbolSearcher) searchOne(ctx context.Context, c pkgDistance, symbols map[string]bool) (*pkg, error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + // If we're considering the package under test from an x_test, load the + // test variant. + includeTest := s.xtest && c.pkg.dir == s.srcDir + _, exports, err := s.loadExports(ctx, c.pkg, includeTest) + if err != nil { + return nil, err + } + + exportsMap := make(map[string]bool, len(exports)) + for _, sym := range exports { + exportsMap[sym.Name] = true + } + for symbol := range symbols { + if !exportsMap[symbol] { + return nil, nil // no match + } + } + return c.pkg, nil +} + +// pkgIsCandidate reports whether pkg is a candidate for satisfying the +// finding which package pkgIdent in the file named by filename is trying +// to refer to. +// +// This check is purely lexical and is meant to be as fast as possible +// because it's run over all $GOPATH directories to filter out poor +// candidates in order to limit the CPU and I/O later parsing the +// exports in candidate packages. +// +// filename is the file being formatted. +// pkgIdent is the package being searched for, like "client" (if +// searching for "client.New") +func pkgIsCandidate(filename string, refs References, pkg *pkg) bool { + // Check "internal" and "vendor" visibility: + if !CanUse(filename, pkg.dir) { + return false + } + + // Speed optimization to minimize disk I/O: + // + // Use the matchesPath heuristic to filter to package paths that could + // reasonably match a dangling reference. + // + // This permits mismatch naming like directory "go-foo" being package "foo", + // or "pkg.v3" being "pkg", or directory + // "google.golang.org/api/cloudbilling/v1" being package "cloudbilling", but + // doesn't permit a directory "foo" to be package "bar", which is strongly + // discouraged anyway. There's no reason goimports needs to be slow just to + // accommodate that. + for pkgIdent := range refs { + if matchesPath(pkgIdent, pkg.importPathShort) { + return true + } + } + return false +} + +// CanUse reports whether the package in dir is usable from filename, +// respecting the Go "internal" and "vendor" visibility rules. +func CanUse(filename, dir string) bool { + // Fast path check, before any allocations. If it doesn't contain vendor + // or internal, it's not tricky: + // Note that this can false-negative on directories like "notinternal", + // but we check it correctly below. This is just a fast path. + if !strings.Contains(dir, "vendor") && !strings.Contains(dir, "internal") { + return true + } + + dirSlash := filepath.ToSlash(dir) + if !strings.Contains(dirSlash, "/vendor/") && !strings.Contains(dirSlash, "/internal/") && !strings.HasSuffix(dirSlash, "/internal") { + return true + } + // Vendor or internal directory only visible from children of parent. + // That means the path from the current directory to the target directory + // can contain ../vendor or ../internal but not ../foo/vendor or ../foo/internal + // or bar/vendor or bar/internal. + // After stripping all the leading ../, the only okay place to see vendor or internal + // is at the very beginning of the path. + absfile, err := filepath.Abs(filename) + if err != nil { + return false + } + absdir, err := filepath.Abs(dir) + if err != nil { + return false + } + rel, err := filepath.Rel(absfile, absdir) + if err != nil { + return false + } + relSlash := filepath.ToSlash(rel) + if i := strings.LastIndex(relSlash, "../"); i >= 0 { + relSlash = relSlash[i+len("../"):] + } + return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal") +} + +// matchesPath reports whether ident may match a potential package name +// referred to by path, using heuristics to filter out unidiomatic package +// names. +// +// Specifically, it checks whether either of the last two '/'- or '\'-delimited +// path segments matches the identifier. The segment-matching heuristic must +// allow for various conventions around segment naming, including go-foo, +// foo-go, and foo.v3. To handle all of these, matching considers both (1) the +// entire segment, ignoring '-' and '.', as well as (2) the last subsegment +// separated by '-' or '.'. So the segment foo-go matches all of the following +// identifiers: foo, go, and foogo. All matches are case insensitive (for ASCII +// identifiers). +// +// See the docstring for [pkgIsCandidate] for an explanation of how this +// heuristic filters potential candidate packages. +func matchesPath(ident, path string) bool { + // Ignore case, for ASCII. + lowerIfASCII := func(b byte) byte { + if 'A' <= b && b <= 'Z' { + return b + ('a' - 'A') + } + return b + } + + // match reports whether path[start:end] matches ident, ignoring [.-]. + match := func(start, end int) bool { + ii := len(ident) - 1 // current byte in ident + pi := end - 1 // current byte in path + for ; pi >= start && ii >= 0; pi-- { + pb := path[pi] + if pb == '-' || pb == '.' { + continue + } + pb = lowerIfASCII(pb) + ib := lowerIfASCII(ident[ii]) + if pb != ib { + return false + } + ii-- + } + return ii < 0 && pi < start // all bytes matched + } + + // segmentEnd and subsegmentEnd hold the end points of the current segment + // and subsegment intervals. + segmentEnd := len(path) + subsegmentEnd := len(path) + + // Count slashes; we only care about the last two segments. + nslash := 0 + + for i := len(path) - 1; i >= 0; i-- { + switch b := path[i]; b { + // TODO(rfindley): we handle backlashes here only because the previous + // heuristic handled backslashes. This is perhaps overly defensive, but is + // the result of many lessons regarding Chesterton's fence and the + // goimports codebase. + // + // However, this function is only ever called with something called an + // 'importPath'. Is it possible that this is a real import path, and + // therefore we need only consider forward slashes? + case '/', '\\': + if match(i+1, segmentEnd) || match(i+1, subsegmentEnd) { + return true + } + nslash++ + if nslash == 2 { + return false // did not match above + } + segmentEnd, subsegmentEnd = i, i // reset + case '-', '.': + if match(i+1, subsegmentEnd) { + return true + } + subsegmentEnd = i + } + } + return match(0, segmentEnd) || match(0, subsegmentEnd) +} + +type visitFn func(node ast.Node) ast.Visitor + +func (fn visitFn) Visit(node ast.Node) ast.Visitor { + return fn(node) +} + +func symbolNameSet(symbols []stdlib.Symbol) map[string]bool { + names := make(map[string]bool) + for _, sym := range symbols { + switch sym.Kind { + case stdlib.Const, stdlib.Var, stdlib.Type, stdlib.Func: + names[sym.Name] = true + } + } + return names +} diff --git a/vendor/golang.org/x/tools/internal/imports/imports.go b/vendor/golang.org/x/tools/internal/imports/imports.go new file mode 100644 index 000000000..2215a1288 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/imports.go @@ -0,0 +1,359 @@ +// Copyright 2013 The Go 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 imports implements a Go pretty-printer (like package "go/format") +// that also adds or removes import statements as necessary. +package imports + +import ( + "bufio" + "bytes" + "context" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/printer" + "go/token" + "io" + "regexp" + "strconv" + "strings" + + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/internal/event" +) + +// Options is golang.org/x/tools/imports.Options with extra internal-only options. +type Options struct { + Env *ProcessEnv // The environment to use. Note: this contains the cached module and filesystem state. + + // LocalPrefix is a comma-separated string of import path prefixes, which, if + // set, instructs Process to sort the import paths with the given prefixes + // into another group after 3rd-party packages. + LocalPrefix string + + Fragment bool // Accept fragment of a source file (no package statement) + AllErrors bool // Report all errors (not just the first 10 on different lines) + + Comments bool // Print comments (true if nil *Options provided) + TabIndent bool // Use tabs for indent (true if nil *Options provided) + TabWidth int // Tab width (8 if nil *Options provided) + + FormatOnly bool // Disable the insertion and deletion of imports +} + +// Process implements golang.org/x/tools/imports.Process with explicit context in opt.Env. +func Process(filename string, src []byte, opt *Options) (formatted []byte, err error) { + fileSet := token.NewFileSet() + var parserMode parser.Mode + if opt.Comments { + parserMode |= parser.ParseComments + } + if opt.AllErrors { + parserMode |= parser.AllErrors + } + file, adjust, err := parse(fileSet, filename, src, parserMode, opt.Fragment) + if err != nil { + return nil, err + } + + if !opt.FormatOnly { + if err := fixImports(fileSet, file, filename, opt.Env); err != nil { + return nil, err + } + } + return formatFile(fileSet, file, src, adjust, opt) +} + +// FixImports returns a list of fixes to the imports that, when applied, +// will leave the imports in the same state as Process. src and opt must +// be specified. +// +// Note that filename's directory influences which imports can be chosen, +// so it is important that filename be accurate. +func FixImports(ctx context.Context, filename string, src []byte, goroot string, logf func(string, ...any), source Source) (fixes []*ImportFix, err error) { + ctx, done := event.Start(ctx, "imports.FixImports") + defer done() + + fileSet := token.NewFileSet() + // TODO(rfindley): these default values for ParseComments and AllErrors were + // extracted from gopls, but are they even needed? + file, _, err := parse(fileSet, filename, src, parser.ParseComments|parser.AllErrors, true) + if err != nil { + return nil, err + } + + return getFixesWithSource(ctx, fileSet, file, filename, goroot, logf, source) +} + +// ApplyFixes applies all of the fixes to the file and formats it. extraMode +// is added in when parsing the file. src and opts must be specified, but no +// env is needed. +func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, extraMode parser.Mode) (formatted []byte, err error) { + // Don't use parse() -- we don't care about fragments or statement lists + // here, and we need to work with unparseable files. + fileSet := token.NewFileSet() + parserMode := parser.SkipObjectResolution + if opt.Comments { + parserMode |= parser.ParseComments + } + if opt.AllErrors { + parserMode |= parser.AllErrors + } + parserMode |= extraMode + + file, err := parser.ParseFile(fileSet, filename, src, parserMode) + if file == nil { + return nil, err + } + + // Apply the fixes to the file. + apply(fileSet, file, fixes) + + return formatFile(fileSet, file, src, nil, opt) +} + +// formatFile formats the file syntax tree. +// It may mutate the token.FileSet and the ast.File. +// +// If an adjust function is provided, it is called after formatting +// with the original source (formatFile's src parameter) and the +// formatted file, and returns the postpocessed result. +func formatFile(fset *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) { + mergeImports(file) + sortImports(opt.LocalPrefix, fset.File(file.FileStart), file) + var spacesBefore []string // import paths we need spaces before + for _, impSection := range astutil.Imports(fset, file) { + // Within each block of contiguous imports, see if any + // import lines are in different group numbers. If so, + // we'll need to put a space between them so it's + // compatible with gofmt. + lastGroup := -1 + for _, importSpec := range impSection { + importPath, _ := strconv.Unquote(importSpec.Path.Value) + groupNum := importGroup(opt.LocalPrefix, importPath) + if groupNum != lastGroup && lastGroup != -1 { + spacesBefore = append(spacesBefore, importPath) + } + lastGroup = groupNum + } + + } + + printerMode := printer.UseSpaces + if opt.TabIndent { + printerMode |= printer.TabIndent + } + printConfig := &printer.Config{Mode: printerMode, Tabwidth: opt.TabWidth} + + var buf bytes.Buffer + err := printConfig.Fprint(&buf, fset, file) + if err != nil { + return nil, err + } + out := buf.Bytes() + if adjust != nil { + out = adjust(src, out) + } + if len(spacesBefore) > 0 { + out, err = addImportSpaces(bytes.NewReader(out), spacesBefore) + if err != nil { + return nil, err + } + } + + out, err = format.Source(out) + if err != nil { + return nil, err + } + return out, nil +} + +// parse parses src, which was read from filename, +// as a Go source file or statement list. +func parse(fset *token.FileSet, filename string, src []byte, parserMode parser.Mode, fragment bool) (*ast.File, func(orig, src []byte) []byte, error) { + if parserMode&parser.SkipObjectResolution != 0 { + panic("legacy ast.Object resolution is required") + } + + // Try as whole source file. + file, err := parser.ParseFile(fset, filename, src, parserMode) + if err == nil { + return file, nil, nil + } + // If the error is that the source file didn't begin with a + // package line and we accept fragmented input, fall through to + // try as a source fragment. Stop and return on any other error. + if !fragment || !strings.Contains(err.Error(), "expected 'package'") { + return nil, nil, err + } + + // If this is a declaration list, make it a source file + // by inserting a package clause. + // Insert using a ;, not a newline, so that parse errors are on + // the correct line. + const prefix = "package main;" + psrc := append([]byte(prefix), src...) + file, err = parser.ParseFile(fset, filename, psrc, parserMode) + if err == nil { + // Gofmt will turn the ; into a \n. + // Do that ourselves now and update the file contents, + // so that positions and line numbers are correct going forward. + psrc[len(prefix)-1] = '\n' + fset.File(file.Package).SetLinesForContent(psrc) + + // If a main function exists, we will assume this is a main + // package and leave the file. + if containsMainFunc(file) { + return file, nil, nil + } + + adjust := func(orig, src []byte) []byte { + // Remove the package clause. + src = src[len(prefix):] + return matchSpace(orig, src) + } + return file, adjust, nil + } + // If the error is that the source file didn't begin with a + // declaration, fall through to try as a statement list. + // Stop and return on any other error. + if !strings.Contains(err.Error(), "expected declaration") { + return nil, nil, err + } + + // If this is a statement list, make it a source file + // by inserting a package clause and turning the list + // into a function body. This handles expressions too. + // Insert using a ;, not a newline, so that the line numbers + // in fsrc match the ones in src. + fsrc := append(append([]byte("package p; func _() {"), src...), '}') + file, err = parser.ParseFile(fset, filename, fsrc, parserMode) + if err == nil { + adjust := func(orig, src []byte) []byte { + // Remove the wrapping. + // Gofmt has turned the ; into a \n\n. + src = src[len("package p\n\nfunc _() {"):] + src = src[:len(src)-len("}\n")] + // Gofmt has also indented the function body one level. + // Remove that indent. + src = bytes.ReplaceAll(src, []byte("\n\t"), []byte("\n")) + return matchSpace(orig, src) + } + return file, adjust, nil + } + + // Failed, and out of options. + return nil, nil, err +} + +// containsMainFunc checks if a file contains a function declaration with the +// function signature 'func main()' +func containsMainFunc(file *ast.File) bool { + for _, decl := range file.Decls { + if f, ok := decl.(*ast.FuncDecl); ok { + if f.Name.Name != "main" { + continue + } + + if len(f.Type.Params.List) != 0 { + continue + } + + if f.Type.Results != nil && len(f.Type.Results.List) != 0 { + continue + } + + return true + } + } + + return false +} + +func cutSpace(b []byte) (before, middle, after []byte) { + i := 0 + for i < len(b) && (b[i] == ' ' || b[i] == '\t' || b[i] == '\n') { + i++ + } + j := len(b) + for j > 0 && (b[j-1] == ' ' || b[j-1] == '\t' || b[j-1] == '\n') { + j-- + } + if i <= j { + return b[:i], b[i:j], b[j:] + } + return nil, nil, b[j:] +} + +// matchSpace reformats src to use the same space context as orig. +// 1. If orig begins with blank lines, matchSpace inserts them at the beginning of src. +// 2. matchSpace copies the indentation of the first non-blank line in orig +// to every non-blank line in src. +// 3. matchSpace copies the trailing space from orig and uses it in place +// of src's trailing space. +func matchSpace(orig []byte, src []byte) []byte { + before, _, after := cutSpace(orig) + i := bytes.LastIndex(before, []byte{'\n'}) + before, indent := before[:i+1], before[i+1:] + + _, src, _ = cutSpace(src) + + var b bytes.Buffer + b.Write(before) + for len(src) > 0 { + line := src + if i := bytes.IndexByte(line, '\n'); i >= 0 { + line, src = line[:i+1], line[i+1:] + } else { + src = nil + } + if len(line) > 0 && line[0] != '\n' { // not blank + b.Write(indent) + } + b.Write(line) + } + b.Write(after) + return b.Bytes() +} + +var impLine = regexp.MustCompile(`^\s+(?:[\w\.]+\s+)?"(.+?)"`) + +func addImportSpaces(r io.Reader, breaks []string) ([]byte, error) { + var out bytes.Buffer + in := bufio.NewReader(r) + inImports := false + done := false + for { + s, err := in.ReadString('\n') + if err == io.EOF { + break + } else if err != nil { + return nil, err + } + + if !inImports && !done && strings.HasPrefix(s, "import") { + inImports = true + } + if inImports && (strings.HasPrefix(s, "var") || + strings.HasPrefix(s, "func") || + strings.HasPrefix(s, "const") || + strings.HasPrefix(s, "type")) { + done = true + inImports = false + } + if inImports && len(breaks) > 0 { + if m := impLine.FindStringSubmatch(s); m != nil { + if m[1] == breaks[0] { + out.WriteByte('\n') + breaks = breaks[1:] + } + } + } + + fmt.Fprint(&out, s) + } + return out.Bytes(), nil +} diff --git a/vendor/golang.org/x/tools/internal/imports/mod.go b/vendor/golang.org/x/tools/internal/imports/mod.go new file mode 100644 index 000000000..df94ec818 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/mod.go @@ -0,0 +1,841 @@ +// Copyright 2019 The Go 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 imports + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "path" + "path/filepath" + "regexp" + "slices" + "sort" + "strconv" + "strings" + + "golang.org/x/mod/module" + "golang.org/x/tools/internal/event" + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" +) + +// Notes(rfindley): ModuleResolver appears to be heavily optimized for scanning +// as fast as possible, which is desirable for a call to goimports from the +// command line, but it doesn't work as well for gopls, where it suffers from +// slow startup (golang/go#44863) and intermittent hanging (golang/go#59216), +// both caused by populating the cache, albeit in slightly different ways. +// +// A high level list of TODOs: +// - Optimize the scan itself, as there is some redundancy statting and +// reading go.mod files. +// - Invert the relationship between ProcessEnv and Resolver (see the +// docstring of ProcessEnv). +// - Make it easier to use an external resolver implementation. +// +// Smaller TODOs are annotated in the code below. + +// ModuleResolver implements the Resolver interface for a workspace using +// modules. +// +// A goal of the ModuleResolver is to invoke the Go command as little as +// possible. To this end, it runs the Go command only for listing module +// information (i.e. `go list -m -e -json ...`). Package scanning, the process +// of loading package information for the modules, is implemented internally +// via the scan method. +// +// It has two types of state: the state derived from the go command, which +// is populated by init, and the state derived from scans, which is populated +// via scan. A root is considered scanned if it has been walked to discover +// directories. However, if the scan did not require additional information +// from the directory (such as package name or exports), the directory +// information itself may be partially populated. It will be lazily filled in +// as needed by scans, using the scanCallback. +type ModuleResolver struct { + env *ProcessEnv + + // Module state, populated during construction + dummyVendorMod *gocommand.ModuleJSON // if vendoring is enabled, a pseudo-module to represent the /vendor directory + moduleCacheDir string // GOMODCACHE, inferred from GOPATH if unset + roots []gopathwalk.Root // roots to scan, in approximate order of importance + mains []*gocommand.ModuleJSON // main modules + mainByDir map[string]*gocommand.ModuleJSON // module information by dir, to join with roots + modsByModPath []*gocommand.ModuleJSON // all modules, ordered by # of path components in their module path + modsByDir []*gocommand.ModuleJSON // ...or by the number of path components in their Dir. + + // Scanning state, populated by scan + + // scanSema prevents concurrent scans, and guards scannedRoots and the cache + // fields below (though the caches themselves are concurrency safe). + // Receive to acquire, send to release. + scanSema chan struct{} + scannedRoots map[gopathwalk.Root]bool // if true, root has been walked + + // Caches of directory info, populated by scans and scan callbacks + // + // moduleCacheCache stores cached information about roots in the module + // cache, which are immutable and therefore do not need to be invalidated. + // + // otherCache stores information about all other roots (even GOROOT), which + // may change. + moduleCacheCache *DirInfoCache + otherCache *DirInfoCache +} + +// newModuleResolver returns a new module-aware goimports resolver. +// +// Note: use caution when modifying this constructor: changes must also be +// reflected in ModuleResolver.ClearForNewScan. +func newModuleResolver(e *ProcessEnv, moduleCacheCache *DirInfoCache) (*ModuleResolver, error) { + r := &ModuleResolver{ + env: e, + scanSema: make(chan struct{}, 1), + } + r.scanSema <- struct{}{} // release + + goenv, err := r.env.goEnv() + if err != nil { + return nil, err + } + + // TODO(rfindley): can we refactor to share logic with r.env.invokeGo? + inv := gocommand.Invocation{ + BuildFlags: r.env.BuildFlags, + ModFlag: r.env.ModFlag, + Env: r.env.env(), + Logf: r.env.Logf, + WorkingDir: r.env.WorkingDir, + } + + vendorEnabled := false + var mainModVendor *gocommand.ModuleJSON // for module vendoring + var mainModsVendor []*gocommand.ModuleJSON // for workspace vendoring + + goWork := r.env.Env["GOWORK"] + if len(goWork) == 0 { + // TODO(rfindley): VendorEnabled runs the go command to get GOFLAGS, but + // they should be available from the ProcessEnv. Can we avoid the redundant + // invocation? + vendorEnabled, mainModVendor, err = gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner) + if err != nil { + return nil, err + } + } else { + vendorEnabled, mainModsVendor, err = gocommand.WorkspaceVendorEnabled(context.Background(), inv, r.env.GocmdRunner) + if err != nil { + return nil, err + } + } + + if vendorEnabled { + if mainModVendor != nil { + // Module vendor mode is on, so all the non-Main modules are irrelevant, + // and we need to search /vendor for everything. + r.mains = []*gocommand.ModuleJSON{mainModVendor} + r.dummyVendorMod = &gocommand.ModuleJSON{ + Path: "", + Dir: filepath.Join(mainModVendor.Dir, "vendor"), + } + r.modsByModPath = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} + r.modsByDir = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} + } else { + // Workspace vendor mode is on, so all the non-Main modules are irrelevant, + // and we need to search /vendor for everything. + r.mains = mainModsVendor + r.dummyVendorMod = &gocommand.ModuleJSON{ + Path: "", + Dir: filepath.Join(filepath.Dir(goWork), "vendor"), + } + r.modsByModPath = append(slices.Clone(mainModsVendor), r.dummyVendorMod) + r.modsByDir = append(slices.Clone(mainModsVendor), r.dummyVendorMod) + } + } else { + // Vendor mode is off, so run go list -m ... to find everything. + err := r.initAllMods() + // We expect an error when running outside of a module with + // GO111MODULE=on. Other errors are fatal. + if err != nil { + if errMsg := err.Error(); !strings.Contains(errMsg, "working directory is not part of a module") && !strings.Contains(errMsg, "go.mod file not found") { + return nil, err + } + } + } + + r.moduleCacheDir = gomodcacheForEnv(goenv) + if r.moduleCacheDir == "" { + return nil, fmt.Errorf("cannot resolve GOMODCACHE") + } + + sort.Slice(r.modsByModPath, func(i, j int) bool { + count := func(x int) int { + return strings.Count(r.modsByModPath[x].Path, "/") + } + return count(j) < count(i) // descending order + }) + sort.Slice(r.modsByDir, func(i, j int) bool { + count := func(x int) int { + return strings.Count(r.modsByDir[x].Dir, string(filepath.Separator)) + } + return count(j) < count(i) // descending order + }) + + r.roots = []gopathwalk.Root{} + if goenv["GOROOT"] != "" { // "" happens in tests + r.roots = append(r.roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "/src"), Type: gopathwalk.RootGOROOT}) + } + r.mainByDir = make(map[string]*gocommand.ModuleJSON) + for _, main := range r.mains { + r.roots = append(r.roots, gopathwalk.Root{Path: main.Dir, Type: gopathwalk.RootCurrentModule}) + r.mainByDir[main.Dir] = main + } + if vendorEnabled { + r.roots = append(r.roots, gopathwalk.Root{Path: r.dummyVendorMod.Dir, Type: gopathwalk.RootOther}) + } else { + addDep := func(mod *gocommand.ModuleJSON) { + if mod.Replace == nil { + // This is redundant with the cache, but we'll skip it cheaply enough + // when we encounter it in the module cache scan. + // + // Including it at a lower index in r.roots than the module cache dir + // helps prioritize matches from within existing dependencies. + r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootModuleCache}) + } else { + r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootOther}) + } + } + // Walk dependent modules before scanning the full mod cache, direct deps first. + for _, mod := range r.modsByModPath { + if !mod.Indirect && !mod.Main { + addDep(mod) + } + } + for _, mod := range r.modsByModPath { + if mod.Indirect && !mod.Main { + addDep(mod) + } + } + // If provided, share the moduleCacheCache. + // + // TODO(rfindley): The module cache is immutable. However, the loaded + // exports do depend on GOOS and GOARCH. Fortunately, the + // ProcessEnv.buildContext does not adjust these from build.DefaultContext + // (even though it should). So for now, this is OK to share, but we need to + // add logic for handling GOOS/GOARCH. + r.moduleCacheCache = moduleCacheCache + r.roots = append(r.roots, gopathwalk.Root{Path: r.moduleCacheDir, Type: gopathwalk.RootModuleCache}) + } + + r.scannedRoots = map[gopathwalk.Root]bool{} + if r.moduleCacheCache == nil { + r.moduleCacheCache = NewDirInfoCache() + } + r.otherCache = NewDirInfoCache() + return r, nil +} + +// gomodcacheForEnv returns the GOMODCACHE value to use based on the given env +// map, which must have GOMODCACHE and GOPATH populated. +// +// TODO(rfindley): this is defensive refactoring. +// 1. Is this even relevant anymore? Can't we just read GOMODCACHE. +// 2. Use this to separate module cache scanning from other scanning. +func gomodcacheForEnv(goenv map[string]string) string { + if gmc := goenv["GOMODCACHE"]; gmc != "" { + // golang/go#67156: ensure that the module cache is clean, since it is + // assumed as a prefix to directories scanned by gopathwalk, which are + // themselves clean. + return filepath.Clean(gmc) + } + gopaths := filepath.SplitList(goenv["GOPATH"]) + if len(gopaths) == 0 { + return "" + } + return filepath.Join(gopaths[0], "/pkg/mod") +} + +func (r *ModuleResolver) initAllMods() error { + stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-e", "-json", "...") + if err != nil { + return err + } + for dec := json.NewDecoder(stdout); dec.More(); { + mod := &gocommand.ModuleJSON{} + if err := dec.Decode(mod); err != nil { + return err + } + if mod.Dir == "" { + r.env.logf("module %v has not been downloaded and will be ignored", mod.Path) + // Can't do anything with a module that's not downloaded. + continue + } + // golang/go#36193: the go command doesn't always clean paths. + mod.Dir = filepath.Clean(mod.Dir) + r.modsByModPath = append(r.modsByModPath, mod) + r.modsByDir = append(r.modsByDir, mod) + if mod.Main { + r.mains = append(r.mains, mod) + } + } + return nil +} + +// ClearForNewScan invalidates the last scan. +// +// It preserves the set of roots, but forgets about the set of directories. +// Though it forgets the set of module cache directories, it remembers their +// contents, since they are assumed to be immutable. +func (r *ModuleResolver) ClearForNewScan() Resolver { + <-r.scanSema // acquire r, to guard scannedRoots + r2 := &ModuleResolver{ + env: r.env, + dummyVendorMod: r.dummyVendorMod, + moduleCacheDir: r.moduleCacheDir, + roots: r.roots, + mains: r.mains, + mainByDir: r.mainByDir, + modsByModPath: r.modsByModPath, + + scanSema: make(chan struct{}, 1), + scannedRoots: make(map[gopathwalk.Root]bool), + otherCache: NewDirInfoCache(), + moduleCacheCache: r.moduleCacheCache, + } + r2.scanSema <- struct{}{} // r2 must start released + // Invalidate root scans. We don't need to invalidate module cache roots, + // because they are immutable. + // (We don't support a use case where GOMODCACHE is cleaned in the middle of + // e.g. a gopls session: the user must restart gopls to get accurate + // imports.) + // + // Scanning for new directories in GOMODCACHE should be handled elsewhere, + // via a call to ScanModuleCache. + for _, root := range r.roots { + if root.Type == gopathwalk.RootModuleCache && r.scannedRoots[root] { + r2.scannedRoots[root] = true + } + } + r.scanSema <- struct{}{} // release r + return r2 +} + +// ClearModuleInfo invalidates resolver state that depends on go.mod file +// contents (essentially, the output of go list -m -json ...). +// +// Notably, it does not forget directory contents, which are reset +// asynchronously via ClearForNewScan. +// +// If the ProcessEnv is a GOPATH environment, ClearModuleInfo is a no op. +// +// TODO(rfindley): move this to a new env.go, consolidating ProcessEnv methods. +func (e *ProcessEnv) ClearModuleInfo() { + if r, ok := e.resolver.(*ModuleResolver); ok { + resolver, err := newModuleResolver(e, e.ModCache) + if err != nil { + e.resolver = nil + e.resolverErr = err + return + } + + <-r.scanSema // acquire (guards caches) + resolver.moduleCacheCache = r.moduleCacheCache + resolver.otherCache = r.otherCache + r.scanSema <- struct{}{} // release + + e.UpdateResolver(resolver) + } +} + +// UpdateResolver sets the resolver for the ProcessEnv to use in imports +// operations. Only for use with the result of [Resolver.ClearForNewScan]. +// +// TODO(rfindley): this awkward API is a result of the (arguably) inverted +// relationship between configuration and state described in the doc comment +// for [ProcessEnv]. +func (e *ProcessEnv) UpdateResolver(r Resolver) { + e.resolver = r + e.resolverErr = nil +} + +// findPackage returns the module and directory from within the main modules +// and their dependencies that contains the package at the given import path, +// or returns nil, "" if no module is in scope. +func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) { + // This can't find packages in the stdlib, but that's harmless for all + // the existing code paths. + for _, m := range r.modsByModPath { + if !strings.HasPrefix(importPath, m.Path) { + continue + } + pathInModule := importPath[len(m.Path):] + pkgDir := filepath.Join(m.Dir, pathInModule) + if r.dirIsNestedModule(pkgDir, m) { + continue + } + + if info, ok := r.cacheLoad(pkgDir); ok { + if loaded, err := info.reachedStatus(nameLoaded); loaded { + if err != nil { + continue // No package in this dir. + } + return m, pkgDir + } + if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil { + continue // Dir is unreadable, etc. + } + // This is slightly wrong: a directory doesn't have to have an + // importable package to count as a package for package-to-module + // resolution. package main or _test files should count but + // don't. + // TODO(heschi): fix this. + if _, err := r.cachePackageName(info); err == nil { + return m, pkgDir + } + } + + // Not cached. Read the filesystem. + pkgFiles, err := os.ReadDir(pkgDir) + if err != nil { + continue + } + // A module only contains a package if it has buildable go + // files in that directory. If not, it could be provided by an + // outer module. See #29736. + for _, fi := range pkgFiles { + if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok { + return m, pkgDir + } + } + } + return nil, "" +} + +func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) { + if info, ok := r.moduleCacheCache.Load(dir); ok { + return info, ok + } + return r.otherCache.Load(dir) +} + +func (r *ModuleResolver) cacheStore(info directoryPackageInfo) { + if info.rootType == gopathwalk.RootModuleCache { + r.moduleCacheCache.Store(info.dir, info) + } else { + r.otherCache.Store(info.dir, info) + } +} + +// cachePackageName caches the package name for a dir already in the cache. +func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) { + if info.rootType == gopathwalk.RootModuleCache { + return r.moduleCacheCache.CachePackageName(info) + } + return r.otherCache.CachePackageName(info) +} + +func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) { + if info.rootType == gopathwalk.RootModuleCache { + return r.moduleCacheCache.CacheExports(ctx, env, info) + } + return r.otherCache.CacheExports(ctx, env, info) +} + +// findModuleByDir returns the module that contains dir, or nil if no such +// module is in scope. +func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON { + // This is quite tricky and may not be correct. dir could be: + // - a package in the main module. + // - a replace target underneath the main module's directory. + // - a nested module in the above. + // - a replace target somewhere totally random. + // - a nested module in the above. + // - in the mod cache. + // - in /vendor/ in -mod=vendor mode. + // - nested module? Dunno. + // Rumor has it that replace targets cannot contain other replace targets. + // + // Note that it is critical here that modsByDir is sorted to have deeper dirs + // first. This ensures that findModuleByDir finds the innermost module. + // See also golang/go#56291. + for _, m := range r.modsByDir { + if !strings.HasPrefix(dir, m.Dir) { + continue + } + + if r.dirIsNestedModule(dir, m) { + continue + } + + return m + } + return nil +} + +// dirIsNestedModule reports if dir is contained in a nested module underneath +// mod, not actually in mod. +func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool { + if !strings.HasPrefix(dir, mod.Dir) { + return false + } + if r.dirInModuleCache(dir) { + // Nested modules in the module cache are pruned, + // so it cannot be a nested module. + return false + } + if mod != nil && mod == r.dummyVendorMod { + // The /vendor pseudomodule is flattened and doesn't actually count. + return false + } + modDir, _ := r.modInfo(dir) + if modDir == "" { + return false + } + return modDir != mod.Dir +} + +func readModName(modFile string) string { + modBytes, err := os.ReadFile(modFile) + if err != nil { + return "" + } + return modulePath(modBytes) +} + +func (r *ModuleResolver) modInfo(dir string) (modDir, modName string) { + if r.dirInModuleCache(dir) { + if matches := modCacheRegexp.FindStringSubmatch(dir); len(matches) == 3 { + index := strings.Index(dir, matches[1]+"@"+matches[2]) + modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2]) + return modDir, readModName(filepath.Join(modDir, "go.mod")) + } + } + for { + if info, ok := r.cacheLoad(dir); ok { + return info.moduleDir, info.moduleName + } + f := filepath.Join(dir, "go.mod") + info, err := os.Stat(f) + if err == nil && !info.IsDir() { + return dir, readModName(f) + } + + d := filepath.Dir(dir) + if len(d) >= len(dir) { + return "", "" // reached top of file system, no go.mod + } + dir = d + } +} + +func (r *ModuleResolver) dirInModuleCache(dir string) bool { + if r.moduleCacheDir == "" { + return false + } + return strings.HasPrefix(dir, r.moduleCacheDir) +} + +func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) { + names := map[string]string{} + for _, path := range importPaths { + // TODO(rfindley): shouldn't this use the dirInfoCache? + _, packageDir := r.findPackage(path) + if packageDir == "" { + continue + } + name, err := packageDirToName(packageDir) + if err != nil { + continue + } + names[path] = name + } + return names, nil +} + +func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error { + ctx, done := event.Start(ctx, "imports.ModuleResolver.scan") + defer done() + + processDir := func(info directoryPackageInfo) { + // Skip this directory if we were not able to get the package information successfully. + if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil { + return + } + pkg, err := r.canonicalize(info) + if err != nil { + return + } + if !callback.dirFound(pkg) { + return + } + + pkg.packageName, err = r.cachePackageName(info) + if err != nil { + return + } + if !callback.packageNameLoaded(pkg) { + return + } + + _, exports, err := r.loadExports(ctx, pkg, false) + if err != nil { + return + } + callback.exportsLoaded(pkg, exports) + } + + // Start processing everything in the cache, and listen for the new stuff + // we discover in the walk below. + stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir) + defer stop1() + stop2 := r.otherCache.ScanAndListen(ctx, processDir) + defer stop2() + + // We assume cached directories are fully cached, including all their + // children, and have not changed. We can skip them. + skip := func(root gopathwalk.Root, dir string) bool { + if r.env.SkipPathInScan != nil && root.Type == gopathwalk.RootCurrentModule { + if root.Path == dir { + return false + } + + if r.env.SkipPathInScan(filepath.Clean(dir)) { + return true + } + } + + info, ok := r.cacheLoad(dir) + if !ok { + return false + } + // This directory can be skipped as long as we have already scanned it. + // Packages with errors will continue to have errors, so there is no need + // to rescan them. + packageScanned, _ := info.reachedStatus(directoryScanned) + return packageScanned + } + + add := func(root gopathwalk.Root, dir string) { + r.cacheStore(r.scanDirForPackage(root, dir)) + } + + // r.roots and the callback are not necessarily safe to use in the + // goroutine below. Process them eagerly. + roots := filterRoots(r.roots, callback.rootFound) + // We can't cancel walks, because we need them to finish to have a usable + // cache. Instead, run them in a separate goroutine and detach. + scanDone := make(chan struct{}) + go func() { + select { + case <-ctx.Done(): + return + case <-r.scanSema: // acquire + } + defer func() { r.scanSema <- struct{}{} }() // release + // We have the lock on r.scannedRoots, and no other scans can run. + for _, root := range roots { + if ctx.Err() != nil { + return + } + + if r.scannedRoots[root] { + continue + } + gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true}) + r.scannedRoots[root] = true + } + close(scanDone) + }() + select { + case <-ctx.Done(): + case <-scanDone: + } + return nil +} + +func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 { + if stdlib.HasPackage(path) { + return MaxRelevance + } + mod, _ := r.findPackage(path) + return modRelevance(mod) +} + +func modRelevance(mod *gocommand.ModuleJSON) float64 { + var relevance float64 + switch { + case mod == nil: // out of scope + return MaxRelevance - 4 + case mod.Indirect: + relevance = MaxRelevance - 3 + case !mod.Main: + relevance = MaxRelevance - 2 + default: + relevance = MaxRelevance - 1 // main module ties with stdlib + } + + _, versionString, ok := module.SplitPathVersion(mod.Path) + if ok { + index := strings.Index(versionString, "v") + if index == -1 { + return relevance + } + if versionNumber, err := strconv.ParseFloat(versionString[index+1:], 64); err == nil { + relevance += versionNumber / 1000 + } + } + + return relevance +} + +// canonicalize gets the result of canonicalizing the packages using the results +// of initializing the resolver from 'go list -m'. +func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) { + // Packages in GOROOT are already canonical, regardless of the std/cmd modules. + if info.rootType == gopathwalk.RootGOROOT { + return &pkg{ + importPathShort: info.nonCanonicalImportPath, + dir: info.dir, + packageName: path.Base(info.nonCanonicalImportPath), + relevance: MaxRelevance, + }, nil + } + + importPath := info.nonCanonicalImportPath + mod := r.findModuleByDir(info.dir) + // Check if the directory is underneath a module that's in scope. + if mod != nil { + // It is. If dir is the target of a replace directive, + // our guessed import path is wrong. Use the real one. + if mod.Dir == info.dir { + importPath = mod.Path + } else { + dirInMod := info.dir[len(mod.Dir)+len("/"):] + importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod)) + } + } else if !strings.HasPrefix(importPath, info.moduleName) { + // The module's name doesn't match the package's import path. It + // probably needs a replace directive we don't have. + return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir) + } + + res := &pkg{ + importPathShort: importPath, + dir: info.dir, + relevance: modRelevance(mod), + } + // We may have discovered a package that has a different version + // in scope already. Canonicalize to that one if possible. + if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" { + res.dir = canonicalDir + } + return res, nil +} + +func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) { + if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest { + return r.cacheExports(ctx, r.env, info) + } + return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest) +} + +func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo { + subdir := "" + if prefix := root.Path + string(filepath.Separator); strings.HasPrefix(dir, prefix) { + subdir = dir[len(prefix):] + } + importPath := filepath.ToSlash(subdir) + if strings.HasPrefix(importPath, "vendor/") { + // Only enter vendor directories if they're explicitly requested as a root. + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("unwanted vendor directory"), + } + } + switch root.Type { + case gopathwalk.RootCurrentModule: + importPath = path.Join(r.mainByDir[root.Path].Path, filepath.ToSlash(subdir)) + case gopathwalk.RootModuleCache: + matches := modCacheRegexp.FindStringSubmatch(subdir) + if len(matches) == 0 { + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("invalid module cache path: %v", subdir), + } + } + modPath, err := module.UnescapePath(filepath.ToSlash(matches[1])) + if err != nil { + r.env.logf("decoding module cache path %q: %v", subdir, err) + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("decoding module cache path %q: %v", subdir, err), + } + } + importPath = path.Join(modPath, filepath.ToSlash(matches[3])) + } + + modDir, modName := r.modInfo(dir) + result := directoryPackageInfo{ + status: directoryScanned, + dir: dir, + rootType: root.Type, + nonCanonicalImportPath: importPath, + moduleDir: modDir, + moduleName: modName, + } + if root.Type == gopathwalk.RootGOROOT { + // stdlib packages are always in scope, despite the confusing go.mod + return result + } + return result +} + +// modCacheRegexp splits a path in a module cache into module, module version, and package. +var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`) + +var ( + slashSlash = []byte("//") + moduleStr = []byte("module") +) + +// modulePath returns the module path from the gomod file text. +// If it cannot find a module path, it returns an empty string. +// It is tolerant of unrelated problems in the go.mod file. +// +// Copied from cmd/go/internal/modfile. +func modulePath(mod []byte) string { + for len(mod) > 0 { + line := mod + mod = nil + if i := bytes.IndexByte(line, '\n'); i >= 0 { + line, mod = line[:i], line[i+1:] + } + if i := bytes.Index(line, slashSlash); i >= 0 { + line = line[:i] + } + line = bytes.TrimSpace(line) + if !bytes.HasPrefix(line, moduleStr) { + continue + } + line = line[len(moduleStr):] + n := len(line) + line = bytes.TrimSpace(line) + if len(line) == n || len(line) == 0 { + continue + } + + if line[0] == '"' || line[0] == '`' { + p, err := strconv.Unquote(string(line)) + if err != nil { + return "" // malformed quoted string or multiline module path + } + return p + } + + return string(line) + } + return "" // missing module path +} diff --git a/vendor/golang.org/x/tools/internal/imports/mod_cache.go b/vendor/golang.org/x/tools/internal/imports/mod_cache.go new file mode 100644 index 000000000..b96c9d4bf --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/mod_cache.go @@ -0,0 +1,331 @@ +// Copyright 2019 The Go 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 imports + +import ( + "context" + "fmt" + "path" + "path/filepath" + "strings" + "sync" + + "golang.org/x/mod/module" + "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" +) + +// To find packages to import, the resolver needs to know about all of +// the packages that could be imported. This includes packages that are +// already in modules that are in (1) the current module, (2) replace targets, +// and (3) packages in the module cache. Packages in (1) and (2) may change over +// time, as the client may edit the current module and locally replaced modules. +// The module cache (which includes all of the packages in (3)) can only +// ever be added to. +// +// The resolver can thus save state about packages in the module cache +// and guarantee that this will not change over time. To obtain information +// about new modules added to the module cache, the module cache should be +// rescanned. +// +// It is OK to serve information about modules that have been deleted, +// as they do still exist. +// TODO(suzmue): can we share information with the caller about +// what module needs to be downloaded to import this package? + +type directoryPackageStatus int + +const ( + _ directoryPackageStatus = iota + directoryScanned + nameLoaded + exportsLoaded +) + +// directoryPackageInfo holds (possibly incomplete) information about packages +// contained in a given directory. +type directoryPackageInfo struct { + // status indicates the extent to which this struct has been filled in. + status directoryPackageStatus + // err is non-nil when there was an error trying to reach status. + err error + + // Set when status >= directoryScanned. + + // dir is the absolute directory of this package. + dir string + rootType gopathwalk.RootType + // nonCanonicalImportPath is the package's expected import path. It may + // not actually be importable at that path. + nonCanonicalImportPath string + + // Module-related information. + moduleDir string // The directory that is the module root of this dir. + moduleName string // The module name that contains this dir. + + // Set when status >= nameLoaded. + + packageName string // the package name, as declared in the source. + + // Set when status >= exportsLoaded. + // TODO(rfindley): it's hard to see this, but exports depend implicitly on + // the default build context GOOS and GOARCH. + // + // We can make this explicit, and key exports by GOOS, GOARCH. + exports []stdlib.Symbol +} + +// reachedStatus returns true when info has a status at least target and any error associated with +// an attempt to reach target. +func (info *directoryPackageInfo) reachedStatus(target directoryPackageStatus) (bool, error) { + if info.err == nil { + return info.status >= target, nil + } + if info.status == target { + return true, info.err + } + return true, nil +} + +// DirInfoCache is a concurrency-safe map for storing information about +// directories that may contain packages. +// +// The information in this cache is built incrementally. Entries are initialized in scan. +// No new keys should be added in any other functions, as all directories containing +// packages are identified in scan. +// +// Other functions, including loadExports and findPackage, may update entries in this cache +// as they discover new things about the directory. +// +// The information in the cache is not expected to change for the cache's +// lifetime, so there is no protection against competing writes. Users should +// take care not to hold the cache across changes to the underlying files. +type DirInfoCache struct { + mu sync.Mutex + // dirs stores information about packages in directories, keyed by absolute path. + dirs map[string]*directoryPackageInfo + listeners map[*int]cacheListener +} + +func NewDirInfoCache() *DirInfoCache { + return &DirInfoCache{ + dirs: make(map[string]*directoryPackageInfo), + listeners: make(map[*int]cacheListener), + } +} + +type cacheListener func(directoryPackageInfo) + +// ScanAndListen calls listener on all the items in the cache, and on anything +// newly added. The returned stop function waits for all in-flight callbacks to +// finish and blocks new ones. +func (d *DirInfoCache) ScanAndListen(ctx context.Context, listener cacheListener) func() { + ctx, cancel := context.WithCancel(ctx) + + // Flushing out all the callbacks is tricky without knowing how many there + // are going to be. Setting an arbitrary limit makes it much easier. + const maxInFlight = 10 + sema := make(chan struct{}, maxInFlight) + for range maxInFlight { + sema <- struct{}{} + } + + cookie := new(int) // A unique ID we can use for the listener. + + // We can't hold mu while calling the listener. + d.mu.Lock() + var keys []string + for key := range d.dirs { + keys = append(keys, key) + } + d.listeners[cookie] = func(info directoryPackageInfo) { + select { + case <-ctx.Done(): + return + case <-sema: + } + listener(info) + sema <- struct{}{} + } + d.mu.Unlock() + + stop := func() { + cancel() + d.mu.Lock() + delete(d.listeners, cookie) + d.mu.Unlock() + for range maxInFlight { + <-sema + } + } + + // Process the pre-existing keys. + for _, k := range keys { + select { + case <-ctx.Done(): + return stop + default: + } + if v, ok := d.Load(k); ok { + listener(v) + } + } + + return stop +} + +// Store stores the package info for dir. +func (d *DirInfoCache) Store(dir string, info directoryPackageInfo) { + d.mu.Lock() + // TODO(rfindley, golang/go#59216): should we overwrite an existing entry? + // That seems incorrect as the cache should be idempotent. + _, old := d.dirs[dir] + d.dirs[dir] = &info + var listeners []cacheListener + for _, l := range d.listeners { + listeners = append(listeners, l) + } + d.mu.Unlock() + + if !old { + for _, l := range listeners { + l(info) + } + } +} + +// Load returns a copy of the directoryPackageInfo for absolute directory dir. +func (d *DirInfoCache) Load(dir string) (directoryPackageInfo, bool) { + d.mu.Lock() + defer d.mu.Unlock() + info, ok := d.dirs[dir] + if !ok { + return directoryPackageInfo{}, false + } + return *info, true +} + +// Keys returns the keys currently present in d. +func (d *DirInfoCache) Keys() (keys []string) { + d.mu.Lock() + defer d.mu.Unlock() + for key := range d.dirs { + keys = append(keys, key) + } + return keys +} + +func (d *DirInfoCache) CachePackageName(info directoryPackageInfo) (string, error) { + if loaded, err := info.reachedStatus(nameLoaded); loaded { + return info.packageName, err + } + if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil { + return "", fmt.Errorf("cannot read package name, scan error: %v", err) + } + info.packageName, info.err = packageDirToName(info.dir) + info.status = nameLoaded + d.Store(info.dir, info) + return info.packageName, info.err +} + +func (d *DirInfoCache) CacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) { + if reached, _ := info.reachedStatus(exportsLoaded); reached { + return info.packageName, info.exports, info.err + } + if reached, err := info.reachedStatus(nameLoaded); reached && err != nil { + return "", nil, err + } + info.packageName, info.exports, info.err = loadExportsFromFiles(ctx, env, info.dir, false) + if info.err == context.Canceled || info.err == context.DeadlineExceeded { + return info.packageName, info.exports, info.err + } + // The cache structure wants things to proceed linearly. We can skip a + // step here, but only if we succeed. + if info.status == nameLoaded || info.err == nil { + info.status = exportsLoaded + } else { + info.status = nameLoaded + } + d.Store(info.dir, info) + return info.packageName, info.exports, info.err +} + +// ScanModuleCache walks the given directory, which must be a GOMODCACHE value, +// for directory package information, storing the results in cache. +func ScanModuleCache(dir string, cache *DirInfoCache, logf func(string, ...any)) { + // Note(rfindley): it's hard to see, but this function attempts to implement + // just the side effects on cache of calling PrimeCache with a ProcessEnv + // that has the given dir as its GOMODCACHE. + // + // Teasing out the control flow, we see that we can avoid any handling of + // vendor/ and can infer module info entirely from the path, simplifying the + // logic here. + + root := gopathwalk.Root{ + Path: filepath.Clean(dir), + Type: gopathwalk.RootModuleCache, + } + + directoryInfo := func(root gopathwalk.Root, dir string) directoryPackageInfo { + // This is a copy of ModuleResolver.scanDirForPackage, trimmed down to + // logic that applies to a module cache directory. + + subdir := "" + if dir != root.Path { + subdir = dir[len(root.Path)+len("/"):] + } + + matches := modCacheRegexp.FindStringSubmatch(subdir) + if len(matches) == 0 { + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("invalid module cache path: %v", subdir), + } + } + modPath, err := module.UnescapePath(filepath.ToSlash(matches[1])) + if err != nil { + if logf != nil { + logf("decoding module cache path %q: %v", subdir, err) + } + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("decoding module cache path %q: %v", subdir, err), + } + } + importPath := path.Join(modPath, filepath.ToSlash(matches[3])) + index := strings.Index(dir, matches[1]+"@"+matches[2]) + modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2]) + modName := readModName(filepath.Join(modDir, "go.mod")) + return directoryPackageInfo{ + status: directoryScanned, + dir: dir, + rootType: root.Type, + nonCanonicalImportPath: importPath, + moduleDir: modDir, + moduleName: modName, + } + } + + add := func(root gopathwalk.Root, dir string) { + info := directoryInfo(root, dir) + cache.Store(info.dir, info) + } + + skip := func(_ gopathwalk.Root, dir string) bool { + // Skip directories that have already been scanned. + // + // Note that gopathwalk only adds "package" directories, which must contain + // a .go file, and all such package directories in the module cache are + // immutable. So if we can load a dir, it can be skipped. + info, ok := cache.Load(dir) + if !ok { + return false + } + packageScanned, _ := info.reachedStatus(directoryScanned) + return packageScanned + } + + gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: logf, ModulesEnabled: true}) +} diff --git a/vendor/golang.org/x/tools/internal/imports/sortimports.go b/vendor/golang.org/x/tools/internal/imports/sortimports.go new file mode 100644 index 000000000..67c17bc43 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/sortimports.go @@ -0,0 +1,298 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Hacked up copy of go/ast/import.go +// Modified to use a single token.File in preference to a FileSet. + +package imports + +import ( + "go/ast" + "go/token" + "log" + "slices" + "sort" + "strconv" +) + +// sortImports sorts runs of consecutive import lines in import blocks in f. +// It also removes duplicate imports when it is possible to do so without data loss. +// +// It may mutate the token.File and the ast.File. +func sortImports(localPrefix string, tokFile *token.File, f *ast.File) { + for i, d := range f.Decls { + d, ok := d.(*ast.GenDecl) + if !ok || d.Tok != token.IMPORT { + // Not an import declaration, so we're done. + // Imports are always first. + break + } + + if len(d.Specs) == 0 { + // Empty import block, remove it. + f.Decls = slices.Delete(f.Decls, i, i+1) + } + + if !d.Lparen.IsValid() { + // Not a block: sorted by default. + continue + } + + // Identify and sort runs of specs on successive lines. + i := 0 + specs := d.Specs[:0] + for j, s := range d.Specs { + if j > i && tokFile.Line(s.Pos()) > 1+tokFile.Line(d.Specs[j-1].End()) { + // j begins a new run. End this one. + specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:j])...) + i = j + } + } + specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:])...) + d.Specs = specs + + // Deduping can leave a blank line before the rparen; clean that up. + // Ignore line directives. + if len(d.Specs) > 0 { + lastSpec := d.Specs[len(d.Specs)-1] + lastLine := tokFile.PositionFor(lastSpec.Pos(), false).Line + if rParenLine := tokFile.PositionFor(d.Rparen, false).Line; rParenLine > lastLine+1 { + tokFile.MergeLine(rParenLine - 1) // has side effects! + } + } + } +} + +// mergeImports merges all the import declarations into the first one. +// Taken from golang.org/x/tools/ast/astutil. +// This does not adjust line numbers properly +func mergeImports(f *ast.File) { + if len(f.Decls) <= 1 { + return + } + + // Merge all the import declarations into the first one. + var first *ast.GenDecl + for i := 0; i < len(f.Decls); i++ { + decl := f.Decls[i] + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { + continue + } + if first == nil { + first = gen + continue // Don't touch the first one. + } + // We now know there is more than one package in this import + // declaration. Ensure that it ends up parenthesized. + first.Lparen = first.Pos() + // Move the imports of the other import declaration to the first one. + for _, spec := range gen.Specs { + spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() + first.Specs = append(first.Specs, spec) + } + f.Decls = slices.Delete(f.Decls, i, i+1) + i-- + } +} + +// declImports reports whether gen contains an import of path. +// Taken from golang.org/x/tools/ast/astutil. +func declImports(gen *ast.GenDecl, path string) bool { + if gen.Tok != token.IMPORT { + return false + } + for _, spec := range gen.Specs { + impspec := spec.(*ast.ImportSpec) + if importPath(impspec) == path { + return true + } + } + return false +} + +func importPath(s ast.Spec) string { + t, err := strconv.Unquote(s.(*ast.ImportSpec).Path.Value) + if err == nil { + return t + } + return "" +} + +func importName(s ast.Spec) string { + n := s.(*ast.ImportSpec).Name + if n == nil { + return "" + } + return n.Name +} + +func importComment(s ast.Spec) string { + c := s.(*ast.ImportSpec).Comment + if c == nil { + return "" + } + return c.Text() +} + +// collapse indicates whether prev may be removed, leaving only next. +func collapse(prev, next ast.Spec) bool { + if importPath(next) != importPath(prev) || importName(next) != importName(prev) { + return false + } + return prev.(*ast.ImportSpec).Comment == nil +} + +type posSpan struct { + Start token.Pos + End token.Pos +} + +// sortSpecs sorts the import specs within each import decl. +// It may mutate the token.File. +func sortSpecs(localPrefix string, tokFile *token.File, f *ast.File, specs []ast.Spec) []ast.Spec { + // Can't short-circuit here even if specs are already sorted, + // since they might yet need deduplication. + // A lone import, however, may be safely ignored. + if len(specs) <= 1 { + return specs + } + + // Record positions for specs. + pos := make([]posSpan, len(specs)) + for i, s := range specs { + pos[i] = posSpan{s.Pos(), s.End()} + } + + // Identify comments in this range. + // Any comment from pos[0].Start to the final line counts. + lastLine := tokFile.Line(pos[len(pos)-1].End) + cstart := len(f.Comments) + cend := len(f.Comments) + for i, g := range f.Comments { + if g.Pos() < pos[0].Start { + continue + } + if i < cstart { + cstart = i + } + if tokFile.Line(g.End()) > lastLine { + cend = i + break + } + } + comments := f.Comments[cstart:cend] + + // Assign each comment to the import spec preceding it. + importComment := map[*ast.ImportSpec][]*ast.CommentGroup{} + specIndex := 0 + for _, g := range comments { + for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() { + specIndex++ + } + s := specs[specIndex].(*ast.ImportSpec) + importComment[s] = append(importComment[s], g) + } + + // Sort the import specs by import path. + // Remove duplicates, when possible without data loss. + // Reassign the import paths to have the same position sequence. + // Reassign each comment to abut the end of its spec. + // Sort the comments by new position. + sort.Sort(byImportSpec{localPrefix, specs}) + + // Dedup. Thanks to our sorting, we can just consider + // adjacent pairs of imports. + deduped := specs[:0] + for i, s := range specs { + if i == len(specs)-1 || !collapse(s, specs[i+1]) { + deduped = append(deduped, s) + } else { + p := s.Pos() + tokFile.MergeLine(tokFile.Line(p)) // has side effects! + } + } + specs = deduped + + // Fix up comment positions + for i, s := range specs { + s := s.(*ast.ImportSpec) + if s.Name != nil { + s.Name.NamePos = pos[i].Start + } + s.Path.ValuePos = pos[i].Start + s.EndPos = pos[i].End + nextSpecPos := pos[i].End + + for _, g := range importComment[s] { + for _, c := range g.List { + c.Slash = pos[i].End + nextSpecPos = c.End() + } + } + if i < len(specs)-1 { + pos[i+1].Start = nextSpecPos + pos[i+1].End = nextSpecPos + } + } + + sort.Sort(byCommentPos(comments)) + + // Fixup comments can insert blank lines, because import specs are on different lines. + // We remove those blank lines here by merging import spec to the first import spec line. + firstSpecLine := tokFile.Line(specs[0].Pos()) + for _, s := range specs[1:] { + p := s.Pos() + line := tokFile.Line(p) + for previousLine := line - 1; previousLine >= firstSpecLine; { + // MergeLine can panic. Avoid the panic at the cost of not removing the blank line + // golang/go#50329 + if previousLine > 0 && previousLine < tokFile.LineCount() { + tokFile.MergeLine(previousLine) // has side effects! + previousLine-- + } else { + // try to gather some data to diagnose how this could happen + req := "Please report what the imports section of your go file looked like." + log.Printf("panic avoided: first:%d line:%d previous:%d max:%d. %s", + firstSpecLine, line, previousLine, tokFile.LineCount(), req) + } + } + } + return specs +} + +type byImportSpec struct { + localPrefix string + specs []ast.Spec // slice of *ast.ImportSpec +} + +func (x byImportSpec) Len() int { return len(x.specs) } +func (x byImportSpec) Swap(i, j int) { x.specs[i], x.specs[j] = x.specs[j], x.specs[i] } +func (x byImportSpec) Less(i, j int) bool { + ipath := importPath(x.specs[i]) + jpath := importPath(x.specs[j]) + + igroup := importGroup(x.localPrefix, ipath) + jgroup := importGroup(x.localPrefix, jpath) + if igroup != jgroup { + return igroup < jgroup + } + + if ipath != jpath { + return ipath < jpath + } + iname := importName(x.specs[i]) + jname := importName(x.specs[j]) + + if iname != jname { + return iname < jname + } + return importComment(x.specs[i]) < importComment(x.specs[j]) +} + +type byCommentPos []*ast.CommentGroup + +func (x byCommentPos) Len() int { return len(x) } +func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() } diff --git a/vendor/golang.org/x/tools/internal/imports/source.go b/vendor/golang.org/x/tools/internal/imports/source.go new file mode 100644 index 000000000..cbe4f3c5b --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/source.go @@ -0,0 +1,63 @@ +// Copyright 2024 The Go 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 imports + +import "context" + +// These types document the APIs below. +// +// TODO(rfindley): consider making these defined types rather than aliases. +type ( + ImportPath = string + PackageName = string + Symbol = string + + // References is set of References found in a Go file. The first map key is the + // left hand side of a selector expression, the second key is the right hand + // side, and the value should always be true. + References = map[PackageName]map[Symbol]bool +) + +// A Result satisfies a missing import. +// +// The Import field describes the missing import spec, and the Package field +// summarizes the package exports. +type Result struct { + Import *ImportInfo + Package *PackageInfo +} + +// An ImportInfo represents a single import statement. +type ImportInfo struct { + ImportPath string // import path, e.g. "crypto/rand". + Name string // import name, e.g. "crand", or "" if none. +} + +// A PackageInfo represents what's known about a package. +type PackageInfo struct { + Name string // package name in the package declaration, if known + Exports map[string]bool // set of names of known package level sortSymbols +} + +// A Source provides imports to satisfy unresolved references in the file being +// fixed. +type Source interface { + // LoadPackageNames queries PackageName information for the requested import + // paths, when operating from the provided srcDir. + // + // TODO(rfindley): try to refactor to remove this operation. + LoadPackageNames(ctx context.Context, srcDir string, paths []ImportPath) (map[ImportPath]PackageName, error) + + // ResolveReferences asks the Source for the best package name to satisfy + // each of the missing references, in the context of fixing the given + // filename. + // + // Returns a map from package name to a [Result] for that package name that + // provides the required symbols. Keys may be omitted in the map if no + // candidates satisfy all missing references for that package name. It is up + // to each data source to select the best result for each entry in the + // missing map. + ResolveReferences(ctx context.Context, filename string, missing References) ([]*Result, error) +} diff --git a/vendor/golang.org/x/tools/internal/imports/source_env.go b/vendor/golang.org/x/tools/internal/imports/source_env.go new file mode 100644 index 000000000..ec996c3cc --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/source_env.go @@ -0,0 +1,129 @@ +// Copyright 2024 The Go 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 imports + +import ( + "context" + "path/filepath" + "strings" + "sync" + + "golang.org/x/sync/errgroup" + "golang.org/x/tools/internal/gopathwalk" +) + +// ProcessEnvSource implements the [Source] interface using the legacy +// [ProcessEnv] abstraction. +type ProcessEnvSource struct { + env *ProcessEnv + srcDir string + filename string + pkgName string +} + +// NewProcessEnvSource returns a [ProcessEnvSource] wrapping the given +// env, to be used for fixing imports in the file with name filename in package +// named pkgName. +func NewProcessEnvSource(env *ProcessEnv, filename, pkgName string) (*ProcessEnvSource, error) { + abs, err := filepath.Abs(filename) + if err != nil { + return nil, err + } + srcDir := filepath.Dir(abs) + return &ProcessEnvSource{ + env: env, + srcDir: srcDir, + filename: filename, + pkgName: pkgName, + }, nil +} + +func (s *ProcessEnvSource) LoadPackageNames(ctx context.Context, srcDir string, unknown []string) (map[string]string, error) { + r, err := s.env.GetResolver() + if err != nil { + return nil, err + } + return r.loadPackageNames(unknown, srcDir) +} + +func (s *ProcessEnvSource) ResolveReferences(ctx context.Context, filename string, refs map[string]map[string]bool) ([]*Result, error) { + var mu sync.Mutex + found := make(map[string][]pkgDistance) + callback := &scanCallback{ + rootFound: func(gopathwalk.Root) bool { + return true // We want everything. + }, + dirFound: func(pkg *pkg) bool { + return pkgIsCandidate(filename, refs, pkg) + }, + packageNameLoaded: func(pkg *pkg) bool { + if _, want := refs[pkg.packageName]; !want { + return false + } + if pkg.dir == s.srcDir && s.pkgName == pkg.packageName { + // The candidate is in the same directory and has the + // same package name. Don't try to import ourselves. + return false + } + if !CanUse(filename, pkg.dir) { + return false + } + mu.Lock() + defer mu.Unlock() + found[pkg.packageName] = append(found[pkg.packageName], pkgDistance{pkg, distance(s.srcDir, pkg.dir)}) + return false // We'll do our own loading after we sort. + }, + } + resolver, err := s.env.GetResolver() + if err != nil { + return nil, err + } + if err := resolver.scan(ctx, callback); err != nil { + return nil, err + } + + g, ctx := errgroup.WithContext(ctx) + + searcher := symbolSearcher{ + logf: s.env.logf, + srcDir: s.srcDir, + xtest: strings.HasSuffix(s.pkgName, "_test"), + loadExports: resolver.loadExports, + } + + var resultMu sync.Mutex + results := make(map[string]*Result, len(refs)) + for pkgName, symbols := range refs { + g.Go(func() error { + found, err := searcher.search(ctx, found[pkgName], pkgName, symbols) + if err != nil { + return err + } + if found == nil { + return nil // No matching package. + } + + imp := &ImportInfo{ + ImportPath: found.importPathShort, + } + pkg := &PackageInfo{ + Name: pkgName, + Exports: symbols, + } + resultMu.Lock() + results[pkgName] = &Result{Import: imp, Package: pkg} + resultMu.Unlock() + return nil + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + var ans []*Result + for _, x := range results { + ans = append(ans, x) + } + return ans, nil +} diff --git a/vendor/golang.org/x/tools/internal/imports/source_modindex.go b/vendor/golang.org/x/tools/internal/imports/source_modindex.go new file mode 100644 index 000000000..05229f06c --- /dev/null +++ b/vendor/golang.org/x/tools/internal/imports/source_modindex.go @@ -0,0 +1,103 @@ +// Copyright 2024 The Go 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 imports + +import ( + "context" + "sync" + "time" + + "golang.org/x/tools/internal/modindex" +) + +// This code is here rather than in the modindex package +// to avoid import loops + +// implements Source using modindex, so only for module cache. +// +// this is perhaps over-engineered. A new Index is read at first use. +// And then Update is called after every 15 minutes, and a new Index +// is read if the index changed. It is not clear the Mutex is needed. +type IndexSource struct { + modcachedir string + mutex sync.Mutex + ix *modindex.Index + expires time.Time +} + +// create a new Source. Called from NewView in cache/session.go. +func NewIndexSource(cachedir string) *IndexSource { + return &IndexSource{modcachedir: cachedir} +} + +func (s *IndexSource) LoadPackageNames(ctx context.Context, srcDir string, paths []ImportPath) (map[ImportPath]PackageName, error) { + /// This is used by goimports to resolve the package names of imports of the + // current package, which is irrelevant for the module cache. + return nil, nil +} + +func (s *IndexSource) ResolveReferences(ctx context.Context, filename string, missing References) ([]*Result, error) { + if err := s.maybeReadIndex(); err != nil { + return nil, err + } + var cs []modindex.Candidate + for pkg, nms := range missing { + for nm := range nms { + x := s.ix.Lookup(pkg, nm, false) + cs = append(cs, x...) + } + } + found := make(map[string]*Result) + for _, c := range cs { + var x *Result + if x = found[c.ImportPath]; x == nil { + x = &Result{ + Import: &ImportInfo{ + ImportPath: c.ImportPath, + Name: "", + }, + Package: &PackageInfo{ + Name: c.PkgName, + Exports: make(map[string]bool), + }, + } + found[c.ImportPath] = x + } + x.Package.Exports[c.Name] = true + } + var ans []*Result + for _, x := range found { + ans = append(ans, x) + } + return ans, nil +} + +func (s *IndexSource) maybeReadIndex() error { + s.mutex.Lock() + defer s.mutex.Unlock() + + var readIndex bool + if time.Now().After(s.expires) { + ok, err := modindex.Update(s.modcachedir) + if err != nil { + return err + } + if ok { + readIndex = true + } + } + + if readIndex || s.ix == nil { + ix, err := modindex.ReadIndex(s.modcachedir) + if err != nil { + return err + } + s.ix = ix + // for now refresh every 15 minutes + s.expires = time.Now().Add(time.Minute * 15) + } + + return nil +} diff --git a/vendor/golang.org/x/tools/internal/modindex/directories.go b/vendor/golang.org/x/tools/internal/modindex/directories.go new file mode 100644 index 000000000..1e1a02f23 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/modindex/directories.go @@ -0,0 +1,135 @@ +// Copyright 2024 The Go 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 modindex + +import ( + "fmt" + "log" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "time" + + "golang.org/x/mod/semver" + "golang.org/x/tools/internal/gopathwalk" +) + +type directory struct { + path Relpath + importPath string + version string // semantic version + syms []symbol +} + +// filterDirs groups the directories by import path, +// sorting the ones with the same import path by semantic version, +// most recent first. +func byImportPath(dirs []Relpath) (map[string][]*directory, error) { + ans := make(map[string][]*directory) // key is import path + for _, d := range dirs { + ip, sv, err := DirToImportPathVersion(d) + if err != nil { + return nil, err + } + ans[ip] = append(ans[ip], &directory{ + path: d, + importPath: ip, + version: sv, + }) + } + for k, v := range ans { + semanticSort(v) + ans[k] = v + } + return ans, nil +} + +// sort the directories by semantic version, latest first +func semanticSort(v []*directory) { + slices.SortFunc(v, func(l, r *directory) int { + if n := semver.Compare(l.version, r.version); n != 0 { + return -n // latest first + } + return strings.Compare(string(l.path), string(r.path)) + }) +} + +// modCacheRegexp splits a relpathpath into module, module version, and package. +var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`) + +// DirToImportPathVersion computes import path and semantic version +func DirToImportPathVersion(dir Relpath) (string, string, error) { + m := modCacheRegexp.FindStringSubmatch(string(dir)) + // m[1] is the module path + // m[2] is the version major.minor.patch(-
 1 && flds[1][1] == 'D',
+			}
+			if px.Type == Func {
+				n, err := strconv.Atoi(flds[2])
+				if err != nil {
+					continue // should never happen
+				}
+				px.Results = int16(n)
+				if len(flds) >= 4 {
+					sig := strings.Split(flds[3], " ")
+					for i := range sig {
+						// $ cannot otherwise occur. removing the spaces
+						// almost works, but for chan struct{}, e.g.
+						sig[i] = strings.Replace(sig[i], "$", " ", -1)
+					}
+					px.Sig = toFields(sig)
+				}
+			}
+			ans = append(ans, px)
+		}
+	}
+	return ans
+}
+
+func toFields(sig []string) []Field {
+	ans := make([]Field, len(sig)/2)
+	for i := range ans {
+		ans[i] = Field{Arg: sig[2*i], Type: sig[2*i+1]}
+	}
+	return ans
+}
+
+// benchmarks show this is measurably better than strings.Split
+// split into first 4 fields separated by single space
+func fastSplit(x string) []string {
+	ans := make([]string, 0, 4)
+	nxt := 0
+	start := 0
+	for i := 0; i < len(x); i++ {
+		if x[i] != ' ' {
+			continue
+		}
+		ans = append(ans, x[start:i])
+		nxt++
+		start = i + 1
+		if nxt >= 3 {
+			break
+		}
+	}
+	ans = append(ans, x[start:])
+	return ans
+}
+
+func asLexType(c byte) LexType {
+	switch c {
+	case 'C':
+		return Const
+	case 'V':
+		return Var
+	case 'T':
+		return Type
+	case 'F':
+		return Func
+	}
+	return -1
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/modindex.go b/vendor/golang.org/x/tools/internal/modindex/modindex.go
new file mode 100644
index 000000000..355a53e71
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/modindex.go
@@ -0,0 +1,164 @@
+// Copyright 2024 The Go 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 modindex contains code for building and searching an index to
+// the Go module cache. The directory containing the index, returned by
+// IndexDir(), contains a file index-name- that contains the name
+// of the current index. We believe writing that short file is atomic.
+// ReadIndex reads that file to get the file name of the index.
+// WriteIndex writes an index with a unique name and then
+// writes that name into a new version of index-name-.
+// ( stands for the CurrentVersion of the index format.)
+package modindex
+
+import (
+	"path/filepath"
+	"slices"
+	"strings"
+	"time"
+
+	"golang.org/x/mod/semver"
+)
+
+// Create always creates a new index for the go module cache that is in cachedir.
+func Create(cachedir string) error {
+	_, err := indexModCache(cachedir, true)
+	return err
+}
+
+// Update the index for the go module cache that is in cachedir,
+// If there is no existing index it will build one.
+// If there are changed directories since the last index, it will
+// write a new one and return true. Otherwise it returns false.
+func Update(cachedir string) (bool, error) {
+	return indexModCache(cachedir, false)
+}
+
+// indexModCache writes an index current as of when it is called.
+// If clear is true the index is constructed from all of GOMODCACHE
+// otherwise the index is constructed from the last previous index
+// and the updates to the cache. It returns true if it wrote an index,
+// false otherwise.
+func indexModCache(cachedir string, clear bool) (bool, error) {
+	cachedir, err := filepath.Abs(cachedir)
+	if err != nil {
+		return false, err
+	}
+	cd := Abspath(cachedir)
+	future := time.Now().Add(24 * time.Hour) // safely in the future
+	ok, err := modindexTimed(future, cd, clear)
+	if err != nil {
+		return false, err
+	}
+	return ok, nil
+}
+
+// modindexTimed writes an index current as of onlyBefore.
+// If clear is true the index is constructed from all of GOMODCACHE
+// otherwise the index is constructed from the last previous index
+// and all the updates to the cache before onlyBefore.
+// It returns true if it wrote a new index, false if it wrote nothing.
+func modindexTimed(onlyBefore time.Time, cachedir Abspath, clear bool) (bool, error) {
+	var curIndex *Index
+	if !clear {
+		var err error
+		curIndex, err = ReadIndex(string(cachedir))
+		if clear && err != nil {
+			return false, err
+		}
+		// TODO(pjw): check that most of those directories still exist
+	}
+	cfg := &work{
+		onlyBefore: onlyBefore,
+		oldIndex:   curIndex,
+		cacheDir:   cachedir,
+	}
+	if curIndex != nil {
+		cfg.onlyAfter = curIndex.Changed
+	}
+	if err := cfg.buildIndex(); err != nil {
+		return false, err
+	}
+	if len(cfg.newIndex.Entries) == 0 && curIndex != nil {
+		// no changes from existing curIndex, don't write a new index
+		return false, nil
+	}
+	if err := cfg.writeIndex(); err != nil {
+		return false, err
+	}
+	return true, nil
+}
+
+type work struct {
+	onlyBefore time.Time // do not use directories later than this
+	onlyAfter  time.Time // only interested in directories after this
+	// directories from before onlyAfter come from oldIndex
+	oldIndex *Index
+	newIndex *Index
+	cacheDir Abspath
+}
+
+func (w *work) buildIndex() error {
+	// The effective date of the new index should be at least
+	// slightly earlier than when the directories are scanned
+	// so set it now.
+	w.newIndex = &Index{Changed: time.Now(), Cachedir: w.cacheDir}
+	dirs := findDirs(string(w.cacheDir), w.onlyAfter, w.onlyBefore)
+	if len(dirs) == 0 {
+		return nil
+	}
+	newdirs, err := byImportPath(dirs)
+	if err != nil {
+		return err
+	}
+	// for each import path it might occur only in newdirs,
+	// only in w.oldIndex, or in both.
+	// If it occurs in both, use the semantically later one
+	if w.oldIndex != nil {
+		for _, e := range w.oldIndex.Entries {
+			found, ok := newdirs[e.ImportPath]
+			if !ok {
+				w.newIndex.Entries = append(w.newIndex.Entries, e)
+				continue // use this one, there is no new one
+			}
+			if semver.Compare(found[0].version, e.Version) > 0 {
+				// use the new one
+			} else {
+				// use the old one, forget the new one
+				w.newIndex.Entries = append(w.newIndex.Entries, e)
+				delete(newdirs, e.ImportPath)
+			}
+		}
+	}
+	// get symbol information for all the new diredtories
+	getSymbols(w.cacheDir, newdirs)
+	// assemble the new index entries
+	for k, v := range newdirs {
+		d := v[0]
+		pkg, names := processSyms(d.syms)
+		if pkg == "" {
+			continue // PJW: does this ever happen?
+		}
+		entry := Entry{
+			PkgName:    pkg,
+			Dir:        d.path,
+			ImportPath: k,
+			Version:    d.version,
+			Names:      names,
+		}
+		w.newIndex.Entries = append(w.newIndex.Entries, entry)
+	}
+	// sort the entries in the new index
+	slices.SortFunc(w.newIndex.Entries, func(l, r Entry) int {
+		if n := strings.Compare(l.PkgName, r.PkgName); n != 0 {
+			return n
+		}
+		return strings.Compare(l.ImportPath, r.ImportPath)
+	})
+	return nil
+}
+
+func (w *work) writeIndex() error {
+	return writeIndex(w.cacheDir, w.newIndex)
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/symbols.go b/vendor/golang.org/x/tools/internal/modindex/symbols.go
new file mode 100644
index 000000000..b918529d4
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/symbols.go
@@ -0,0 +1,218 @@
+// Copyright 2024 The Go 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 modindex
+
+import (
+	"fmt"
+	"go/ast"
+	"go/parser"
+	"go/token"
+	"go/types"
+	"os"
+	"path/filepath"
+	"runtime"
+	"slices"
+	"strings"
+
+	"golang.org/x/sync/errgroup"
+)
+
+// The name of a symbol contains information about the symbol:
+//  T for types, TD if the type is deprecated
+//  C for consts, CD if the const is deprecated
+//  V for vars, VD if the var is deprecated
+// and for funcs:  F  ( )*
+// any spaces in  are replaced by $s so that the fields
+// of the name are space separated. F is replaced by FD if the func
+// is deprecated.
+type symbol struct {
+	pkg  string // name of the symbols's package
+	name string // declared name
+	kind string // T, C, V, or F, follwed by D if deprecated
+	sig  string // signature information, for F
+}
+
+// find the symbols for the best directories
+func getSymbols(cd Abspath, dirs map[string][]*directory) {
+	var g errgroup.Group
+	g.SetLimit(max(2, runtime.GOMAXPROCS(0)/2))
+	for _, vv := range dirs {
+		// throttling some day?
+		d := vv[0]
+		g.Go(func() error {
+			thedir := filepath.Join(string(cd), string(d.path))
+			mode := parser.SkipObjectResolution | parser.ParseComments
+
+			fi, err := os.ReadDir(thedir)
+			if err != nil {
+				return nil // log this someday?
+			}
+			for _, fx := range fi {
+				if !strings.HasSuffix(fx.Name(), ".go") || strings.HasSuffix(fx.Name(), "_test.go") {
+					continue
+				}
+				fname := filepath.Join(thedir, fx.Name())
+				tr, err := parser.ParseFile(token.NewFileSet(), fname, nil, mode)
+				if err != nil {
+					continue // ignore errors, someday log them?
+				}
+				d.syms = append(d.syms, getFileExports(tr)...)
+			}
+			return nil
+		})
+	}
+	g.Wait()
+}
+
+func getFileExports(f *ast.File) []symbol {
+	pkg := f.Name.Name
+	if pkg == "main" {
+		return nil
+	}
+	var ans []symbol
+	// should we look for //go:build ignore?
+	for _, decl := range f.Decls {
+		switch decl := decl.(type) {
+		case *ast.FuncDecl:
+			if decl.Recv != nil {
+				// ignore methods, as we are completing package selections
+				continue
+			}
+			name := decl.Name.Name
+			dtype := decl.Type
+			// not looking at dtype.TypeParams. That is, treating
+			// generic functions just like non-generic ones.
+			sig := dtype.Params
+			kind := "F"
+			if isDeprecated(decl.Doc) {
+				kind += "D"
+			}
+			result := []string{fmt.Sprintf("%d", dtype.Results.NumFields())}
+			for _, x := range sig.List {
+				// This code creates a string representing the type.
+				// TODO(pjw): it may be fragile:
+				// 1. x.Type could be nil, perhaps in ill-formed code
+				// 2. ExprString might someday change incompatibly to
+				//    include struct tags, which can be arbitrary strings
+				if x.Type == nil {
+					// Can this happen without a parse error? (Files with parse
+					// errors are ignored in getSymbols)
+					continue // maybe report this someday
+				}
+				tp := types.ExprString(x.Type)
+				if len(tp) == 0 {
+					// Can this happen?
+					continue // maybe report this someday
+				}
+				// This is only safe if ExprString never returns anything with a $
+				// The only place a $ can occur seems to be in a struct tag, which
+				// can be an arbitrary string literal, and ExprString does not presently
+				// print struct tags. So for this to happen the type of a formal parameter
+				// has to be a explict struct, e.g. foo(x struct{a int "$"}) and ExprString
+				// would have to show the struct tag. Even testing for this case seems
+				// a waste of effort, but let's remember the possibility
+				if strings.Contains(tp, "$") {
+					continue
+				}
+				tp = strings.Replace(tp, " ", "$", -1)
+				if len(x.Names) == 0 {
+					result = append(result, "_")
+					result = append(result, tp)
+				} else {
+					for _, y := range x.Names {
+						result = append(result, y.Name)
+						result = append(result, tp)
+					}
+				}
+			}
+			sigs := strings.Join(result, " ")
+			if s := newsym(pkg, name, kind, sigs); s != nil {
+				ans = append(ans, *s)
+			}
+		case *ast.GenDecl:
+			depr := isDeprecated(decl.Doc)
+			switch decl.Tok {
+			case token.CONST, token.VAR:
+				tp := "V"
+				if decl.Tok == token.CONST {
+					tp = "C"
+				}
+				if depr {
+					tp += "D"
+				}
+				for _, sp := range decl.Specs {
+					for _, x := range sp.(*ast.ValueSpec).Names {
+						if s := newsym(pkg, x.Name, tp, ""); s != nil {
+							ans = append(ans, *s)
+						}
+					}
+				}
+			case token.TYPE:
+				tp := "T"
+				if depr {
+					tp += "D"
+				}
+				for _, sp := range decl.Specs {
+					if s := newsym(pkg, sp.(*ast.TypeSpec).Name.Name, tp, ""); s != nil {
+						ans = append(ans, *s)
+					}
+				}
+			}
+		}
+	}
+	return ans
+}
+
+func newsym(pkg, name, kind, sig string) *symbol {
+	if len(name) == 0 || !ast.IsExported(name) {
+		return nil
+	}
+	sym := symbol{pkg: pkg, name: name, kind: kind, sig: sig}
+	return &sym
+}
+
+func isDeprecated(doc *ast.CommentGroup) bool {
+	if doc == nil {
+		return false
+	}
+	// go.dev/wiki/Deprecated Paragraph starting 'Deprecated:'
+	// This code fails for /* Deprecated: */, but it's the code from
+	// gopls/internal/analysis/deprecated
+	lines := strings.Split(doc.Text(), "\n\n")
+	for _, line := range lines {
+		if strings.HasPrefix(line, "Deprecated:") {
+			return true
+		}
+	}
+	return false
+}
+
+// return the package name and the value for the symbols.
+// if there are multiple packages, choose one arbitrarily
+// the returned slice is sorted lexicographically
+func processSyms(syms []symbol) (string, []string) {
+	if len(syms) == 0 {
+		return "", nil
+	}
+	slices.SortFunc(syms, func(l, r symbol) int {
+		return strings.Compare(l.name, r.name)
+	})
+	pkg := syms[0].pkg
+	var names []string
+	for _, s := range syms {
+		var nx string
+		if s.pkg == pkg {
+			if s.sig != "" {
+				nx = fmt.Sprintf("%s %s %s", s.name, s.kind, s.sig)
+			} else {
+				nx = fmt.Sprintf("%s %s", s.name, s.kind)
+			}
+			names = append(names, nx)
+		} else {
+			continue // PJW: do we want to keep track of these?
+		}
+	}
+	return pkg, names
+}
diff --git a/vendor/golang.org/x/tools/internal/modindex/types.go b/vendor/golang.org/x/tools/internal/modindex/types.go
new file mode 100644
index 000000000..ece448863
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/modindex/types.go
@@ -0,0 +1,25 @@
+// Copyright 2024 The Go 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 modindex
+
+import (
+	"strings"
+)
+
+// some special types to avoid confusions
+
+// distinguish various types of directory names. It's easy to get confused.
+type Abspath string // absolute paths
+type Relpath string // paths with GOMODCACHE prefix removed
+
+func toRelpath(cachedir Abspath, s string) Relpath {
+	if strings.HasPrefix(s, string(cachedir)) {
+		if s == string(cachedir) {
+			return Relpath("")
+		}
+		return Relpath(s[len(cachedir)+1:])
+	}
+	return Relpath(s)
+}
diff --git a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go
new file mode 100644
index 000000000..25ebab663
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go
@@ -0,0 +1,20 @@
+// Copyright 2020 The Go 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 packagesinternal exposes internal-only fields from go/packages.
+package packagesinternal
+
+var GetDepsErrors = func(p any) []*PackageError { return nil }
+
+type PackageError struct {
+	ImportStack []string // shortest path from package named on command line to this one
+	Pos         string   // position of error (if present, file:line:col)
+	Err         string   // the error itself
+}
+
+var TypecheckCgo int
+var DepsErrors int // must be set as a LoadMode to call GetDepsErrors
+
+var SetModFlag = func(config any, value string) {}
+var SetModFile = func(config any, value string) {}
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/codes.go b/vendor/golang.org/x/tools/internal/pkgbits/codes.go
new file mode 100644
index 000000000..f0cabde96
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/codes.go
@@ -0,0 +1,77 @@
+// Copyright 2021 The Go 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 pkgbits
+
+// A Code is an enum value that can be encoded into bitstreams.
+//
+// Code types are preferable for enum types, because they allow
+// Decoder to detect desyncs.
+type Code interface {
+	// Marker returns the SyncMarker for the Code's dynamic type.
+	Marker() SyncMarker
+
+	// Value returns the Code's ordinal value.
+	Value() int
+}
+
+// A CodeVal distinguishes among go/constant.Value encodings.
+type CodeVal int
+
+func (c CodeVal) Marker() SyncMarker { return SyncVal }
+func (c CodeVal) Value() int         { return int(c) }
+
+// Note: These values are public and cannot be changed without
+// updating the go/types importers.
+
+const (
+	ValBool CodeVal = iota
+	ValString
+	ValInt64
+	ValBigInt
+	ValBigRat
+	ValBigFloat
+)
+
+// A CodeType distinguishes among go/types.Type encodings.
+type CodeType int
+
+func (c CodeType) Marker() SyncMarker { return SyncType }
+func (c CodeType) Value() int         { return int(c) }
+
+// Note: These values are public and cannot be changed without
+// updating the go/types importers.
+
+const (
+	TypeBasic CodeType = iota
+	TypeNamed
+	TypePointer
+	TypeSlice
+	TypeArray
+	TypeChan
+	TypeMap
+	TypeSignature
+	TypeStruct
+	TypeInterface
+	TypeUnion
+	TypeTypeParam
+)
+
+// A CodeObj distinguishes among go/types.Object encodings.
+type CodeObj int
+
+func (c CodeObj) Marker() SyncMarker { return SyncCodeObj }
+func (c CodeObj) Value() int         { return int(c) }
+
+// Note: These values are public and cannot be changed without
+// updating the go/types importers.
+
+const (
+	ObjAlias CodeObj = iota
+	ObjConst
+	ObjType
+	ObjFunc
+	ObjVar
+	ObjStub
+)
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/decoder.go b/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
new file mode 100644
index 000000000..c0aba26c4
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/decoder.go
@@ -0,0 +1,519 @@
+// Copyright 2021 The Go 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 pkgbits
+
+import (
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"go/constant"
+	"go/token"
+	"io"
+	"math/big"
+	"os"
+	"runtime"
+	"strings"
+)
+
+// A PkgDecoder provides methods for decoding a package's Unified IR
+// export data.
+type PkgDecoder struct {
+	// version is the file format version.
+	version Version
+
+	// sync indicates whether the file uses sync markers.
+	sync bool
+
+	// pkgPath is the package path for the package to be decoded.
+	//
+	// TODO(mdempsky): Remove; unneeded since CL 391014.
+	pkgPath string
+
+	// elemData is the full data payload of the encoded package.
+	// Elements are densely and contiguously packed together.
+	//
+	// The last 8 bytes of elemData are the package fingerprint.
+	elemData string
+
+	// elemEnds stores the byte-offset end positions of element
+	// bitstreams within elemData.
+	//
+	// For example, element I's bitstream data starts at elemEnds[I-1]
+	// (or 0, if I==0) and ends at elemEnds[I].
+	//
+	// Note: elemEnds is indexed by absolute indices, not
+	// section-relative indices.
+	elemEnds []uint32
+
+	// elemEndsEnds stores the index-offset end positions of relocation
+	// sections within elemEnds.
+	//
+	// For example, section K's end positions start at elemEndsEnds[K-1]
+	// (or 0, if K==0) and end at elemEndsEnds[K].
+	elemEndsEnds [numRelocs]uint32
+
+	scratchRelocEnt []RelocEnt
+}
+
+// PkgPath returns the package path for the package
+//
+// TODO(mdempsky): Remove; unneeded since CL 391014.
+func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath }
+
+// SyncMarkers reports whether pr uses sync markers.
+func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync }
+
+// NewPkgDecoder returns a PkgDecoder initialized to read the Unified
+// IR export data from input. pkgPath is the package path for the
+// compilation unit that produced the export data.
+func NewPkgDecoder(pkgPath, input string) PkgDecoder {
+	pr := PkgDecoder{
+		pkgPath: pkgPath,
+	}
+
+	// TODO(mdempsky): Implement direct indexing of input string to
+	// avoid copying the position information.
+
+	r := strings.NewReader(input)
+
+	var ver uint32
+	assert(binary.Read(r, binary.LittleEndian, &ver) == nil)
+	pr.version = Version(ver)
+
+	if pr.version >= numVersions {
+		panic(fmt.Errorf("cannot decode %q, export data version %d is greater than maximum supported version %d", pkgPath, pr.version, numVersions-1))
+	}
+
+	if pr.version.Has(Flags) {
+		var flags uint32
+		assert(binary.Read(r, binary.LittleEndian, &flags) == nil)
+		pr.sync = flags&flagSyncMarkers != 0
+	}
+
+	assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil)
+
+	pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1])
+	assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil)
+
+	pos, err := r.Seek(0, io.SeekCurrent)
+	assert(err == nil)
+
+	pr.elemData = input[pos:]
+
+	const fingerprintSize = 8
+	assert(len(pr.elemData)-fingerprintSize == int(pr.elemEnds[len(pr.elemEnds)-1]))
+
+	return pr
+}
+
+// NumElems returns the number of elements in section k.
+func (pr *PkgDecoder) NumElems(k RelocKind) int {
+	count := int(pr.elemEndsEnds[k])
+	if k > 0 {
+		count -= int(pr.elemEndsEnds[k-1])
+	}
+	return count
+}
+
+// TotalElems returns the total number of elements across all sections.
+func (pr *PkgDecoder) TotalElems() int {
+	return len(pr.elemEnds)
+}
+
+// Fingerprint returns the package fingerprint.
+func (pr *PkgDecoder) Fingerprint() [8]byte {
+	var fp [8]byte
+	copy(fp[:], pr.elemData[len(pr.elemData)-8:])
+	return fp
+}
+
+// AbsIdx returns the absolute index for the given (section, index)
+// pair.
+func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int {
+	absIdx := int(idx)
+	if k > 0 {
+		absIdx += int(pr.elemEndsEnds[k-1])
+	}
+	if absIdx >= int(pr.elemEndsEnds[k]) {
+		panicf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds)
+	}
+	return absIdx
+}
+
+// DataIdx returns the raw element bitstream for the given (section,
+// index) pair.
+func (pr *PkgDecoder) DataIdx(k RelocKind, idx Index) string {
+	absIdx := pr.AbsIdx(k, idx)
+
+	var start uint32
+	if absIdx > 0 {
+		start = pr.elemEnds[absIdx-1]
+	}
+	end := pr.elemEnds[absIdx]
+
+	return pr.elemData[start:end]
+}
+
+// StringIdx returns the string value for the given string index.
+func (pr *PkgDecoder) StringIdx(idx Index) string {
+	return pr.DataIdx(RelocString, idx)
+}
+
+// NewDecoder returns a Decoder for the given (section, index) pair,
+// and decodes the given SyncMarker from the element bitstream.
+func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
+	r := pr.NewDecoderRaw(k, idx)
+	r.Sync(marker)
+	return r
+}
+
+// TempDecoder returns a Decoder for the given (section, index) pair,
+// and decodes the given SyncMarker from the element bitstream.
+// If possible the Decoder should be RetireDecoder'd when it is no longer
+// needed, this will avoid heap allocations.
+func (pr *PkgDecoder) TempDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
+	r := pr.TempDecoderRaw(k, idx)
+	r.Sync(marker)
+	return r
+}
+
+func (pr *PkgDecoder) RetireDecoder(d *Decoder) {
+	pr.scratchRelocEnt = d.Relocs
+	d.Relocs = nil
+}
+
+// NewDecoderRaw returns a Decoder for the given (section, index) pair.
+//
+// Most callers should use NewDecoder instead.
+func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder {
+	r := Decoder{
+		common: pr,
+		k:      k,
+		Idx:    idx,
+	}
+
+	r.Data.Reset(pr.DataIdx(k, idx))
+	r.Sync(SyncRelocs)
+	r.Relocs = make([]RelocEnt, r.Len())
+	for i := range r.Relocs {
+		r.Sync(SyncReloc)
+		r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
+	}
+
+	return r
+}
+
+func (pr *PkgDecoder) TempDecoderRaw(k RelocKind, idx Index) Decoder {
+	r := Decoder{
+		common: pr,
+		k:      k,
+		Idx:    idx,
+	}
+
+	r.Data.Reset(pr.DataIdx(k, idx))
+	r.Sync(SyncRelocs)
+	l := r.Len()
+	if cap(pr.scratchRelocEnt) >= l {
+		r.Relocs = pr.scratchRelocEnt[:l]
+		pr.scratchRelocEnt = nil
+	} else {
+		r.Relocs = make([]RelocEnt, l)
+	}
+	for i := range r.Relocs {
+		r.Sync(SyncReloc)
+		r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
+	}
+
+	return r
+}
+
+// A Decoder provides methods for decoding an individual element's
+// bitstream data.
+type Decoder struct {
+	common *PkgDecoder
+
+	Relocs []RelocEnt
+	Data   strings.Reader
+
+	k   RelocKind
+	Idx Index
+}
+
+func (r *Decoder) checkErr(err error) {
+	if err != nil {
+		panicf("unexpected decoding error: %w", err)
+	}
+}
+
+func (r *Decoder) rawUvarint() uint64 {
+	x, err := readUvarint(&r.Data)
+	r.checkErr(err)
+	return x
+}
+
+// readUvarint is a type-specialized copy of encoding/binary.ReadUvarint.
+// This avoids the interface conversion and thus has better escape properties,
+// which flows up the stack.
+func readUvarint(r *strings.Reader) (uint64, error) {
+	var x uint64
+	var s uint
+	for i := range binary.MaxVarintLen64 {
+		b, err := r.ReadByte()
+		if err != nil {
+			if i > 0 && err == io.EOF {
+				err = io.ErrUnexpectedEOF
+			}
+			return x, err
+		}
+		if b < 0x80 {
+			if i == binary.MaxVarintLen64-1 && b > 1 {
+				return x, overflow
+			}
+			return x | uint64(b)<> 1)
+	if ux&1 != 0 {
+		x = ^x
+	}
+	return x
+}
+
+func (r *Decoder) rawReloc(k RelocKind, idx int) Index {
+	e := r.Relocs[idx]
+	assert(e.Kind == k)
+	return e.Idx
+}
+
+// Sync decodes a sync marker from the element bitstream and asserts
+// that it matches the expected marker.
+//
+// If r.common.sync is false, then Sync is a no-op.
+func (r *Decoder) Sync(mWant SyncMarker) {
+	if !r.common.sync {
+		return
+	}
+
+	pos, _ := r.Data.Seek(0, io.SeekCurrent)
+	mHave := SyncMarker(r.rawUvarint())
+	writerPCs := make([]int, r.rawUvarint())
+	for i := range writerPCs {
+		writerPCs[i] = int(r.rawUvarint())
+	}
+
+	if mHave == mWant {
+		return
+	}
+
+	// There's some tension here between printing:
+	//
+	// (1) full file paths that tools can recognize (e.g., so emacs
+	//     hyperlinks the "file:line" text for easy navigation), or
+	//
+	// (2) short file paths that are easier for humans to read (e.g., by
+	//     omitting redundant or irrelevant details, so it's easier to
+	//     focus on the useful bits that remain).
+	//
+	// The current formatting favors the former, as it seems more
+	// helpful in practice. But perhaps the formatting could be improved
+	// to better address both concerns. For example, use relative file
+	// paths if they would be shorter, or rewrite file paths to contain
+	// "$GOROOT" (like objabi.AbsFile does) if tools can be taught how
+	// to reliably expand that again.
+
+	fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos)
+
+	fmt.Printf("\nfound %v, written at:\n", mHave)
+	if len(writerPCs) == 0 {
+		fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath)
+	}
+	for _, pc := range writerPCs {
+		fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(RelocString, pc)))
+	}
+
+	fmt.Printf("\nexpected %v, reading at:\n", mWant)
+	var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size?
+	n := runtime.Callers(2, readerPCs[:])
+	for _, pc := range fmtFrames(readerPCs[:n]...) {
+		fmt.Printf("\t%s\n", pc)
+	}
+
+	// We already printed a stack trace for the reader, so now we can
+	// simply exit. Printing a second one with panic or base.Fatalf
+	// would just be noise.
+	os.Exit(1)
+}
+
+// Bool decodes and returns a bool value from the element bitstream.
+func (r *Decoder) Bool() bool {
+	r.Sync(SyncBool)
+	x, err := r.Data.ReadByte()
+	r.checkErr(err)
+	assert(x < 2)
+	return x != 0
+}
+
+// Int64 decodes and returns an int64 value from the element bitstream.
+func (r *Decoder) Int64() int64 {
+	r.Sync(SyncInt64)
+	return r.rawVarint()
+}
+
+// Uint64 decodes and returns a uint64 value from the element bitstream.
+func (r *Decoder) Uint64() uint64 {
+	r.Sync(SyncUint64)
+	return r.rawUvarint()
+}
+
+// Len decodes and returns a non-negative int value from the element bitstream.
+func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v }
+
+// Int decodes and returns an int value from the element bitstream.
+func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v }
+
+// Uint decodes and returns a uint value from the element bitstream.
+func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v }
+
+// Code decodes a Code value from the element bitstream and returns
+// its ordinal value. It's the caller's responsibility to convert the
+// result to an appropriate Code type.
+//
+// TODO(mdempsky): Ideally this method would have signature "Code[T
+// Code] T" instead, but we don't allow generic methods and the
+// compiler can't depend on generics yet anyway.
+func (r *Decoder) Code(mark SyncMarker) int {
+	r.Sync(mark)
+	return r.Len()
+}
+
+// Reloc decodes a relocation of expected section k from the element
+// bitstream and returns an index to the referenced element.
+func (r *Decoder) Reloc(k RelocKind) Index {
+	r.Sync(SyncUseReloc)
+	return r.rawReloc(k, r.Len())
+}
+
+// String decodes and returns a string value from the element
+// bitstream.
+func (r *Decoder) String() string {
+	r.Sync(SyncString)
+	return r.common.StringIdx(r.Reloc(RelocString))
+}
+
+// Strings decodes and returns a variable-length slice of strings from
+// the element bitstream.
+func (r *Decoder) Strings() []string {
+	res := make([]string, r.Len())
+	for i := range res {
+		res[i] = r.String()
+	}
+	return res
+}
+
+// Value decodes and returns a constant.Value from the element
+// bitstream.
+func (r *Decoder) Value() constant.Value {
+	r.Sync(SyncValue)
+	isComplex := r.Bool()
+	val := r.scalar()
+	if isComplex {
+		val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar()))
+	}
+	return val
+}
+
+func (r *Decoder) scalar() constant.Value {
+	switch tag := CodeVal(r.Code(SyncVal)); tag {
+	default:
+		panic(fmt.Errorf("unexpected scalar tag: %v", tag))
+
+	case ValBool:
+		return constant.MakeBool(r.Bool())
+	case ValString:
+		return constant.MakeString(r.String())
+	case ValInt64:
+		return constant.MakeInt64(r.Int64())
+	case ValBigInt:
+		return constant.Make(r.bigInt())
+	case ValBigRat:
+		num := r.bigInt()
+		denom := r.bigInt()
+		return constant.Make(new(big.Rat).SetFrac(num, denom))
+	case ValBigFloat:
+		return constant.Make(r.bigFloat())
+	}
+}
+
+func (r *Decoder) bigInt() *big.Int {
+	v := new(big.Int).SetBytes([]byte(r.String()))
+	if r.Bool() {
+		v.Neg(v)
+	}
+	return v
+}
+
+func (r *Decoder) bigFloat() *big.Float {
+	v := new(big.Float).SetPrec(512)
+	assert(v.UnmarshalText([]byte(r.String())) == nil)
+	return v
+}
+
+// @@@ Helpers
+
+// TODO(mdempsky): These should probably be removed. I think they're a
+// smell that the export data format is not yet quite right.
+
+// PeekPkgPath returns the package path for the specified package
+// index.
+func (pr *PkgDecoder) PeekPkgPath(idx Index) string {
+	var path string
+	{
+		r := pr.TempDecoder(RelocPkg, idx, SyncPkgDef)
+		path = r.String()
+		pr.RetireDecoder(&r)
+	}
+	if path == "" {
+		path = pr.pkgPath
+	}
+	return path
+}
+
+// PeekObj returns the package path, object name, and CodeObj for the
+// specified object index.
+func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) {
+	var ridx Index
+	var name string
+	var rcode int
+	{
+		r := pr.TempDecoder(RelocName, idx, SyncObject1)
+		r.Sync(SyncSym)
+		r.Sync(SyncPkg)
+		ridx = r.Reloc(RelocPkg)
+		name = r.String()
+		rcode = r.Code(SyncCodeObj)
+		pr.RetireDecoder(&r)
+	}
+
+	path := pr.PeekPkgPath(ridx)
+	assert(name != "")
+
+	tag := CodeObj(rcode)
+
+	return path, name, tag
+}
+
+// Version reports the version of the bitstream.
+func (w *Decoder) Version() Version { return w.common.version }
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/doc.go b/vendor/golang.org/x/tools/internal/pkgbits/doc.go
new file mode 100644
index 000000000..c8a2796b5
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/doc.go
@@ -0,0 +1,32 @@
+// Copyright 2022 The Go 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 pkgbits implements low-level coding abstractions for
+// Unified IR's export data format.
+//
+// At a low-level, a package is a collection of bitstream elements.
+// Each element has a "kind" and a dense, non-negative index.
+// Elements can be randomly accessed given their kind and index.
+//
+// Individual elements are sequences of variable-length values (e.g.,
+// integers, booleans, strings, go/constant values, cross-references
+// to other elements). Package pkgbits provides APIs for encoding and
+// decoding these low-level values, but the details of mapping
+// higher-level Go constructs into elements is left to higher-level
+// abstractions.
+//
+// Elements may cross-reference each other with "relocations." For
+// example, an element representing a pointer type has a relocation
+// referring to the element type.
+//
+// Go constructs may be composed as a constellation of multiple
+// elements. For example, a declared function may have one element to
+// describe the object (e.g., its name, type, position), and a
+// separate element to describe its function body. This allows readers
+// some flexibility in efficiently seeking or re-reading data (e.g.,
+// inlining requires re-reading the function body for each inlined
+// call, without needing to re-read the object-level details).
+//
+// This is a copy of internal/pkgbits in the Go implementation.
+package pkgbits
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/encoder.go b/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
new file mode 100644
index 000000000..c17a12399
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/encoder.go
@@ -0,0 +1,392 @@
+// Copyright 2021 The Go 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 pkgbits
+
+import (
+	"bytes"
+	"crypto/md5"
+	"encoding/binary"
+	"go/constant"
+	"io"
+	"math/big"
+	"runtime"
+	"strings"
+)
+
+// A PkgEncoder provides methods for encoding a package's Unified IR
+// export data.
+type PkgEncoder struct {
+	// version of the bitstream.
+	version Version
+
+	// elems holds the bitstream for previously encoded elements.
+	elems [numRelocs][]string
+
+	// stringsIdx maps previously encoded strings to their index within
+	// the RelocString section, to allow deduplication. That is,
+	// elems[RelocString][stringsIdx[s]] == s (if present).
+	stringsIdx map[string]Index
+
+	// syncFrames is the number of frames to write at each sync
+	// marker. A negative value means sync markers are omitted.
+	syncFrames int
+}
+
+// SyncMarkers reports whether pw uses sync markers.
+func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 }
+
+// NewPkgEncoder returns an initialized PkgEncoder.
+//
+// syncFrames is the number of caller frames that should be serialized
+// at Sync points. Serializing additional frames results in larger
+// export data files, but can help diagnosing desync errors in
+// higher-level Unified IR reader/writer code. If syncFrames is
+// negative, then sync markers are omitted entirely.
+func NewPkgEncoder(version Version, syncFrames int) PkgEncoder {
+	return PkgEncoder{
+		version:    version,
+		stringsIdx: make(map[string]Index),
+		syncFrames: syncFrames,
+	}
+}
+
+// DumpTo writes the package's encoded data to out0 and returns the
+// package fingerprint.
+func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) {
+	h := md5.New()
+	out := io.MultiWriter(out0, h)
+
+	writeUint32 := func(x uint32) {
+		assert(binary.Write(out, binary.LittleEndian, x) == nil)
+	}
+
+	writeUint32(uint32(pw.version))
+
+	if pw.version.Has(Flags) {
+		var flags uint32
+		if pw.SyncMarkers() {
+			flags |= flagSyncMarkers
+		}
+		writeUint32(flags)
+	}
+
+	// Write elemEndsEnds.
+	var sum uint32
+	for _, elems := range &pw.elems {
+		sum += uint32(len(elems))
+		writeUint32(sum)
+	}
+
+	// Write elemEnds.
+	sum = 0
+	for _, elems := range &pw.elems {
+		for _, elem := range elems {
+			sum += uint32(len(elem))
+			writeUint32(sum)
+		}
+	}
+
+	// Write elemData.
+	for _, elems := range &pw.elems {
+		for _, elem := range elems {
+			_, err := io.WriteString(out, elem)
+			assert(err == nil)
+		}
+	}
+
+	// Write fingerprint.
+	copy(fingerprint[:], h.Sum(nil))
+	_, err := out0.Write(fingerprint[:])
+	assert(err == nil)
+
+	return
+}
+
+// StringIdx adds a string value to the strings section, if not
+// already present, and returns its index.
+func (pw *PkgEncoder) StringIdx(s string) Index {
+	if idx, ok := pw.stringsIdx[s]; ok {
+		assert(pw.elems[RelocString][idx] == s)
+		return idx
+	}
+
+	idx := Index(len(pw.elems[RelocString]))
+	pw.elems[RelocString] = append(pw.elems[RelocString], s)
+	pw.stringsIdx[s] = idx
+	return idx
+}
+
+// NewEncoder returns an Encoder for a new element within the given
+// section, and encodes the given SyncMarker as the start of the
+// element bitstream.
+func (pw *PkgEncoder) NewEncoder(k RelocKind, marker SyncMarker) Encoder {
+	e := pw.NewEncoderRaw(k)
+	e.Sync(marker)
+	return e
+}
+
+// NewEncoderRaw returns an Encoder for a new element within the given
+// section.
+//
+// Most callers should use NewEncoder instead.
+func (pw *PkgEncoder) NewEncoderRaw(k RelocKind) Encoder {
+	idx := Index(len(pw.elems[k]))
+	pw.elems[k] = append(pw.elems[k], "") // placeholder
+
+	return Encoder{
+		p:   pw,
+		k:   k,
+		Idx: idx,
+	}
+}
+
+// An Encoder provides methods for encoding an individual element's
+// bitstream data.
+type Encoder struct {
+	p *PkgEncoder
+
+	Relocs   []RelocEnt
+	RelocMap map[RelocEnt]uint32
+	Data     bytes.Buffer // accumulated element bitstream data
+
+	encodingRelocHeader bool
+
+	k   RelocKind
+	Idx Index // index within relocation section
+}
+
+// Flush finalizes the element's bitstream and returns its Index.
+func (w *Encoder) Flush() Index {
+	var sb strings.Builder
+
+	// Backup the data so we write the relocations at the front.
+	var tmp bytes.Buffer
+	io.Copy(&tmp, &w.Data)
+
+	// TODO(mdempsky): Consider writing these out separately so they're
+	// easier to strip, along with function bodies, so that we can prune
+	// down to just the data that's relevant to go/types.
+	if w.encodingRelocHeader {
+		panic("encodingRelocHeader already true; recursive flush?")
+	}
+	w.encodingRelocHeader = true
+	w.Sync(SyncRelocs)
+	w.Len(len(w.Relocs))
+	for _, rEnt := range w.Relocs {
+		w.Sync(SyncReloc)
+		w.Len(int(rEnt.Kind))
+		w.Len(int(rEnt.Idx))
+	}
+
+	io.Copy(&sb, &w.Data)
+	io.Copy(&sb, &tmp)
+	w.p.elems[w.k][w.Idx] = sb.String()
+
+	return w.Idx
+}
+
+func (w *Encoder) checkErr(err error) {
+	if err != nil {
+		panicf("unexpected encoding error: %v", err)
+	}
+}
+
+func (w *Encoder) rawUvarint(x uint64) {
+	var buf [binary.MaxVarintLen64]byte
+	n := binary.PutUvarint(buf[:], x)
+	_, err := w.Data.Write(buf[:n])
+	w.checkErr(err)
+}
+
+func (w *Encoder) rawVarint(x int64) {
+	// Zig-zag encode.
+	ux := uint64(x) << 1
+	if x < 0 {
+		ux = ^ux
+	}
+
+	w.rawUvarint(ux)
+}
+
+func (w *Encoder) rawReloc(r RelocKind, idx Index) int {
+	e := RelocEnt{r, idx}
+	if w.RelocMap != nil {
+		if i, ok := w.RelocMap[e]; ok {
+			return int(i)
+		}
+	} else {
+		w.RelocMap = make(map[RelocEnt]uint32)
+	}
+
+	i := len(w.Relocs)
+	w.RelocMap[e] = uint32(i)
+	w.Relocs = append(w.Relocs, e)
+	return i
+}
+
+func (w *Encoder) Sync(m SyncMarker) {
+	if !w.p.SyncMarkers() {
+		return
+	}
+
+	// Writing out stack frame string references requires working
+	// relocations, but writing out the relocations themselves involves
+	// sync markers. To prevent infinite recursion, we simply trim the
+	// stack frame for sync markers within the relocation header.
+	var frames []string
+	if !w.encodingRelocHeader && w.p.syncFrames > 0 {
+		pcs := make([]uintptr, w.p.syncFrames)
+		n := runtime.Callers(2, pcs)
+		frames = fmtFrames(pcs[:n]...)
+	}
+
+	// TODO(mdempsky): Save space by writing out stack frames as a
+	// linked list so we can share common stack frames.
+	w.rawUvarint(uint64(m))
+	w.rawUvarint(uint64(len(frames)))
+	for _, frame := range frames {
+		w.rawUvarint(uint64(w.rawReloc(RelocString, w.p.StringIdx(frame))))
+	}
+}
+
+// Bool encodes and writes a bool value into the element bitstream,
+// and then returns the bool value.
+//
+// For simple, 2-alternative encodings, the idiomatic way to call Bool
+// is something like:
+//
+//	if w.Bool(x != 0) {
+//		// alternative #1
+//	} else {
+//		// alternative #2
+//	}
+//
+// For multi-alternative encodings, use Code instead.
+func (w *Encoder) Bool(b bool) bool {
+	w.Sync(SyncBool)
+	var x byte
+	if b {
+		x = 1
+	}
+	err := w.Data.WriteByte(x)
+	w.checkErr(err)
+	return b
+}
+
+// Int64 encodes and writes an int64 value into the element bitstream.
+func (w *Encoder) Int64(x int64) {
+	w.Sync(SyncInt64)
+	w.rawVarint(x)
+}
+
+// Uint64 encodes and writes a uint64 value into the element bitstream.
+func (w *Encoder) Uint64(x uint64) {
+	w.Sync(SyncUint64)
+	w.rawUvarint(x)
+}
+
+// Len encodes and writes a non-negative int value into the element bitstream.
+func (w *Encoder) Len(x int) { assert(x >= 0); w.Uint64(uint64(x)) }
+
+// Int encodes and writes an int value into the element bitstream.
+func (w *Encoder) Int(x int) { w.Int64(int64(x)) }
+
+// Uint encodes and writes a uint value into the element bitstream.
+func (w *Encoder) Uint(x uint) { w.Uint64(uint64(x)) }
+
+// Reloc encodes and writes a relocation for the given (section,
+// index) pair into the element bitstream.
+//
+// Note: Only the index is formally written into the element
+// bitstream, so bitstream decoders must know from context which
+// section an encoded relocation refers to.
+func (w *Encoder) Reloc(r RelocKind, idx Index) {
+	w.Sync(SyncUseReloc)
+	w.Len(w.rawReloc(r, idx))
+}
+
+// Code encodes and writes a Code value into the element bitstream.
+func (w *Encoder) Code(c Code) {
+	w.Sync(c.Marker())
+	w.Len(c.Value())
+}
+
+// String encodes and writes a string value into the element
+// bitstream.
+//
+// Internally, strings are deduplicated by adding them to the strings
+// section (if not already present), and then writing a relocation
+// into the element bitstream.
+func (w *Encoder) String(s string) {
+	w.StringRef(w.p.StringIdx(s))
+}
+
+// StringRef writes a reference to the given index, which must be a
+// previously encoded string value.
+func (w *Encoder) StringRef(idx Index) {
+	w.Sync(SyncString)
+	w.Reloc(RelocString, idx)
+}
+
+// Strings encodes and writes a variable-length slice of strings into
+// the element bitstream.
+func (w *Encoder) Strings(ss []string) {
+	w.Len(len(ss))
+	for _, s := range ss {
+		w.String(s)
+	}
+}
+
+// Value encodes and writes a constant.Value into the element
+// bitstream.
+func (w *Encoder) Value(val constant.Value) {
+	w.Sync(SyncValue)
+	if w.Bool(val.Kind() == constant.Complex) {
+		w.scalar(constant.Real(val))
+		w.scalar(constant.Imag(val))
+	} else {
+		w.scalar(val)
+	}
+}
+
+func (w *Encoder) scalar(val constant.Value) {
+	switch v := constant.Val(val).(type) {
+	default:
+		panicf("unhandled %v (%v)", val, val.Kind())
+	case bool:
+		w.Code(ValBool)
+		w.Bool(v)
+	case string:
+		w.Code(ValString)
+		w.String(v)
+	case int64:
+		w.Code(ValInt64)
+		w.Int64(v)
+	case *big.Int:
+		w.Code(ValBigInt)
+		w.bigInt(v)
+	case *big.Rat:
+		w.Code(ValBigRat)
+		w.bigInt(v.Num())
+		w.bigInt(v.Denom())
+	case *big.Float:
+		w.Code(ValBigFloat)
+		w.bigFloat(v)
+	}
+}
+
+func (w *Encoder) bigInt(v *big.Int) {
+	b := v.Bytes()
+	w.String(string(b)) // TODO: More efficient encoding.
+	w.Bool(v.Sign() < 0)
+}
+
+func (w *Encoder) bigFloat(v *big.Float) {
+	b := v.Append(nil, 'p', -1)
+	w.String(string(b)) // TODO: More efficient encoding.
+}
+
+// Version reports the version of the bitstream.
+func (w *Encoder) Version() Version { return w.p.version }
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/flags.go b/vendor/golang.org/x/tools/internal/pkgbits/flags.go
new file mode 100644
index 000000000..654222745
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/flags.go
@@ -0,0 +1,9 @@
+// Copyright 2022 The Go 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 pkgbits
+
+const (
+	flagSyncMarkers = 1 << iota // file format contains sync markers
+)
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/reloc.go b/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
new file mode 100644
index 000000000..fcdfb97ca
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/reloc.go
@@ -0,0 +1,42 @@
+// Copyright 2021 The Go 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 pkgbits
+
+// A RelocKind indicates a particular section within a unified IR export.
+type RelocKind int32
+
+// An Index represents a bitstream element index within a particular
+// section.
+type Index int32
+
+// A relocEnt (relocation entry) is an entry in an element's local
+// reference table.
+//
+// TODO(mdempsky): Rename this too.
+type RelocEnt struct {
+	Kind RelocKind
+	Idx  Index
+}
+
+// Reserved indices within the meta relocation section.
+const (
+	PublicRootIdx  Index = 0
+	PrivateRootIdx Index = 1
+)
+
+const (
+	RelocString RelocKind = iota
+	RelocMeta
+	RelocPosBase
+	RelocPkg
+	RelocName
+	RelocType
+	RelocObj
+	RelocObjExt
+	RelocObjDict
+	RelocBody
+
+	numRelocs = iota
+)
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/support.go b/vendor/golang.org/x/tools/internal/pkgbits/support.go
new file mode 100644
index 000000000..50534a295
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/support.go
@@ -0,0 +1,17 @@
+// Copyright 2022 The Go 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 pkgbits
+
+import "fmt"
+
+func assert(b bool) {
+	if !b {
+		panic("assertion failed")
+	}
+}
+
+func panicf(format string, args ...any) {
+	panic(fmt.Errorf(format, args...))
+}
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/sync.go b/vendor/golang.org/x/tools/internal/pkgbits/sync.go
new file mode 100644
index 000000000..1520b73af
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/sync.go
@@ -0,0 +1,136 @@
+// Copyright 2021 The Go 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 pkgbits
+
+import (
+	"fmt"
+	"runtime"
+	"strings"
+)
+
+// fmtFrames formats a backtrace for reporting reader/writer desyncs.
+func fmtFrames(pcs ...uintptr) []string {
+	res := make([]string, 0, len(pcs))
+	walkFrames(pcs, func(file string, line int, name string, offset uintptr) {
+		// Trim package from function name. It's just redundant noise.
+		name = strings.TrimPrefix(name, "cmd/compile/internal/noder.")
+
+		res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset))
+	})
+	return res
+}
+
+type frameVisitor func(file string, line int, name string, offset uintptr)
+
+// walkFrames calls visit for each call frame represented by pcs.
+//
+// pcs should be a slice of PCs, as returned by runtime.Callers.
+func walkFrames(pcs []uintptr, visit frameVisitor) {
+	if len(pcs) == 0 {
+		return
+	}
+
+	frames := runtime.CallersFrames(pcs)
+	for {
+		frame, more := frames.Next()
+		visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry)
+		if !more {
+			return
+		}
+	}
+}
+
+// SyncMarker is an enum type that represents markers that may be
+// written to export data to ensure the reader and writer stay
+// synchronized.
+type SyncMarker int
+
+//go:generate stringer -type=SyncMarker -trimprefix=Sync
+
+const (
+	_ SyncMarker = iota
+
+	// Public markers (known to go/types importers).
+
+	// Low-level coding markers.
+	SyncEOF
+	SyncBool
+	SyncInt64
+	SyncUint64
+	SyncString
+	SyncValue
+	SyncVal
+	SyncRelocs
+	SyncReloc
+	SyncUseReloc
+
+	// Higher-level object and type markers.
+	SyncPublic
+	SyncPos
+	SyncPosBase
+	SyncObject
+	SyncObject1
+	SyncPkg
+	SyncPkgDef
+	SyncMethod
+	SyncType
+	SyncTypeIdx
+	SyncTypeParamNames
+	SyncSignature
+	SyncParams
+	SyncParam
+	SyncCodeObj
+	SyncSym
+	SyncLocalIdent
+	SyncSelector
+
+	// Private markers (only known to cmd/compile).
+	SyncPrivate
+
+	SyncFuncExt
+	SyncVarExt
+	SyncTypeExt
+	SyncPragma
+
+	SyncExprList
+	SyncExprs
+	SyncExpr
+	SyncExprType
+	SyncAssign
+	SyncOp
+	SyncFuncLit
+	SyncCompLit
+
+	SyncDecl
+	SyncFuncBody
+	SyncOpenScope
+	SyncCloseScope
+	SyncCloseAnotherScope
+	SyncDeclNames
+	SyncDeclName
+
+	SyncStmts
+	SyncBlockStmt
+	SyncIfStmt
+	SyncForStmt
+	SyncSwitchStmt
+	SyncRangeStmt
+	SyncCaseClause
+	SyncCommClause
+	SyncSelectStmt
+	SyncDecls
+	SyncLabeledStmt
+	SyncUseObjLocal
+	SyncAddLocal
+	SyncLinkname
+	SyncStmt1
+	SyncStmtsEnd
+	SyncLabel
+	SyncOptLabel
+
+	SyncMultiExpr
+	SyncRType
+	SyncConvRTTI
+)
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go b/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
new file mode 100644
index 000000000..582ad56d3
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go
@@ -0,0 +1,92 @@
+// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT.
+
+package pkgbits
+
+import "strconv"
+
+func _() {
+	// An "invalid array index" compiler error signifies that the constant values have changed.
+	// Re-run the stringer command to generate them again.
+	var x [1]struct{}
+	_ = x[SyncEOF-1]
+	_ = x[SyncBool-2]
+	_ = x[SyncInt64-3]
+	_ = x[SyncUint64-4]
+	_ = x[SyncString-5]
+	_ = x[SyncValue-6]
+	_ = x[SyncVal-7]
+	_ = x[SyncRelocs-8]
+	_ = x[SyncReloc-9]
+	_ = x[SyncUseReloc-10]
+	_ = x[SyncPublic-11]
+	_ = x[SyncPos-12]
+	_ = x[SyncPosBase-13]
+	_ = x[SyncObject-14]
+	_ = x[SyncObject1-15]
+	_ = x[SyncPkg-16]
+	_ = x[SyncPkgDef-17]
+	_ = x[SyncMethod-18]
+	_ = x[SyncType-19]
+	_ = x[SyncTypeIdx-20]
+	_ = x[SyncTypeParamNames-21]
+	_ = x[SyncSignature-22]
+	_ = x[SyncParams-23]
+	_ = x[SyncParam-24]
+	_ = x[SyncCodeObj-25]
+	_ = x[SyncSym-26]
+	_ = x[SyncLocalIdent-27]
+	_ = x[SyncSelector-28]
+	_ = x[SyncPrivate-29]
+	_ = x[SyncFuncExt-30]
+	_ = x[SyncVarExt-31]
+	_ = x[SyncTypeExt-32]
+	_ = x[SyncPragma-33]
+	_ = x[SyncExprList-34]
+	_ = x[SyncExprs-35]
+	_ = x[SyncExpr-36]
+	_ = x[SyncExprType-37]
+	_ = x[SyncAssign-38]
+	_ = x[SyncOp-39]
+	_ = x[SyncFuncLit-40]
+	_ = x[SyncCompLit-41]
+	_ = x[SyncDecl-42]
+	_ = x[SyncFuncBody-43]
+	_ = x[SyncOpenScope-44]
+	_ = x[SyncCloseScope-45]
+	_ = x[SyncCloseAnotherScope-46]
+	_ = x[SyncDeclNames-47]
+	_ = x[SyncDeclName-48]
+	_ = x[SyncStmts-49]
+	_ = x[SyncBlockStmt-50]
+	_ = x[SyncIfStmt-51]
+	_ = x[SyncForStmt-52]
+	_ = x[SyncSwitchStmt-53]
+	_ = x[SyncRangeStmt-54]
+	_ = x[SyncCaseClause-55]
+	_ = x[SyncCommClause-56]
+	_ = x[SyncSelectStmt-57]
+	_ = x[SyncDecls-58]
+	_ = x[SyncLabeledStmt-59]
+	_ = x[SyncUseObjLocal-60]
+	_ = x[SyncAddLocal-61]
+	_ = x[SyncLinkname-62]
+	_ = x[SyncStmt1-63]
+	_ = x[SyncStmtsEnd-64]
+	_ = x[SyncLabel-65]
+	_ = x[SyncOptLabel-66]
+	_ = x[SyncMultiExpr-67]
+	_ = x[SyncRType-68]
+	_ = x[SyncConvRTTI-69]
+}
+
+const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI"
+
+var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480}
+
+func (i SyncMarker) String() string {
+	i -= 1
+	if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) {
+		return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")"
+	}
+	return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]]
+}
diff --git a/vendor/golang.org/x/tools/internal/pkgbits/version.go b/vendor/golang.org/x/tools/internal/pkgbits/version.go
new file mode 100644
index 000000000..53af9df22
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/pkgbits/version.go
@@ -0,0 +1,85 @@
+// Copyright 2024 The Go 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 pkgbits
+
+// Version indicates a version of a unified IR bitstream.
+// Each Version indicates the addition, removal, or change of
+// new data in the bitstream.
+//
+// These are serialized to disk and the interpretation remains fixed.
+type Version uint32
+
+const (
+	// V0: initial prototype.
+	//
+	// All data that is not assigned a Field is in version V0
+	// and has not been deprecated.
+	V0 Version = iota
+
+	// V1: adds the Flags uint32 word
+	V1
+
+	// V2: removes unused legacy fields and supports type parameters for aliases.
+	// - remove the legacy "has init" bool from the public root
+	// - remove obj's "derived func instance" bool
+	// - add a TypeParamNames field to ObjAlias
+	// - remove derived info "needed" bool
+	V2
+
+	numVersions = iota
+)
+
+// Field denotes a unit of data in the serialized unified IR bitstream.
+// It is conceptually a like field in a structure.
+//
+// We only really need Fields when the data may or may not be present
+// in a stream based on the Version of the bitstream.
+//
+// Unlike much of pkgbits, Fields are not serialized and
+// can change values as needed.
+type Field int
+
+const (
+	// Flags in a uint32 in the header of a bitstream
+	// that is used to indicate whether optional features are enabled.
+	Flags Field = iota
+
+	// Deprecated: HasInit was a bool indicating whether a package
+	// has any init functions.
+	HasInit
+
+	// Deprecated: DerivedFuncInstance was a bool indicating
+	// whether an object was a function instance.
+	DerivedFuncInstance
+
+	// ObjAlias has a list of TypeParamNames.
+	AliasTypeParamNames
+
+	// Deprecated: DerivedInfoNeeded was a bool indicating
+	// whether a type was a derived type.
+	DerivedInfoNeeded
+
+	numFields = iota
+)
+
+// introduced is the version a field was added.
+var introduced = [numFields]Version{
+	Flags:               V1,
+	AliasTypeParamNames: V2,
+}
+
+// removed is the version a field was removed in or 0 for fields
+// that have not yet been deprecated.
+// (So removed[f]-1 is the last version it is included in.)
+var removed = [numFields]Version{
+	HasInit:             V2,
+	DerivedFuncInstance: V2,
+	DerivedInfoNeeded:   V2,
+}
+
+// Has reports whether field f is present in a bitstream at version v.
+func (v Version) Has(f Field) bool {
+	return introduced[f] <= v && (v < removed[f] || removed[f] == V0)
+}
diff --git a/vendor/golang.org/x/tools/internal/stdlib/deps.go b/vendor/golang.org/x/tools/internal/stdlib/deps.go
new file mode 100644
index 000000000..c50bf406b
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/stdlib/deps.go
@@ -0,0 +1,359 @@
+// Copyright 2025 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Code generated by generate.go. DO NOT EDIT.
+
+package stdlib
+
+type pkginfo struct {
+	name string
+	deps string // list of indices of dependencies, as varint-encoded deltas
+}
+
+var deps = [...]pkginfo{
+	{"archive/tar", "\x03j\x03E6\x01\v\x01\"\x01\x01\x02\x05\n\x02\x01\x02\x02\v"},
+	{"archive/zip", "\x02\x04`\a\x16\x0206\x01*\x05\x01\x11\x03\x02\r\x04"},
+	{"bufio", "\x03j~E\x13"},
+	{"bytes", "m+S\x03\fG\x02\x02"},
+	{"cmp", ""},
+	{"compress/bzip2", "\x02\x02\xe7\x01B"},
+	{"compress/flate", "\x02k\x03{\r\x024\x01\x03"},
+	{"compress/gzip", "\x02\x04`\a\x03\x15fT"},
+	{"compress/lzw", "\x02k\x03{"},
+	{"compress/zlib", "\x02\x04`\a\x03\x13\x01g"},
+	{"container/heap", "\xae\x02"},
+	{"container/list", ""},
+	{"container/ring", ""},
+	{"context", "m\\i\x01\f"},
+	{"crypto", "\x83\x01hD"},
+	{"crypto/aes", "\x10\n\a\x8e\x02"},
+	{"crypto/cipher", "\x03\x1e\x01\x01\x1d\x11\x1c,R"},
+	{"crypto/des", "\x10\x13\x1d-,\x96\x01\x03"},
+	{"crypto/dsa", "@\x04)~\x0e"},
+	{"crypto/ecdh", "\x03\v\f\x0e\x04\x14\x04\r\x1c~"},
+	{"crypto/ecdsa", "\x0e\x05\x03\x04\x01\x0e\x16\x01\x04\f\x01\x1c~\x0e\x04K\x01"},
+	{"crypto/ed25519", "\x0e\x1c\x16\n\a\x1c~D"},
+	{"crypto/elliptic", "0=~\x0e9"},
+	{"crypto/fips140", " \x05\x90\x01"},
+	{"crypto/hkdf", "-\x12\x01-\x16"},
+	{"crypto/hmac", "\x1a\x14\x11\x01\x112"},
+	{"crypto/internal/boring", "\x0e\x02\rf"},
+	{"crypto/internal/boring/bbig", "\x1a\xdf\x01L"},
+	{"crypto/internal/boring/bcache", "\xb3\x02\x12"},
+	{"crypto/internal/boring/sig", ""},
+	{"crypto/internal/cryptotest", "\x03\r\n)\x0e\x19\x06\x13\x12#\a\t\x11\x12\x11\x1a\r\r\x05\n"},
+	{"crypto/internal/entropy", "E"},
+	{"crypto/internal/fips140", ">/~8\r\x15"},
+	{"crypto/internal/fips140/aes", "\x03\x1d\x03\x02\x13\x04\x01\x01\x05*\x8d\x015"},
+	{"crypto/internal/fips140/aes/gcm", " \x01\x02\x02\x02\x11\x04\x01\x06*\x8b\x01"},
+	{"crypto/internal/fips140/alias", "\xc5\x02"},
+	{"crypto/internal/fips140/bigmod", "%\x17\x01\x06*\x8d\x01"},
+	{"crypto/internal/fips140/check", " \x0e\x06\b\x02\xad\x01Z"},
+	{"crypto/internal/fips140/check/checktest", "%\xfe\x01\""},
+	{"crypto/internal/fips140/drbg", "\x03\x1c\x01\x01\x04\x13\x04\b\x01(~\x0f8"},
+	{"crypto/internal/fips140/ecdh", "\x03\x1d\x05\x02\t\f1~\x0f8"},
+	{"crypto/internal/fips140/ecdsa", "\x03\x1d\x04\x01\x02\a\x02\x067~G"},
+	{"crypto/internal/fips140/ed25519", "\x03\x1d\x05\x02\x04\v7\xc2\x01\x03"},
+	{"crypto/internal/fips140/edwards25519", "%\a\f\x041\x8d\x018"},
+	{"crypto/internal/fips140/edwards25519/field", "%\x13\x041\x8d\x01"},
+	{"crypto/internal/fips140/hkdf", "\x03\x1d\x05\t\x069"},
+	{"crypto/internal/fips140/hmac", "\x03\x1d\x14\x01\x017"},
+	{"crypto/internal/fips140/mlkem", "\x03\x1d\x05\x02\x0e\x03\x041"},
+	{"crypto/internal/fips140/nistec", "%\f\a\x041\x8d\x01)\x0f\x13"},
+	{"crypto/internal/fips140/nistec/fiat", "%\x135\x8d\x01"},
+	{"crypto/internal/fips140/pbkdf2", "\x03\x1d\x05\t\x069"},
+	{"crypto/internal/fips140/rsa", "\x03\x1d\x04\x01\x02\r\x01\x01\x025~G"},
+	{"crypto/internal/fips140/sha256", "\x03\x1d\x1c\x01\x06*\x8d\x01"},
+	{"crypto/internal/fips140/sha3", "\x03\x1d\x18\x04\x010\x8d\x01K"},
+	{"crypto/internal/fips140/sha512", "\x03\x1d\x1c\x01\x06*\x8d\x01"},
+	{"crypto/internal/fips140/ssh", " \x05"},
+	{"crypto/internal/fips140/subtle", "#"},
+	{"crypto/internal/fips140/tls12", "\x03\x1d\x05\t\x06\x027"},
+	{"crypto/internal/fips140/tls13", "\x03\x1d\x05\b\a\b1"},
+	{"crypto/internal/fips140deps", ""},
+	{"crypto/internal/fips140deps/byteorder", "\x99\x01"},
+	{"crypto/internal/fips140deps/cpu", "\xad\x01\a"},
+	{"crypto/internal/fips140deps/godebug", "\xb5\x01"},
+	{"crypto/internal/fips140hash", "5\x1a4\xc2\x01"},
+	{"crypto/internal/fips140only", "'\r\x01\x01M26"},
+	{"crypto/internal/fips140test", ""},
+	{"crypto/internal/hpke", "\x0e\x01\x01\x03\x1a\x1d#,aM"},
+	{"crypto/internal/impl", "\xb0\x02"},
+	{"crypto/internal/randutil", "\xeb\x01\x12"},
+	{"crypto/internal/sysrand", "mi\"\x1e\r\x0f\x01\x01\v\x06"},
+	{"crypto/internal/sysrand/internal/seccomp", "m"},
+	{"crypto/md5", "\x0e2-\x16\x16a"},
+	{"crypto/mlkem", "/"},
+	{"crypto/pbkdf2", "2\r\x01-\x16"},
+	{"crypto/rand", "\x1a\x06\a\x19\x04\x01(~\x0eL"},
+	{"crypto/rc4", "#\x1d-\xc2\x01"},
+	{"crypto/rsa", "\x0e\f\x01\t\x0f\f\x01\x04\x06\a\x1c\x03\x1326\r\x01"},
+	{"crypto/sha1", "\x0e\f&-\x16\x16\x14M"},
+	{"crypto/sha256", "\x0e\f\x1aO"},
+	{"crypto/sha3", "\x0e'N\xc2\x01"},
+	{"crypto/sha512", "\x0e\f\x1cM"},
+	{"crypto/subtle", "8\x96\x01U"},
+	{"crypto/tls", "\x03\b\x02\x01\x01\x01\x01\x02\x01\x01\x01\x03\x01\a\x01\v\x02\n\x01\b\x05\x03\x01\x01\x01\x01\x02\x01\x02\x01\x17\x02\x03\x13\x16\x14\b6\x16\x15\r\n\x01\x01\x01\x02\x01\f\x06\x02\x01"},
+	{"crypto/tls/internal/fips140tls", " \x93\x02"},
+	{"crypto/x509", "\x03\v\x01\x01\x01\x01\x01\x01\x01\x011\x03\x02\x01\x01\x02\x05\x0e\x06\x02\x02\x03E\x033\x01\x02\t\x01\x01\x01\a\x0f\x05\x01\x06\x02\x05\f\x01\x02\r\x02\x01\x01\x02\x03\x01"},
+	{"crypto/x509/pkix", "c\x06\a\x89\x01F"},
+	{"database/sql", "\x03\nJ\x16\x03{\f\x06!\x05\n\x02\x03\x01\f\x02\x02\x02"},
+	{"database/sql/driver", "\r`\x03\xae\x01\x11\x10"},
+	{"debug/buildinfo", "\x03W\x02\x01\x01\b\a\x03`\x19\x02\x01*\x0f "},
+	{"debug/dwarf", "\x03c\a\x03{0\x13\x01\x01"},
+	{"debug/elf", "\x03\x06P\r\a\x03`\x1a\x01+\x19\x01\x15"},
+	{"debug/gosym", "\x03c\n\xbe\x01\x01\x01\x02"},
+	{"debug/macho", "\x03\x06P\r\n`\x1b+\x19\x01"},
+	{"debug/pe", "\x03\x06P\r\a\x03`\x1b+\x19\x01\x15"},
+	{"debug/plan9obj", "f\a\x03`\x1b+"},
+	{"embed", "m+:\x19\x01S"},
+	{"embed/internal/embedtest", ""},
+	{"encoding", ""},
+	{"encoding/ascii85", "\xeb\x01D"},
+	{"encoding/asn1", "\x03j\x03\x88\x01\x01%\x0f\x02\x01\x0f\x03\x01"},
+	{"encoding/base32", "\xeb\x01B\x02"},
+	{"encoding/base64", "f\x85\x01B\x02"},
+	{"encoding/binary", "m~\r&\x0f\x05"},
+	{"encoding/csv", "\x02\x01j\x03{E\x11\x02"},
+	{"encoding/gob", "\x02_\x05\a\x03`\x1b\f\x01\x02\x1c\b\x14\x01\x0e\x02"},
+	{"encoding/hex", "m\x03{B\x03"},
+	{"encoding/json", "\x03\x01]\x04\b\x03{\r&\x0f\x02\x01\x02\x0f\x01\x01\x02"},
+	{"encoding/pem", "\x03b\b~B\x03"},
+	{"encoding/xml", "\x02\x01^\f\x03{3\x05\f\x01\x02\x0f\x02"},
+	{"errors", "\xc9\x01|"},
+	{"expvar", "jK:\t\n\x14\r\n\x02\x03\x01\x10"},
+	{"flag", "a\f\x03{+\b\x05\n\x02\x01\x0f"},
+	{"fmt", "mE9\r\x1e\b\x0f\x02\x03\x11"},
+	{"go/ast", "\x03\x01l\x0f\x01k\x03(\b\x0f\x02\x01"},
+	{"go/ast/internal/tests", ""},
+	{"go/build", "\x02\x01j\x03\x01\x03\x02\a\x02\x01\x17\x1e\x04\x02\t\x14\x13\x01*\x01\x04\x01\a\n\x02\x01\x11\x02\x02"},
+	{"go/build/constraint", "m\xc2\x01\x01\x11\x02"},
+	{"go/constant", "p\x10x\x01\x015\x01\x02\x11"},
+	{"go/doc", "\x04l\x01\x06\t=.0\x12\x02\x01\x11\x02"},
+	{"go/doc/comment", "\x03m\xbd\x01\x01\x01\x01\x11\x02"},
+	{"go/format", "\x03m\x01\f\x01\x02kE"},
+	{"go/importer", "s\a\x01\x01\x04\x01j8"},
+	{"go/internal/gccgoimporter", "\x02\x01W\x13\x03\x05\v\x01h\x02+\x01\x05\x13\x01\v\b"},
+	{"go/internal/gcimporter", "\x02n\x10\x01/\x05\x0e(+\x17\x03\x02"},
+	{"go/internal/srcimporter", "p\x01\x02\n\x03\x01j+\x01\x05\x14\x02\x13"},
+	{"go/parser", "\x03j\x03\x01\x03\v\x01k\x01*\x06\x14"},
+	{"go/printer", "p\x01\x03\x03\tk\r\x1e\x17\x02\x01\x02\n\x05\x02"},
+	{"go/scanner", "\x03m\x10k1\x12\x01\x12\x02"},
+	{"go/token", "\x04l\xbd\x01\x02\x03\x01\x0e\x02"},
+	{"go/types", "\x03\x01\x06c\x03\x01\x04\b\x03\x02\x15\x1e\x06,\x04\x03\n$\a\n\x01\x01\x01\x02\x01\x0e\x02\x02"},
+	{"go/version", "\xba\x01v"},
+	{"hash", "\xeb\x01"},
+	{"hash/adler32", "m\x16\x16"},
+	{"hash/crc32", "m\x16\x16\x14\x85\x01\x01\x12"},
+	{"hash/crc64", "m\x16\x16\x99\x01"},
+	{"hash/fnv", "m\x16\x16a"},
+	{"hash/maphash", "\x94\x01\x05\x1b\x03AM"},
+	{"html", "\xb0\x02\x02\x11"},
+	{"html/template", "\x03g\x06\x19,6\x01\v\x1f\x05\x01\x02\x03\x0e\x01\x02\v\x01\x03\x02"},
+	{"image", "\x02k\x1f_\x0f5\x03\x01"},
+	{"image/color", ""},
+	{"image/color/palette", "\x8c\x01"},
+	{"image/draw", "\x8b\x01\x01\x04"},
+	{"image/gif", "\x02\x01\x05e\x03\x1b\x01\x01\x01\vR"},
+	{"image/internal/imageutil", "\x8b\x01"},
+	{"image/jpeg", "\x02k\x1e\x01\x04["},
+	{"image/png", "\x02\a]\n\x13\x02\x06\x01_D"},
+	{"index/suffixarray", "\x03c\a~\r)\f\x01"},
+	{"internal/abi", "\xb4\x01\x91\x01"},
+	{"internal/asan", "\xc5\x02"},
+	{"internal/bisect", "\xa3\x02\x0f\x01"},
+	{"internal/buildcfg", "pG_\x06\x02\x05\f\x01"},
+	{"internal/bytealg", "\xad\x01\x98\x01"},
+	{"internal/byteorder", ""},
+	{"internal/cfg", ""},
+	{"internal/chacha8rand", "\x99\x01\x1b\x91\x01"},
+	{"internal/copyright", ""},
+	{"internal/coverage", ""},
+	{"internal/coverage/calloc", ""},
+	{"internal/coverage/cfile", "j\x06\x17\x16\x01\x02\x01\x01\x01\x01\x01\x01\x01#\x01 +\x06\a\f\x01\x03\f\x06"},
+	{"internal/coverage/cformat", "\x04l-\x04J\f6\x01\x02\f"},
+	{"internal/coverage/cmerge", "p-["},
+	{"internal/coverage/decodecounter", "f\n-\v\x02A+\x19\x16"},
+	{"internal/coverage/decodemeta", "\x02d\n\x17\x16\v\x02A+"},
+	{"internal/coverage/encodecounter", "\x02d\n-\f\x01\x02?\f\x1f\x17"},
+	{"internal/coverage/encodemeta", "\x02\x01c\n\x13\x04\x16\r\x02?+/"},
+	{"internal/coverage/pods", "\x04l-y\x06\x05\f\x02\x01"},
+	{"internal/coverage/rtcov", "\xc5\x02"},
+	{"internal/coverage/slicereader", "f\n{Z"},
+	{"internal/coverage/slicewriter", "p{"},
+	{"internal/coverage/stringtab", "p8\x04?"},
+	{"internal/coverage/test", ""},
+	{"internal/coverage/uleb128", ""},
+	{"internal/cpu", "\xc5\x02"},
+	{"internal/dag", "\x04l\xbd\x01\x03"},
+	{"internal/diff", "\x03m\xbe\x01\x02"},
+	{"internal/exportdata", "\x02\x01j\x03\x03]\x1b+\x01\x05\x13\x01\x02"},
+	{"internal/filepathlite", "m+:\x1aA"},
+	{"internal/fmtsort", "\x04\x9a\x02\x0f"},
+	{"internal/fuzz", "\x03\nA\x18\x04\x03\x03\x01\f\x0356\r\x02\x1c\x01\x05\x02\x05\f\x01\x02\x01\x01\v\x04\x02"},
+	{"internal/goarch", ""},
+	{"internal/godebug", "\x96\x01 |\x01\x12"},
+	{"internal/godebugs", ""},
+	{"internal/goexperiment", ""},
+	{"internal/goos", ""},
+	{"internal/goroot", "\x96\x02\x01\x05\x14\x02"},
+	{"internal/gover", "\x04"},
+	{"internal/goversion", ""},
+	{"internal/itoa", ""},
+	{"internal/lazyregexp", "\x96\x02\v\x0f\x02"},
+	{"internal/lazytemplate", "\xeb\x01+\x1a\x02\v"},
+	{"internal/msan", "\xc5\x02"},
+	{"internal/nettrace", ""},
+	{"internal/obscuretestdata", "e\x86\x01+"},
+	{"internal/oserror", "m"},
+	{"internal/pkgbits", "\x03K\x18\a\x03\x05\vk\x0e\x1d\r\f\x01"},
+	{"internal/platform", ""},
+	{"internal/poll", "mO\x1a\x158\x0f\x01\x01\v\x06"},
+	{"internal/profile", "\x03\x04f\x03{6\r\x01\x01\x0f"},
+	{"internal/profilerecord", ""},
+	{"internal/race", "\x94\x01\xb1\x01"},
+	{"internal/reflectlite", "\x94\x01 4;\""},
+	{"internal/runtime/atomic", "\xc5\x02"},
+	{"internal/runtime/exithook", "\xca\x01{"},
+	{"internal/runtime/maps", "\x94\x01\x01\x1f\v\t\x05\x01w"},
+	{"internal/runtime/math", "\xb4\x01"},
+	{"internal/runtime/sys", "\xb4\x01\x04"},
+	{"internal/runtime/syscall", "\xc5\x02"},
+	{"internal/saferio", "\xeb\x01Z"},
+	{"internal/singleflight", "\xb2\x02"},
+	{"internal/stringslite", "\x98\x01\xad\x01"},
+	{"internal/sync", "\x94\x01 \x14k\x12"},
+	{"internal/synctest", "\xc5\x02"},
+	{"internal/syscall/execenv", "\xb4\x02"},
+	{"internal/syscall/unix", "\xa3\x02\x10\x01\x11"},
+	{"internal/sysinfo", "\x02\x01\xaa\x01>+\x1a\x02"},
+	{"internal/syslist", ""},
+	{"internal/testenv", "\x03\n`\x02\x01*\x1a\x10(*\x01\x05\a\f\x01\x02\x02\x01\n"},
+	{"internal/testlog", "\xb2\x02\x01\x12"},
+	{"internal/testpty", "m\x03\xa6\x01"},
+	{"internal/trace", "\x02\x01\x01\x06\\\a\x03m\x01\x01\x06\x06\x03\n5\x01\x02\x0f"},
+	{"internal/trace/event", ""},
+	{"internal/trace/event/go122", "pm"},
+	{"internal/trace/internal/oldtrace", "\x03\x01b\a\x03m\b\x06\r5\x01"},
+	{"internal/trace/internal/testgen/go122", "\x03c\nl\x01\x01\x03\x04\x010\v\x0f"},
+	{"internal/trace/raw", "\x02d\nm\b\x06D\x01\x11"},
+	{"internal/trace/testtrace", "\x02\x01j\x03l\x05\x05\x056\f\x02\x01"},
+	{"internal/trace/traceviewer", "\x02]\v\x06\x1a<\x16\b\a\x04\t\n\x14\x01\x05\a\f\x01\x02\r"},
+	{"internal/trace/traceviewer/format", ""},
+	{"internal/trace/version", "pm\x01\r"},
+	{"internal/txtar", "\x03m\xa6\x01\x1a"},
+	{"internal/types/errors", "\xaf\x02"},
+	{"internal/unsafeheader", "\xc5\x02"},
+	{"internal/xcoff", "Y\r\a\x03`\x1b+\x19\x01"},
+	{"internal/zstd", "f\a\x03{\x0f"},
+	{"io", "m\xc5\x01"},
+	{"io/fs", "m+*)0\x12\x12\x04"},
+	{"io/ioutil", "\xeb\x01\x01*\x17\x03"},
+	{"iter", "\xc8\x01[\""},
+	{"log", "p{\x05&\r\x0f\x01\f"},
+	{"log/internal", ""},
+	{"log/slog", "\x03\nT\t\x03\x03{\x04\x01\x02\x02\x04&\x05\n\x02\x01\x02\x01\f\x02\x02\x02"},
+	{"log/slog/internal", ""},
+	{"log/slog/internal/benchmarks", "\r`\x03{\x06\x03;\x10"},
+	{"log/slog/internal/buffer", "\xb2\x02"},
+	{"log/slog/internal/slogtest", "\xf1\x01"},
+	{"log/syslog", "m\x03\x7f\x12\x15\x1a\x02\r"},
+	{"maps", "\xee\x01W"},
+	{"math", "\xad\x01MK"},
+	{"math/big", "\x03j\x03)\x14>\r\x02\x023\x01\x02\x13"},
+	{"math/bits", "\xc5\x02"},
+	{"math/cmplx", "\xf8\x01\x02"},
+	{"math/rand", "\xb5\x01C:\x01\x12"},
+	{"math/rand/v2", "m,\x02]\x02K"},
+	{"mime", "\x02\x01b\b\x03{\f\x1f\x17\x03\x02\x0f\x02"},
+	{"mime/multipart", "\x02\x01G#\x03E6\f\x01\x06\x02\x14\x02\x06\x11\x02\x01\x15"},
+	{"mime/quotedprintable", "\x02\x01m{"},
+	{"net", "\x04\t`+\x1d\a\x04\x05\f\x01\x04\x15\x01$\x06\r\n\x05\x01\x01\v\x06\a"},
+	{"net/http", "\x02\x01\x04\x04\x02=\b\x13\x01\a\x03E6\x01\x03\b\x01\x02\x02\x02\x01\x02\x06\x02\x01\n\x01\x01\x05\x01\x02\x05\n\x01\x01\x01\x02\x01\f\x02\x02\x02\b\x01\x01\x01"},
+	{"net/http/cgi", "\x02P\x1b\x03{\x04\b\n\x01\x12\x01\x01\x01\x04\x01\x05\x02\n\x02\x01\x0f\x0e"},
+	{"net/http/cookiejar", "\x04i\x03\x91\x01\x01\b\v\x18\x03\x02\r\x04"},
+	{"net/http/fcgi", "\x02\x01\nY\a\x03{\x16\x01\x01\x13\x1a\x02\r"},
+	{"net/http/httptest", "\x02\x01\nE\x02\x1b\x01{\x04\x12\x01\t\t\x02\x19\x01\x02\r\x0e"},
+	{"net/http/httptrace", "\rEnA\x13\n!"},
+	{"net/http/httputil", "\x02\x01\n`\x03{\x04\x0f\x03\x01\x05\x02\x01\n\x01\x1b\x02\r\x0e"},
+	{"net/http/internal", "\x02\x01j\x03{"},
+	{"net/http/internal/ascii", "\xb0\x02\x11"},
+	{"net/http/internal/testcert", "\xb0\x02"},
+	{"net/http/pprof", "\x02\x01\nc\x19,\x11%\x04\x13\x13\x01\r\x06\x03\x01\x02\x01\x0f"},
+	{"net/internal/cgotest", ""},
+	{"net/internal/socktest", "p\xc2\x01\x02"},
+	{"net/mail", "\x02k\x03{\x04\x0f\x03\x13\x1c\x02\r\x04"},
+	{"net/netip", "\x04i+\x01#<\x025\x15"},
+	{"net/rpc", "\x02f\x05\x03\x10\na\x04\x12\x01\x1c\x0f\x03\x02"},
+	{"net/rpc/jsonrpc", "j\x03\x03{\x16\x10!"},
+	{"net/smtp", "\x19.\v\x13\b\x03{\x16\x13\x1c"},
+	{"net/textproto", "\x02\x01j\x03{\r\t.\x01\x02\x13"},
+	{"net/url", "m\x03\x87\x01$\x12\x02\x01\x15"},
+	{"os", "m+\x01\x18\x03\b\t\r\x03\x01\x04\x11\x017\n\x05\x01\x01\v\x06"},
+	{"os/exec", "\x03\n`H \x01\x15\x01*\x06\a\f\x01\x04\v"},
+	{"os/exec/internal/fdtest", "\xb4\x02"},
+	{"os/signal", "\r\x89\x02\x17\x05\x02"},
+	{"os/user", "\x02\x01j\x03{+\r\f\x01\x02"},
+	{"path", "m+\xab\x01"},
+	{"path/filepath", "m+\x19;*\r\n\x03\x04\x0f"},
+	{"plugin", "m"},
+	{"reflect", "m'\x04\x1c\b\f\x04\x02\x1a\x06\n+\f\x03\x0f\x02\x02"},
+	{"reflect/internal/example1", ""},
+	{"reflect/internal/example2", ""},
+	{"regexp", "\x03\xe8\x017\v\x02\x01\x02\x0f\x02"},
+	{"regexp/syntax", "\xad\x02\x01\x01\x01\x11\x02"},
+	{"runtime", "\x94\x01\x04\x01\x02\f\x06\a\x02\x01\x01\x0f\x03\x01\x01\x01\x01\x01\x03s"},
+	{"runtime/coverage", "\x9f\x01L"},
+	{"runtime/debug", "pUQ\r\n\x02\x01\x0f\x06"},
+	{"runtime/internal/startlinetest", ""},
+	{"runtime/internal/wasitest", ""},
+	{"runtime/metrics", "\xb6\x01B+\""},
+	{"runtime/pprof", "\x02\x01\x01\x03\x06Y\a\x03$3$\r\x1e\r\n\x01\x01\x01\x02\x02\b\x03\x06"},
+	{"runtime/race", "\xab\x02"},
+	{"runtime/race/internal/amd64v1", ""},
+	{"runtime/trace", "\rc{8\x0f\x01\x12"},
+	{"slices", "\x04\xea\x01\fK"},
+	{"sort", "\xc9\x0113"},
+	{"strconv", "m+:&\x02I"},
+	{"strings", "m'\x04:\x19\x03\f8\x0f\x02\x02"},
+	{"structs", ""},
+	{"sync", "\xc8\x01\vP\x10\x12"},
+	{"sync/atomic", "\xc5\x02"},
+	{"syscall", "m(\x03\x01\x1b\b\x03\x03\x06\aT\x0f\x01\x12"},
+	{"testing", "\x03\n`\x02\x01G\x11\x0f\x14\r\x04\x1a\x06\x02\x05\x02\a\x01\x02\x01\x02\x01\f\x02\x02\x02"},
+	{"testing/fstest", "m\x03{\x01\v$\x12\x03\b\a"},
+	{"testing/internal/testdeps", "\x02\v\xa6\x01'\x11+\x03\x05\x03\b\a\x02\r"},
+	{"testing/iotest", "\x03j\x03{\x04"},
+	{"testing/quick", "o\x01\x88\x01\x04\"\x12\x0f"},
+	{"testing/slogtest", "\r`\x03\x81\x01-\x05\x12\n"},
+	{"text/scanner", "\x03m{++\x02"},
+	{"text/tabwriter", "p{X"},
+	{"text/template", "m\x03B9\x01\v\x1e\x01\x05\x01\x02\x05\r\x02\f\x03\x02"},
+	{"text/template/parse", "\x03m\xb3\x01\f\x01\x11\x02"},
+	{"time", "m+\x1d\x1d()\x0f\x02\x11"},
+	{"time/tzdata", "m\xc7\x01\x11"},
+	{"unicode", ""},
+	{"unicode/utf16", ""},
+	{"unicode/utf8", ""},
+	{"unique", "\x94\x01>\x01P\x0f\x13\x12"},
+	{"unsafe", ""},
+	{"vendor/golang.org/x/crypto/chacha20", "\x10V\a\x8d\x01)'"},
+	{"vendor/golang.org/x/crypto/chacha20poly1305", "\x10V\a\xd9\x01\x04\x01\a"},
+	{"vendor/golang.org/x/crypto/cryptobyte", "c\n\x03\x89\x01%!\n"},
+	{"vendor/golang.org/x/crypto/cryptobyte/asn1", ""},
+	{"vendor/golang.org/x/crypto/internal/alias", "\xc5\x02"},
+	{"vendor/golang.org/x/crypto/internal/poly1305", "Q\x15\x94\x01"},
+	{"vendor/golang.org/x/net/dns/dnsmessage", "m"},
+	{"vendor/golang.org/x/net/http/httpguts", "\x81\x02\x13\x1c\x13\r"},
+	{"vendor/golang.org/x/net/http/httpproxy", "m\x03\x91\x01\x0f\x05\x01\x1a\x13\r"},
+	{"vendor/golang.org/x/net/http2/hpack", "\x03j\x03{G"},
+	{"vendor/golang.org/x/net/idna", "p\x88\x018\x13\x10\x02\x01"},
+	{"vendor/golang.org/x/net/nettest", "\x03c\a\x03{\x11\x05\x15\x01\f\f\x01\x02\x02\x01\n"},
+	{"vendor/golang.org/x/sys/cpu", "\x96\x02\r\f\x01\x15"},
+	{"vendor/golang.org/x/text/secure/bidirule", "m\xd6\x01\x11\x01"},
+	{"vendor/golang.org/x/text/transform", "\x03j~X"},
+	{"vendor/golang.org/x/text/unicode/bidi", "\x03\be\x7f?\x15"},
+	{"vendor/golang.org/x/text/unicode/norm", "f\n{G\x11\x11"},
+	{"weak", "\x94\x01\x8f\x01\""},
+}
diff --git a/vendor/golang.org/x/tools/internal/stdlib/import.go b/vendor/golang.org/x/tools/internal/stdlib/import.go
new file mode 100644
index 000000000..f6909878a
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/stdlib/import.go
@@ -0,0 +1,89 @@
+// Copyright 2025 The Go 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 stdlib
+
+// This file provides the API for the import graph of the standard library.
+//
+// Be aware that the compiler-generated code for every package
+// implicitly depends on package "runtime" and a handful of others
+// (see runtimePkgs in GOROOT/src/cmd/internal/objabi/pkgspecial.go).
+
+import (
+	"encoding/binary"
+	"iter"
+	"slices"
+	"strings"
+)
+
+// Imports returns the sequence of packages directly imported by the
+// named standard packages, in name order.
+// The imports of an unknown package are the empty set.
+//
+// The graph is built into the application and may differ from the
+// graph in the Go source tree being analyzed by the application.
+func Imports(pkgs ...string) iter.Seq[string] {
+	return func(yield func(string) bool) {
+		for _, pkg := range pkgs {
+			if i, ok := find(pkg); ok {
+				var depIndex uint64
+				for data := []byte(deps[i].deps); len(data) > 0; {
+					delta, n := binary.Uvarint(data)
+					depIndex += delta
+					if !yield(deps[depIndex].name) {
+						return
+					}
+					data = data[n:]
+				}
+			}
+		}
+	}
+}
+
+// Dependencies returns the set of all dependencies of the named
+// standard packages, including the initial package,
+// in a deterministic topological order.
+// The dependencies of an unknown package are the empty set.
+//
+// The graph is built into the application and may differ from the
+// graph in the Go source tree being analyzed by the application.
+func Dependencies(pkgs ...string) iter.Seq[string] {
+	return func(yield func(string) bool) {
+		for _, pkg := range pkgs {
+			if i, ok := find(pkg); ok {
+				var seen [1 + len(deps)/8]byte // bit set of seen packages
+				var visit func(i int) bool
+				visit = func(i int) bool {
+					bit := byte(1) << (i % 8)
+					if seen[i/8]&bit == 0 {
+						seen[i/8] |= bit
+						var depIndex uint64
+						for data := []byte(deps[i].deps); len(data) > 0; {
+							delta, n := binary.Uvarint(data)
+							depIndex += delta
+							if !visit(int(depIndex)) {
+								return false
+							}
+							data = data[n:]
+						}
+						if !yield(deps[i].name) {
+							return false
+						}
+					}
+					return true
+				}
+				if !visit(i) {
+					return
+				}
+			}
+		}
+	}
+}
+
+// find returns the index of pkg in the deps table.
+func find(pkg string) (int, bool) {
+	return slices.BinarySearchFunc(deps[:], pkg, func(p pkginfo, n string) int {
+		return strings.Compare(p.name, n)
+	})
+}
diff --git a/vendor/golang.org/x/tools/internal/stdlib/manifest.go b/vendor/golang.org/x/tools/internal/stdlib/manifest.go
new file mode 100644
index 000000000..2b418796a
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/stdlib/manifest.go
@@ -0,0 +1,17647 @@
+// Copyright 2025 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Code generated by generate.go. DO NOT EDIT.
+
+package stdlib
+
+var PackageSymbols = map[string][]Symbol{
+	"archive/tar": {
+		{"(*Header).FileInfo", Method, 1},
+		{"(*Reader).Next", Method, 0},
+		{"(*Reader).Read", Method, 0},
+		{"(*Writer).AddFS", Method, 22},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).Write", Method, 0},
+		{"(*Writer).WriteHeader", Method, 0},
+		{"(Format).String", Method, 10},
+		{"ErrFieldTooLong", Var, 0},
+		{"ErrHeader", Var, 0},
+		{"ErrInsecurePath", Var, 20},
+		{"ErrWriteAfterClose", Var, 0},
+		{"ErrWriteTooLong", Var, 0},
+		{"FileInfoHeader", Func, 1},
+		{"FileInfoNames", Type, 23},
+		{"Format", Type, 10},
+		{"FormatGNU", Const, 10},
+		{"FormatPAX", Const, 10},
+		{"FormatUSTAR", Const, 10},
+		{"FormatUnknown", Const, 10},
+		{"Header", Type, 0},
+		{"Header.AccessTime", Field, 0},
+		{"Header.ChangeTime", Field, 0},
+		{"Header.Devmajor", Field, 0},
+		{"Header.Devminor", Field, 0},
+		{"Header.Format", Field, 10},
+		{"Header.Gid", Field, 0},
+		{"Header.Gname", Field, 0},
+		{"Header.Linkname", Field, 0},
+		{"Header.ModTime", Field, 0},
+		{"Header.Mode", Field, 0},
+		{"Header.Name", Field, 0},
+		{"Header.PAXRecords", Field, 10},
+		{"Header.Size", Field, 0},
+		{"Header.Typeflag", Field, 0},
+		{"Header.Uid", Field, 0},
+		{"Header.Uname", Field, 0},
+		{"Header.Xattrs", Field, 3},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"Reader", Type, 0},
+		{"TypeBlock", Const, 0},
+		{"TypeChar", Const, 0},
+		{"TypeCont", Const, 0},
+		{"TypeDir", Const, 0},
+		{"TypeFifo", Const, 0},
+		{"TypeGNULongLink", Const, 1},
+		{"TypeGNULongName", Const, 1},
+		{"TypeGNUSparse", Const, 3},
+		{"TypeLink", Const, 0},
+		{"TypeReg", Const, 0},
+		{"TypeRegA", Const, 0},
+		{"TypeSymlink", Const, 0},
+		{"TypeXGlobalHeader", Const, 0},
+		{"TypeXHeader", Const, 0},
+		{"Writer", Type, 0},
+	},
+	"archive/zip": {
+		{"(*File).DataOffset", Method, 2},
+		{"(*File).FileInfo", Method, 0},
+		{"(*File).ModTime", Method, 0},
+		{"(*File).Mode", Method, 0},
+		{"(*File).Open", Method, 0},
+		{"(*File).OpenRaw", Method, 17},
+		{"(*File).SetModTime", Method, 0},
+		{"(*File).SetMode", Method, 0},
+		{"(*FileHeader).FileInfo", Method, 0},
+		{"(*FileHeader).ModTime", Method, 0},
+		{"(*FileHeader).Mode", Method, 0},
+		{"(*FileHeader).SetModTime", Method, 0},
+		{"(*FileHeader).SetMode", Method, 0},
+		{"(*ReadCloser).Close", Method, 0},
+		{"(*ReadCloser).Open", Method, 16},
+		{"(*ReadCloser).RegisterDecompressor", Method, 6},
+		{"(*Reader).Open", Method, 16},
+		{"(*Reader).RegisterDecompressor", Method, 6},
+		{"(*Writer).AddFS", Method, 22},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Copy", Method, 17},
+		{"(*Writer).Create", Method, 0},
+		{"(*Writer).CreateHeader", Method, 0},
+		{"(*Writer).CreateRaw", Method, 17},
+		{"(*Writer).Flush", Method, 4},
+		{"(*Writer).RegisterCompressor", Method, 6},
+		{"(*Writer).SetComment", Method, 10},
+		{"(*Writer).SetOffset", Method, 5},
+		{"Compressor", Type, 2},
+		{"Decompressor", Type, 2},
+		{"Deflate", Const, 0},
+		{"ErrAlgorithm", Var, 0},
+		{"ErrChecksum", Var, 0},
+		{"ErrFormat", Var, 0},
+		{"ErrInsecurePath", Var, 20},
+		{"File", Type, 0},
+		{"File.FileHeader", Field, 0},
+		{"FileHeader", Type, 0},
+		{"FileHeader.CRC32", Field, 0},
+		{"FileHeader.Comment", Field, 0},
+		{"FileHeader.CompressedSize", Field, 0},
+		{"FileHeader.CompressedSize64", Field, 1},
+		{"FileHeader.CreatorVersion", Field, 0},
+		{"FileHeader.ExternalAttrs", Field, 0},
+		{"FileHeader.Extra", Field, 0},
+		{"FileHeader.Flags", Field, 0},
+		{"FileHeader.Method", Field, 0},
+		{"FileHeader.Modified", Field, 10},
+		{"FileHeader.ModifiedDate", Field, 0},
+		{"FileHeader.ModifiedTime", Field, 0},
+		{"FileHeader.Name", Field, 0},
+		{"FileHeader.NonUTF8", Field, 10},
+		{"FileHeader.ReaderVersion", Field, 0},
+		{"FileHeader.UncompressedSize", Field, 0},
+		{"FileHeader.UncompressedSize64", Field, 1},
+		{"FileInfoHeader", Func, 0},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"OpenReader", Func, 0},
+		{"ReadCloser", Type, 0},
+		{"ReadCloser.Reader", Field, 0},
+		{"Reader", Type, 0},
+		{"Reader.Comment", Field, 0},
+		{"Reader.File", Field, 0},
+		{"RegisterCompressor", Func, 2},
+		{"RegisterDecompressor", Func, 2},
+		{"Store", Const, 0},
+		{"Writer", Type, 0},
+	},
+	"bufio": {
+		{"(*Reader).Buffered", Method, 0},
+		{"(*Reader).Discard", Method, 5},
+		{"(*Reader).Peek", Method, 0},
+		{"(*Reader).Read", Method, 0},
+		{"(*Reader).ReadByte", Method, 0},
+		{"(*Reader).ReadBytes", Method, 0},
+		{"(*Reader).ReadLine", Method, 0},
+		{"(*Reader).ReadRune", Method, 0},
+		{"(*Reader).ReadSlice", Method, 0},
+		{"(*Reader).ReadString", Method, 0},
+		{"(*Reader).Reset", Method, 2},
+		{"(*Reader).Size", Method, 10},
+		{"(*Reader).UnreadByte", Method, 0},
+		{"(*Reader).UnreadRune", Method, 0},
+		{"(*Reader).WriteTo", Method, 1},
+		{"(*Scanner).Buffer", Method, 6},
+		{"(*Scanner).Bytes", Method, 1},
+		{"(*Scanner).Err", Method, 1},
+		{"(*Scanner).Scan", Method, 1},
+		{"(*Scanner).Split", Method, 1},
+		{"(*Scanner).Text", Method, 1},
+		{"(*Writer).Available", Method, 0},
+		{"(*Writer).AvailableBuffer", Method, 18},
+		{"(*Writer).Buffered", Method, 0},
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).ReadFrom", Method, 1},
+		{"(*Writer).Reset", Method, 2},
+		{"(*Writer).Size", Method, 10},
+		{"(*Writer).Write", Method, 0},
+		{"(*Writer).WriteByte", Method, 0},
+		{"(*Writer).WriteRune", Method, 0},
+		{"(*Writer).WriteString", Method, 0},
+		{"(ReadWriter).Available", Method, 0},
+		{"(ReadWriter).AvailableBuffer", Method, 18},
+		{"(ReadWriter).Discard", Method, 5},
+		{"(ReadWriter).Flush", Method, 0},
+		{"(ReadWriter).Peek", Method, 0},
+		{"(ReadWriter).Read", Method, 0},
+		{"(ReadWriter).ReadByte", Method, 0},
+		{"(ReadWriter).ReadBytes", Method, 0},
+		{"(ReadWriter).ReadFrom", Method, 1},
+		{"(ReadWriter).ReadLine", Method, 0},
+		{"(ReadWriter).ReadRune", Method, 0},
+		{"(ReadWriter).ReadSlice", Method, 0},
+		{"(ReadWriter).ReadString", Method, 0},
+		{"(ReadWriter).UnreadByte", Method, 0},
+		{"(ReadWriter).UnreadRune", Method, 0},
+		{"(ReadWriter).Write", Method, 0},
+		{"(ReadWriter).WriteByte", Method, 0},
+		{"(ReadWriter).WriteRune", Method, 0},
+		{"(ReadWriter).WriteString", Method, 0},
+		{"(ReadWriter).WriteTo", Method, 1},
+		{"ErrAdvanceTooFar", Var, 1},
+		{"ErrBadReadCount", Var, 15},
+		{"ErrBufferFull", Var, 0},
+		{"ErrFinalToken", Var, 6},
+		{"ErrInvalidUnreadByte", Var, 0},
+		{"ErrInvalidUnreadRune", Var, 0},
+		{"ErrNegativeAdvance", Var, 1},
+		{"ErrNegativeCount", Var, 0},
+		{"ErrTooLong", Var, 1},
+		{"MaxScanTokenSize", Const, 1},
+		{"NewReadWriter", Func, 0},
+		{"NewReader", Func, 0},
+		{"NewReaderSize", Func, 0},
+		{"NewScanner", Func, 1},
+		{"NewWriter", Func, 0},
+		{"NewWriterSize", Func, 0},
+		{"ReadWriter", Type, 0},
+		{"ReadWriter.Reader", Field, 0},
+		{"ReadWriter.Writer", Field, 0},
+		{"Reader", Type, 0},
+		{"ScanBytes", Func, 1},
+		{"ScanLines", Func, 1},
+		{"ScanRunes", Func, 1},
+		{"ScanWords", Func, 1},
+		{"Scanner", Type, 1},
+		{"SplitFunc", Type, 1},
+		{"Writer", Type, 0},
+	},
+	"bytes": {
+		{"(*Buffer).Available", Method, 21},
+		{"(*Buffer).AvailableBuffer", Method, 21},
+		{"(*Buffer).Bytes", Method, 0},
+		{"(*Buffer).Cap", Method, 5},
+		{"(*Buffer).Grow", Method, 1},
+		{"(*Buffer).Len", Method, 0},
+		{"(*Buffer).Next", Method, 0},
+		{"(*Buffer).Read", Method, 0},
+		{"(*Buffer).ReadByte", Method, 0},
+		{"(*Buffer).ReadBytes", Method, 0},
+		{"(*Buffer).ReadFrom", Method, 0},
+		{"(*Buffer).ReadRune", Method, 0},
+		{"(*Buffer).ReadString", Method, 0},
+		{"(*Buffer).Reset", Method, 0},
+		{"(*Buffer).String", Method, 0},
+		{"(*Buffer).Truncate", Method, 0},
+		{"(*Buffer).UnreadByte", Method, 0},
+		{"(*Buffer).UnreadRune", Method, 0},
+		{"(*Buffer).Write", Method, 0},
+		{"(*Buffer).WriteByte", Method, 0},
+		{"(*Buffer).WriteRune", Method, 0},
+		{"(*Buffer).WriteString", Method, 0},
+		{"(*Buffer).WriteTo", Method, 0},
+		{"(*Reader).Len", Method, 0},
+		{"(*Reader).Read", Method, 0},
+		{"(*Reader).ReadAt", Method, 0},
+		{"(*Reader).ReadByte", Method, 0},
+		{"(*Reader).ReadRune", Method, 0},
+		{"(*Reader).Reset", Method, 7},
+		{"(*Reader).Seek", Method, 0},
+		{"(*Reader).Size", Method, 5},
+		{"(*Reader).UnreadByte", Method, 0},
+		{"(*Reader).UnreadRune", Method, 0},
+		{"(*Reader).WriteTo", Method, 1},
+		{"Buffer", Type, 0},
+		{"Clone", Func, 20},
+		{"Compare", Func, 0},
+		{"Contains", Func, 0},
+		{"ContainsAny", Func, 7},
+		{"ContainsFunc", Func, 21},
+		{"ContainsRune", Func, 7},
+		{"Count", Func, 0},
+		{"Cut", Func, 18},
+		{"CutPrefix", Func, 20},
+		{"CutSuffix", Func, 20},
+		{"Equal", Func, 0},
+		{"EqualFold", Func, 0},
+		{"ErrTooLarge", Var, 0},
+		{"Fields", Func, 0},
+		{"FieldsFunc", Func, 0},
+		{"FieldsFuncSeq", Func, 24},
+		{"FieldsSeq", Func, 24},
+		{"HasPrefix", Func, 0},
+		{"HasSuffix", Func, 0},
+		{"Index", Func, 0},
+		{"IndexAny", Func, 0},
+		{"IndexByte", Func, 0},
+		{"IndexFunc", Func, 0},
+		{"IndexRune", Func, 0},
+		{"Join", Func, 0},
+		{"LastIndex", Func, 0},
+		{"LastIndexAny", Func, 0},
+		{"LastIndexByte", Func, 5},
+		{"LastIndexFunc", Func, 0},
+		{"Lines", Func, 24},
+		{"Map", Func, 0},
+		{"MinRead", Const, 0},
+		{"NewBuffer", Func, 0},
+		{"NewBufferString", Func, 0},
+		{"NewReader", Func, 0},
+		{"Reader", Type, 0},
+		{"Repeat", Func, 0},
+		{"Replace", Func, 0},
+		{"ReplaceAll", Func, 12},
+		{"Runes", Func, 0},
+		{"Split", Func, 0},
+		{"SplitAfter", Func, 0},
+		{"SplitAfterN", Func, 0},
+		{"SplitAfterSeq", Func, 24},
+		{"SplitN", Func, 0},
+		{"SplitSeq", Func, 24},
+		{"Title", Func, 0},
+		{"ToLower", Func, 0},
+		{"ToLowerSpecial", Func, 0},
+		{"ToTitle", Func, 0},
+		{"ToTitleSpecial", Func, 0},
+		{"ToUpper", Func, 0},
+		{"ToUpperSpecial", Func, 0},
+		{"ToValidUTF8", Func, 13},
+		{"Trim", Func, 0},
+		{"TrimFunc", Func, 0},
+		{"TrimLeft", Func, 0},
+		{"TrimLeftFunc", Func, 0},
+		{"TrimPrefix", Func, 1},
+		{"TrimRight", Func, 0},
+		{"TrimRightFunc", Func, 0},
+		{"TrimSpace", Func, 0},
+		{"TrimSuffix", Func, 1},
+	},
+	"cmp": {
+		{"Compare", Func, 21},
+		{"Less", Func, 21},
+		{"Or", Func, 22},
+		{"Ordered", Type, 21},
+	},
+	"compress/bzip2": {
+		{"(StructuralError).Error", Method, 0},
+		{"NewReader", Func, 0},
+		{"StructuralError", Type, 0},
+	},
+	"compress/flate": {
+		{"(*ReadError).Error", Method, 0},
+		{"(*WriteError).Error", Method, 0},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).Reset", Method, 2},
+		{"(*Writer).Write", Method, 0},
+		{"(CorruptInputError).Error", Method, 0},
+		{"(InternalError).Error", Method, 0},
+		{"BestCompression", Const, 0},
+		{"BestSpeed", Const, 0},
+		{"CorruptInputError", Type, 0},
+		{"DefaultCompression", Const, 0},
+		{"HuffmanOnly", Const, 7},
+		{"InternalError", Type, 0},
+		{"NewReader", Func, 0},
+		{"NewReaderDict", Func, 0},
+		{"NewWriter", Func, 0},
+		{"NewWriterDict", Func, 0},
+		{"NoCompression", Const, 0},
+		{"ReadError", Type, 0},
+		{"ReadError.Err", Field, 0},
+		{"ReadError.Offset", Field, 0},
+		{"Reader", Type, 0},
+		{"Resetter", Type, 4},
+		{"WriteError", Type, 0},
+		{"WriteError.Err", Field, 0},
+		{"WriteError.Offset", Field, 0},
+		{"Writer", Type, 0},
+	},
+	"compress/gzip": {
+		{"(*Reader).Close", Method, 0},
+		{"(*Reader).Multistream", Method, 4},
+		{"(*Reader).Read", Method, 0},
+		{"(*Reader).Reset", Method, 3},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Flush", Method, 1},
+		{"(*Writer).Reset", Method, 2},
+		{"(*Writer).Write", Method, 0},
+		{"BestCompression", Const, 0},
+		{"BestSpeed", Const, 0},
+		{"DefaultCompression", Const, 0},
+		{"ErrChecksum", Var, 0},
+		{"ErrHeader", Var, 0},
+		{"Header", Type, 0},
+		{"Header.Comment", Field, 0},
+		{"Header.Extra", Field, 0},
+		{"Header.ModTime", Field, 0},
+		{"Header.Name", Field, 0},
+		{"Header.OS", Field, 0},
+		{"HuffmanOnly", Const, 8},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"NewWriterLevel", Func, 0},
+		{"NoCompression", Const, 0},
+		{"Reader", Type, 0},
+		{"Reader.Header", Field, 0},
+		{"Writer", Type, 0},
+		{"Writer.Header", Field, 0},
+	},
+	"compress/lzw": {
+		{"(*Reader).Close", Method, 17},
+		{"(*Reader).Read", Method, 17},
+		{"(*Reader).Reset", Method, 17},
+		{"(*Writer).Close", Method, 17},
+		{"(*Writer).Reset", Method, 17},
+		{"(*Writer).Write", Method, 17},
+		{"LSB", Const, 0},
+		{"MSB", Const, 0},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"Order", Type, 0},
+		{"Reader", Type, 17},
+		{"Writer", Type, 17},
+	},
+	"compress/zlib": {
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).Reset", Method, 2},
+		{"(*Writer).Write", Method, 0},
+		{"BestCompression", Const, 0},
+		{"BestSpeed", Const, 0},
+		{"DefaultCompression", Const, 0},
+		{"ErrChecksum", Var, 0},
+		{"ErrDictionary", Var, 0},
+		{"ErrHeader", Var, 0},
+		{"HuffmanOnly", Const, 8},
+		{"NewReader", Func, 0},
+		{"NewReaderDict", Func, 0},
+		{"NewWriter", Func, 0},
+		{"NewWriterLevel", Func, 0},
+		{"NewWriterLevelDict", Func, 0},
+		{"NoCompression", Const, 0},
+		{"Resetter", Type, 4},
+		{"Writer", Type, 0},
+	},
+	"container/heap": {
+		{"Fix", Func, 2},
+		{"Init", Func, 0},
+		{"Interface", Type, 0},
+		{"Pop", Func, 0},
+		{"Push", Func, 0},
+		{"Remove", Func, 0},
+	},
+	"container/list": {
+		{"(*Element).Next", Method, 0},
+		{"(*Element).Prev", Method, 0},
+		{"(*List).Back", Method, 0},
+		{"(*List).Front", Method, 0},
+		{"(*List).Init", Method, 0},
+		{"(*List).InsertAfter", Method, 0},
+		{"(*List).InsertBefore", Method, 0},
+		{"(*List).Len", Method, 0},
+		{"(*List).MoveAfter", Method, 2},
+		{"(*List).MoveBefore", Method, 2},
+		{"(*List).MoveToBack", Method, 0},
+		{"(*List).MoveToFront", Method, 0},
+		{"(*List).PushBack", Method, 0},
+		{"(*List).PushBackList", Method, 0},
+		{"(*List).PushFront", Method, 0},
+		{"(*List).PushFrontList", Method, 0},
+		{"(*List).Remove", Method, 0},
+		{"Element", Type, 0},
+		{"Element.Value", Field, 0},
+		{"List", Type, 0},
+		{"New", Func, 0},
+	},
+	"container/ring": {
+		{"(*Ring).Do", Method, 0},
+		{"(*Ring).Len", Method, 0},
+		{"(*Ring).Link", Method, 0},
+		{"(*Ring).Move", Method, 0},
+		{"(*Ring).Next", Method, 0},
+		{"(*Ring).Prev", Method, 0},
+		{"(*Ring).Unlink", Method, 0},
+		{"New", Func, 0},
+		{"Ring", Type, 0},
+		{"Ring.Value", Field, 0},
+	},
+	"context": {
+		{"AfterFunc", Func, 21},
+		{"Background", Func, 7},
+		{"CancelCauseFunc", Type, 20},
+		{"CancelFunc", Type, 7},
+		{"Canceled", Var, 7},
+		{"Cause", Func, 20},
+		{"Context", Type, 7},
+		{"DeadlineExceeded", Var, 7},
+		{"TODO", Func, 7},
+		{"WithCancel", Func, 7},
+		{"WithCancelCause", Func, 20},
+		{"WithDeadline", Func, 7},
+		{"WithDeadlineCause", Func, 21},
+		{"WithTimeout", Func, 7},
+		{"WithTimeoutCause", Func, 21},
+		{"WithValue", Func, 7},
+		{"WithoutCancel", Func, 21},
+	},
+	"crypto": {
+		{"(Hash).Available", Method, 0},
+		{"(Hash).HashFunc", Method, 4},
+		{"(Hash).New", Method, 0},
+		{"(Hash).Size", Method, 0},
+		{"(Hash).String", Method, 15},
+		{"BLAKE2b_256", Const, 9},
+		{"BLAKE2b_384", Const, 9},
+		{"BLAKE2b_512", Const, 9},
+		{"BLAKE2s_256", Const, 9},
+		{"Decrypter", Type, 5},
+		{"DecrypterOpts", Type, 5},
+		{"Hash", Type, 0},
+		{"MD4", Const, 0},
+		{"MD5", Const, 0},
+		{"MD5SHA1", Const, 0},
+		{"PrivateKey", Type, 0},
+		{"PublicKey", Type, 2},
+		{"RIPEMD160", Const, 0},
+		{"RegisterHash", Func, 0},
+		{"SHA1", Const, 0},
+		{"SHA224", Const, 0},
+		{"SHA256", Const, 0},
+		{"SHA384", Const, 0},
+		{"SHA3_224", Const, 4},
+		{"SHA3_256", Const, 4},
+		{"SHA3_384", Const, 4},
+		{"SHA3_512", Const, 4},
+		{"SHA512", Const, 0},
+		{"SHA512_224", Const, 5},
+		{"SHA512_256", Const, 5},
+		{"Signer", Type, 4},
+		{"SignerOpts", Type, 4},
+	},
+	"crypto/aes": {
+		{"(KeySizeError).Error", Method, 0},
+		{"BlockSize", Const, 0},
+		{"KeySizeError", Type, 0},
+		{"NewCipher", Func, 0},
+	},
+	"crypto/cipher": {
+		{"(StreamReader).Read", Method, 0},
+		{"(StreamWriter).Close", Method, 0},
+		{"(StreamWriter).Write", Method, 0},
+		{"AEAD", Type, 2},
+		{"Block", Type, 0},
+		{"BlockMode", Type, 0},
+		{"NewCBCDecrypter", Func, 0},
+		{"NewCBCEncrypter", Func, 0},
+		{"NewCFBDecrypter", Func, 0},
+		{"NewCFBEncrypter", Func, 0},
+		{"NewCTR", Func, 0},
+		{"NewGCM", Func, 2},
+		{"NewGCMWithNonceSize", Func, 5},
+		{"NewGCMWithRandomNonce", Func, 24},
+		{"NewGCMWithTagSize", Func, 11},
+		{"NewOFB", Func, 0},
+		{"Stream", Type, 0},
+		{"StreamReader", Type, 0},
+		{"StreamReader.R", Field, 0},
+		{"StreamReader.S", Field, 0},
+		{"StreamWriter", Type, 0},
+		{"StreamWriter.Err", Field, 0},
+		{"StreamWriter.S", Field, 0},
+		{"StreamWriter.W", Field, 0},
+	},
+	"crypto/des": {
+		{"(KeySizeError).Error", Method, 0},
+		{"BlockSize", Const, 0},
+		{"KeySizeError", Type, 0},
+		{"NewCipher", Func, 0},
+		{"NewTripleDESCipher", Func, 0},
+	},
+	"crypto/dsa": {
+		{"ErrInvalidPublicKey", Var, 0},
+		{"GenerateKey", Func, 0},
+		{"GenerateParameters", Func, 0},
+		{"L1024N160", Const, 0},
+		{"L2048N224", Const, 0},
+		{"L2048N256", Const, 0},
+		{"L3072N256", Const, 0},
+		{"ParameterSizes", Type, 0},
+		{"Parameters", Type, 0},
+		{"Parameters.G", Field, 0},
+		{"Parameters.P", Field, 0},
+		{"Parameters.Q", Field, 0},
+		{"PrivateKey", Type, 0},
+		{"PrivateKey.PublicKey", Field, 0},
+		{"PrivateKey.X", Field, 0},
+		{"PublicKey", Type, 0},
+		{"PublicKey.Parameters", Field, 0},
+		{"PublicKey.Y", Field, 0},
+		{"Sign", Func, 0},
+		{"Verify", Func, 0},
+	},
+	"crypto/ecdh": {
+		{"(*PrivateKey).Bytes", Method, 20},
+		{"(*PrivateKey).Curve", Method, 20},
+		{"(*PrivateKey).ECDH", Method, 20},
+		{"(*PrivateKey).Equal", Method, 20},
+		{"(*PrivateKey).Public", Method, 20},
+		{"(*PrivateKey).PublicKey", Method, 20},
+		{"(*PublicKey).Bytes", Method, 20},
+		{"(*PublicKey).Curve", Method, 20},
+		{"(*PublicKey).Equal", Method, 20},
+		{"Curve", Type, 20},
+		{"P256", Func, 20},
+		{"P384", Func, 20},
+		{"P521", Func, 20},
+		{"PrivateKey", Type, 20},
+		{"PublicKey", Type, 20},
+		{"X25519", Func, 20},
+	},
+	"crypto/ecdsa": {
+		{"(*PrivateKey).ECDH", Method, 20},
+		{"(*PrivateKey).Equal", Method, 15},
+		{"(*PrivateKey).Public", Method, 4},
+		{"(*PrivateKey).Sign", Method, 4},
+		{"(*PublicKey).ECDH", Method, 20},
+		{"(*PublicKey).Equal", Method, 15},
+		{"(PrivateKey).Add", Method, 0},
+		{"(PrivateKey).Double", Method, 0},
+		{"(PrivateKey).IsOnCurve", Method, 0},
+		{"(PrivateKey).Params", Method, 0},
+		{"(PrivateKey).ScalarBaseMult", Method, 0},
+		{"(PrivateKey).ScalarMult", Method, 0},
+		{"(PublicKey).Add", Method, 0},
+		{"(PublicKey).Double", Method, 0},
+		{"(PublicKey).IsOnCurve", Method, 0},
+		{"(PublicKey).Params", Method, 0},
+		{"(PublicKey).ScalarBaseMult", Method, 0},
+		{"(PublicKey).ScalarMult", Method, 0},
+		{"GenerateKey", Func, 0},
+		{"PrivateKey", Type, 0},
+		{"PrivateKey.D", Field, 0},
+		{"PrivateKey.PublicKey", Field, 0},
+		{"PublicKey", Type, 0},
+		{"PublicKey.Curve", Field, 0},
+		{"PublicKey.X", Field, 0},
+		{"PublicKey.Y", Field, 0},
+		{"Sign", Func, 0},
+		{"SignASN1", Func, 15},
+		{"Verify", Func, 0},
+		{"VerifyASN1", Func, 15},
+	},
+	"crypto/ed25519": {
+		{"(*Options).HashFunc", Method, 20},
+		{"(PrivateKey).Equal", Method, 15},
+		{"(PrivateKey).Public", Method, 13},
+		{"(PrivateKey).Seed", Method, 13},
+		{"(PrivateKey).Sign", Method, 13},
+		{"(PublicKey).Equal", Method, 15},
+		{"GenerateKey", Func, 13},
+		{"NewKeyFromSeed", Func, 13},
+		{"Options", Type, 20},
+		{"Options.Context", Field, 20},
+		{"Options.Hash", Field, 20},
+		{"PrivateKey", Type, 13},
+		{"PrivateKeySize", Const, 13},
+		{"PublicKey", Type, 13},
+		{"PublicKeySize", Const, 13},
+		{"SeedSize", Const, 13},
+		{"Sign", Func, 13},
+		{"SignatureSize", Const, 13},
+		{"Verify", Func, 13},
+		{"VerifyWithOptions", Func, 20},
+	},
+	"crypto/elliptic": {
+		{"(*CurveParams).Add", Method, 0},
+		{"(*CurveParams).Double", Method, 0},
+		{"(*CurveParams).IsOnCurve", Method, 0},
+		{"(*CurveParams).Params", Method, 0},
+		{"(*CurveParams).ScalarBaseMult", Method, 0},
+		{"(*CurveParams).ScalarMult", Method, 0},
+		{"Curve", Type, 0},
+		{"CurveParams", Type, 0},
+		{"CurveParams.B", Field, 0},
+		{"CurveParams.BitSize", Field, 0},
+		{"CurveParams.Gx", Field, 0},
+		{"CurveParams.Gy", Field, 0},
+		{"CurveParams.N", Field, 0},
+		{"CurveParams.Name", Field, 5},
+		{"CurveParams.P", Field, 0},
+		{"GenerateKey", Func, 0},
+		{"Marshal", Func, 0},
+		{"MarshalCompressed", Func, 15},
+		{"P224", Func, 0},
+		{"P256", Func, 0},
+		{"P384", Func, 0},
+		{"P521", Func, 0},
+		{"Unmarshal", Func, 0},
+		{"UnmarshalCompressed", Func, 15},
+	},
+	"crypto/fips140": {
+		{"Enabled", Func, 24},
+	},
+	"crypto/hkdf": {
+		{"Expand", Func, 24},
+		{"Extract", Func, 24},
+		{"Key", Func, 24},
+	},
+	"crypto/hmac": {
+		{"Equal", Func, 1},
+		{"New", Func, 0},
+	},
+	"crypto/md5": {
+		{"BlockSize", Const, 0},
+		{"New", Func, 0},
+		{"Size", Const, 0},
+		{"Sum", Func, 2},
+	},
+	"crypto/mlkem": {
+		{"(*DecapsulationKey1024).Bytes", Method, 24},
+		{"(*DecapsulationKey1024).Decapsulate", Method, 24},
+		{"(*DecapsulationKey1024).EncapsulationKey", Method, 24},
+		{"(*DecapsulationKey768).Bytes", Method, 24},
+		{"(*DecapsulationKey768).Decapsulate", Method, 24},
+		{"(*DecapsulationKey768).EncapsulationKey", Method, 24},
+		{"(*EncapsulationKey1024).Bytes", Method, 24},
+		{"(*EncapsulationKey1024).Encapsulate", Method, 24},
+		{"(*EncapsulationKey768).Bytes", Method, 24},
+		{"(*EncapsulationKey768).Encapsulate", Method, 24},
+		{"CiphertextSize1024", Const, 24},
+		{"CiphertextSize768", Const, 24},
+		{"DecapsulationKey1024", Type, 24},
+		{"DecapsulationKey768", Type, 24},
+		{"EncapsulationKey1024", Type, 24},
+		{"EncapsulationKey768", Type, 24},
+		{"EncapsulationKeySize1024", Const, 24},
+		{"EncapsulationKeySize768", Const, 24},
+		{"GenerateKey1024", Func, 24},
+		{"GenerateKey768", Func, 24},
+		{"NewDecapsulationKey1024", Func, 24},
+		{"NewDecapsulationKey768", Func, 24},
+		{"NewEncapsulationKey1024", Func, 24},
+		{"NewEncapsulationKey768", Func, 24},
+		{"SeedSize", Const, 24},
+		{"SharedKeySize", Const, 24},
+	},
+	"crypto/pbkdf2": {
+		{"Key", Func, 24},
+	},
+	"crypto/rand": {
+		{"Int", Func, 0},
+		{"Prime", Func, 0},
+		{"Read", Func, 0},
+		{"Reader", Var, 0},
+		{"Text", Func, 24},
+	},
+	"crypto/rc4": {
+		{"(*Cipher).Reset", Method, 0},
+		{"(*Cipher).XORKeyStream", Method, 0},
+		{"(KeySizeError).Error", Method, 0},
+		{"Cipher", Type, 0},
+		{"KeySizeError", Type, 0},
+		{"NewCipher", Func, 0},
+	},
+	"crypto/rsa": {
+		{"(*PSSOptions).HashFunc", Method, 4},
+		{"(*PrivateKey).Decrypt", Method, 5},
+		{"(*PrivateKey).Equal", Method, 15},
+		{"(*PrivateKey).Precompute", Method, 0},
+		{"(*PrivateKey).Public", Method, 4},
+		{"(*PrivateKey).Sign", Method, 4},
+		{"(*PrivateKey).Size", Method, 11},
+		{"(*PrivateKey).Validate", Method, 0},
+		{"(*PublicKey).Equal", Method, 15},
+		{"(*PublicKey).Size", Method, 11},
+		{"CRTValue", Type, 0},
+		{"CRTValue.Coeff", Field, 0},
+		{"CRTValue.Exp", Field, 0},
+		{"CRTValue.R", Field, 0},
+		{"DecryptOAEP", Func, 0},
+		{"DecryptPKCS1v15", Func, 0},
+		{"DecryptPKCS1v15SessionKey", Func, 0},
+		{"EncryptOAEP", Func, 0},
+		{"EncryptPKCS1v15", Func, 0},
+		{"ErrDecryption", Var, 0},
+		{"ErrMessageTooLong", Var, 0},
+		{"ErrVerification", Var, 0},
+		{"GenerateKey", Func, 0},
+		{"GenerateMultiPrimeKey", Func, 0},
+		{"OAEPOptions", Type, 5},
+		{"OAEPOptions.Hash", Field, 5},
+		{"OAEPOptions.Label", Field, 5},
+		{"OAEPOptions.MGFHash", Field, 20},
+		{"PKCS1v15DecryptOptions", Type, 5},
+		{"PKCS1v15DecryptOptions.SessionKeyLen", Field, 5},
+		{"PSSOptions", Type, 2},
+		{"PSSOptions.Hash", Field, 4},
+		{"PSSOptions.SaltLength", Field, 2},
+		{"PSSSaltLengthAuto", Const, 2},
+		{"PSSSaltLengthEqualsHash", Const, 2},
+		{"PrecomputedValues", Type, 0},
+		{"PrecomputedValues.CRTValues", Field, 0},
+		{"PrecomputedValues.Dp", Field, 0},
+		{"PrecomputedValues.Dq", Field, 0},
+		{"PrecomputedValues.Qinv", Field, 0},
+		{"PrivateKey", Type, 0},
+		{"PrivateKey.D", Field, 0},
+		{"PrivateKey.Precomputed", Field, 0},
+		{"PrivateKey.Primes", Field, 0},
+		{"PrivateKey.PublicKey", Field, 0},
+		{"PublicKey", Type, 0},
+		{"PublicKey.E", Field, 0},
+		{"PublicKey.N", Field, 0},
+		{"SignPKCS1v15", Func, 0},
+		{"SignPSS", Func, 2},
+		{"VerifyPKCS1v15", Func, 0},
+		{"VerifyPSS", Func, 2},
+	},
+	"crypto/sha1": {
+		{"BlockSize", Const, 0},
+		{"New", Func, 0},
+		{"Size", Const, 0},
+		{"Sum", Func, 2},
+	},
+	"crypto/sha256": {
+		{"BlockSize", Const, 0},
+		{"New", Func, 0},
+		{"New224", Func, 0},
+		{"Size", Const, 0},
+		{"Size224", Const, 0},
+		{"Sum224", Func, 2},
+		{"Sum256", Func, 2},
+	},
+	"crypto/sha3": {
+		{"(*SHA3).AppendBinary", Method, 24},
+		{"(*SHA3).BlockSize", Method, 24},
+		{"(*SHA3).MarshalBinary", Method, 24},
+		{"(*SHA3).Reset", Method, 24},
+		{"(*SHA3).Size", Method, 24},
+		{"(*SHA3).Sum", Method, 24},
+		{"(*SHA3).UnmarshalBinary", Method, 24},
+		{"(*SHA3).Write", Method, 24},
+		{"(*SHAKE).AppendBinary", Method, 24},
+		{"(*SHAKE).BlockSize", Method, 24},
+		{"(*SHAKE).MarshalBinary", Method, 24},
+		{"(*SHAKE).Read", Method, 24},
+		{"(*SHAKE).Reset", Method, 24},
+		{"(*SHAKE).UnmarshalBinary", Method, 24},
+		{"(*SHAKE).Write", Method, 24},
+		{"New224", Func, 24},
+		{"New256", Func, 24},
+		{"New384", Func, 24},
+		{"New512", Func, 24},
+		{"NewCSHAKE128", Func, 24},
+		{"NewCSHAKE256", Func, 24},
+		{"NewSHAKE128", Func, 24},
+		{"NewSHAKE256", Func, 24},
+		{"SHA3", Type, 24},
+		{"SHAKE", Type, 24},
+		{"Sum224", Func, 24},
+		{"Sum256", Func, 24},
+		{"Sum384", Func, 24},
+		{"Sum512", Func, 24},
+		{"SumSHAKE128", Func, 24},
+		{"SumSHAKE256", Func, 24},
+	},
+	"crypto/sha512": {
+		{"BlockSize", Const, 0},
+		{"New", Func, 0},
+		{"New384", Func, 0},
+		{"New512_224", Func, 5},
+		{"New512_256", Func, 5},
+		{"Size", Const, 0},
+		{"Size224", Const, 5},
+		{"Size256", Const, 5},
+		{"Size384", Const, 0},
+		{"Sum384", Func, 2},
+		{"Sum512", Func, 2},
+		{"Sum512_224", Func, 5},
+		{"Sum512_256", Func, 5},
+	},
+	"crypto/subtle": {
+		{"ConstantTimeByteEq", Func, 0},
+		{"ConstantTimeCompare", Func, 0},
+		{"ConstantTimeCopy", Func, 0},
+		{"ConstantTimeEq", Func, 0},
+		{"ConstantTimeLessOrEq", Func, 2},
+		{"ConstantTimeSelect", Func, 0},
+		{"WithDataIndependentTiming", Func, 24},
+		{"XORBytes", Func, 20},
+	},
+	"crypto/tls": {
+		{"(*CertificateRequestInfo).Context", Method, 17},
+		{"(*CertificateRequestInfo).SupportsCertificate", Method, 14},
+		{"(*CertificateVerificationError).Error", Method, 20},
+		{"(*CertificateVerificationError).Unwrap", Method, 20},
+		{"(*ClientHelloInfo).Context", Method, 17},
+		{"(*ClientHelloInfo).SupportsCertificate", Method, 14},
+		{"(*ClientSessionState).ResumptionState", Method, 21},
+		{"(*Config).BuildNameToCertificate", Method, 0},
+		{"(*Config).Clone", Method, 8},
+		{"(*Config).DecryptTicket", Method, 21},
+		{"(*Config).EncryptTicket", Method, 21},
+		{"(*Config).SetSessionTicketKeys", Method, 5},
+		{"(*Conn).Close", Method, 0},
+		{"(*Conn).CloseWrite", Method, 8},
+		{"(*Conn).ConnectionState", Method, 0},
+		{"(*Conn).Handshake", Method, 0},
+		{"(*Conn).HandshakeContext", Method, 17},
+		{"(*Conn).LocalAddr", Method, 0},
+		{"(*Conn).NetConn", Method, 18},
+		{"(*Conn).OCSPResponse", Method, 0},
+		{"(*Conn).Read", Method, 0},
+		{"(*Conn).RemoteAddr", Method, 0},
+		{"(*Conn).SetDeadline", Method, 0},
+		{"(*Conn).SetReadDeadline", Method, 0},
+		{"(*Conn).SetWriteDeadline", Method, 0},
+		{"(*Conn).VerifyHostname", Method, 0},
+		{"(*Conn).Write", Method, 0},
+		{"(*ConnectionState).ExportKeyingMaterial", Method, 11},
+		{"(*Dialer).Dial", Method, 15},
+		{"(*Dialer).DialContext", Method, 15},
+		{"(*ECHRejectionError).Error", Method, 23},
+		{"(*QUICConn).Close", Method, 21},
+		{"(*QUICConn).ConnectionState", Method, 21},
+		{"(*QUICConn).HandleData", Method, 21},
+		{"(*QUICConn).NextEvent", Method, 21},
+		{"(*QUICConn).SendSessionTicket", Method, 21},
+		{"(*QUICConn).SetTransportParameters", Method, 21},
+		{"(*QUICConn).Start", Method, 21},
+		{"(*QUICConn).StoreSession", Method, 23},
+		{"(*SessionState).Bytes", Method, 21},
+		{"(AlertError).Error", Method, 21},
+		{"(ClientAuthType).String", Method, 15},
+		{"(CurveID).String", Method, 15},
+		{"(QUICEncryptionLevel).String", Method, 21},
+		{"(RecordHeaderError).Error", Method, 6},
+		{"(SignatureScheme).String", Method, 15},
+		{"AlertError", Type, 21},
+		{"Certificate", Type, 0},
+		{"Certificate.Certificate", Field, 0},
+		{"Certificate.Leaf", Field, 0},
+		{"Certificate.OCSPStaple", Field, 0},
+		{"Certificate.PrivateKey", Field, 0},
+		{"Certificate.SignedCertificateTimestamps", Field, 5},
+		{"Certificate.SupportedSignatureAlgorithms", Field, 14},
+		{"CertificateRequestInfo", Type, 8},
+		{"CertificateRequestInfo.AcceptableCAs", Field, 8},
+		{"CertificateRequestInfo.SignatureSchemes", Field, 8},
+		{"CertificateRequestInfo.Version", Field, 14},
+		{"CertificateVerificationError", Type, 20},
+		{"CertificateVerificationError.Err", Field, 20},
+		{"CertificateVerificationError.UnverifiedCertificates", Field, 20},
+		{"CipherSuite", Type, 14},
+		{"CipherSuite.ID", Field, 14},
+		{"CipherSuite.Insecure", Field, 14},
+		{"CipherSuite.Name", Field, 14},
+		{"CipherSuite.SupportedVersions", Field, 14},
+		{"CipherSuiteName", Func, 14},
+		{"CipherSuites", Func, 14},
+		{"Client", Func, 0},
+		{"ClientAuthType", Type, 0},
+		{"ClientHelloInfo", Type, 4},
+		{"ClientHelloInfo.CipherSuites", Field, 4},
+		{"ClientHelloInfo.Conn", Field, 8},
+		{"ClientHelloInfo.Extensions", Field, 24},
+		{"ClientHelloInfo.ServerName", Field, 4},
+		{"ClientHelloInfo.SignatureSchemes", Field, 8},
+		{"ClientHelloInfo.SupportedCurves", Field, 4},
+		{"ClientHelloInfo.SupportedPoints", Field, 4},
+		{"ClientHelloInfo.SupportedProtos", Field, 8},
+		{"ClientHelloInfo.SupportedVersions", Field, 8},
+		{"ClientSessionCache", Type, 3},
+		{"ClientSessionState", Type, 3},
+		{"Config", Type, 0},
+		{"Config.Certificates", Field, 0},
+		{"Config.CipherSuites", Field, 0},
+		{"Config.ClientAuth", Field, 0},
+		{"Config.ClientCAs", Field, 0},
+		{"Config.ClientSessionCache", Field, 3},
+		{"Config.CurvePreferences", Field, 3},
+		{"Config.DynamicRecordSizingDisabled", Field, 7},
+		{"Config.EncryptedClientHelloConfigList", Field, 23},
+		{"Config.EncryptedClientHelloKeys", Field, 24},
+		{"Config.EncryptedClientHelloRejectionVerify", Field, 23},
+		{"Config.GetCertificate", Field, 4},
+		{"Config.GetClientCertificate", Field, 8},
+		{"Config.GetConfigForClient", Field, 8},
+		{"Config.InsecureSkipVerify", Field, 0},
+		{"Config.KeyLogWriter", Field, 8},
+		{"Config.MaxVersion", Field, 2},
+		{"Config.MinVersion", Field, 2},
+		{"Config.NameToCertificate", Field, 0},
+		{"Config.NextProtos", Field, 0},
+		{"Config.PreferServerCipherSuites", Field, 1},
+		{"Config.Rand", Field, 0},
+		{"Config.Renegotiation", Field, 7},
+		{"Config.RootCAs", Field, 0},
+		{"Config.ServerName", Field, 0},
+		{"Config.SessionTicketKey", Field, 1},
+		{"Config.SessionTicketsDisabled", Field, 1},
+		{"Config.Time", Field, 0},
+		{"Config.UnwrapSession", Field, 21},
+		{"Config.VerifyConnection", Field, 15},
+		{"Config.VerifyPeerCertificate", Field, 8},
+		{"Config.WrapSession", Field, 21},
+		{"Conn", Type, 0},
+		{"ConnectionState", Type, 0},
+		{"ConnectionState.CipherSuite", Field, 0},
+		{"ConnectionState.DidResume", Field, 1},
+		{"ConnectionState.ECHAccepted", Field, 23},
+		{"ConnectionState.HandshakeComplete", Field, 0},
+		{"ConnectionState.NegotiatedProtocol", Field, 0},
+		{"ConnectionState.NegotiatedProtocolIsMutual", Field, 0},
+		{"ConnectionState.OCSPResponse", Field, 5},
+		{"ConnectionState.PeerCertificates", Field, 0},
+		{"ConnectionState.ServerName", Field, 0},
+		{"ConnectionState.SignedCertificateTimestamps", Field, 5},
+		{"ConnectionState.TLSUnique", Field, 4},
+		{"ConnectionState.VerifiedChains", Field, 0},
+		{"ConnectionState.Version", Field, 3},
+		{"CurveID", Type, 3},
+		{"CurveP256", Const, 3},
+		{"CurveP384", Const, 3},
+		{"CurveP521", Const, 3},
+		{"Dial", Func, 0},
+		{"DialWithDialer", Func, 3},
+		{"Dialer", Type, 15},
+		{"Dialer.Config", Field, 15},
+		{"Dialer.NetDialer", Field, 15},
+		{"ECDSAWithP256AndSHA256", Const, 8},
+		{"ECDSAWithP384AndSHA384", Const, 8},
+		{"ECDSAWithP521AndSHA512", Const, 8},
+		{"ECDSAWithSHA1", Const, 10},
+		{"ECHRejectionError", Type, 23},
+		{"ECHRejectionError.RetryConfigList", Field, 23},
+		{"Ed25519", Const, 13},
+		{"EncryptedClientHelloKey", Type, 24},
+		{"EncryptedClientHelloKey.Config", Field, 24},
+		{"EncryptedClientHelloKey.PrivateKey", Field, 24},
+		{"EncryptedClientHelloKey.SendAsRetry", Field, 24},
+		{"InsecureCipherSuites", Func, 14},
+		{"Listen", Func, 0},
+		{"LoadX509KeyPair", Func, 0},
+		{"NewLRUClientSessionCache", Func, 3},
+		{"NewListener", Func, 0},
+		{"NewResumptionState", Func, 21},
+		{"NoClientCert", Const, 0},
+		{"PKCS1WithSHA1", Const, 8},
+		{"PKCS1WithSHA256", Const, 8},
+		{"PKCS1WithSHA384", Const, 8},
+		{"PKCS1WithSHA512", Const, 8},
+		{"PSSWithSHA256", Const, 8},
+		{"PSSWithSHA384", Const, 8},
+		{"PSSWithSHA512", Const, 8},
+		{"ParseSessionState", Func, 21},
+		{"QUICClient", Func, 21},
+		{"QUICConfig", Type, 21},
+		{"QUICConfig.EnableSessionEvents", Field, 23},
+		{"QUICConfig.TLSConfig", Field, 21},
+		{"QUICConn", Type, 21},
+		{"QUICEncryptionLevel", Type, 21},
+		{"QUICEncryptionLevelApplication", Const, 21},
+		{"QUICEncryptionLevelEarly", Const, 21},
+		{"QUICEncryptionLevelHandshake", Const, 21},
+		{"QUICEncryptionLevelInitial", Const, 21},
+		{"QUICEvent", Type, 21},
+		{"QUICEvent.Data", Field, 21},
+		{"QUICEvent.Kind", Field, 21},
+		{"QUICEvent.Level", Field, 21},
+		{"QUICEvent.SessionState", Field, 23},
+		{"QUICEvent.Suite", Field, 21},
+		{"QUICEventKind", Type, 21},
+		{"QUICHandshakeDone", Const, 21},
+		{"QUICNoEvent", Const, 21},
+		{"QUICRejectedEarlyData", Const, 21},
+		{"QUICResumeSession", Const, 23},
+		{"QUICServer", Func, 21},
+		{"QUICSessionTicketOptions", Type, 21},
+		{"QUICSessionTicketOptions.EarlyData", Field, 21},
+		{"QUICSessionTicketOptions.Extra", Field, 23},
+		{"QUICSetReadSecret", Const, 21},
+		{"QUICSetWriteSecret", Const, 21},
+		{"QUICStoreSession", Const, 23},
+		{"QUICTransportParameters", Const, 21},
+		{"QUICTransportParametersRequired", Const, 21},
+		{"QUICWriteData", Const, 21},
+		{"RecordHeaderError", Type, 6},
+		{"RecordHeaderError.Conn", Field, 12},
+		{"RecordHeaderError.Msg", Field, 6},
+		{"RecordHeaderError.RecordHeader", Field, 6},
+		{"RenegotiateFreelyAsClient", Const, 7},
+		{"RenegotiateNever", Const, 7},
+		{"RenegotiateOnceAsClient", Const, 7},
+		{"RenegotiationSupport", Type, 7},
+		{"RequestClientCert", Const, 0},
+		{"RequireAndVerifyClientCert", Const, 0},
+		{"RequireAnyClientCert", Const, 0},
+		{"Server", Func, 0},
+		{"SessionState", Type, 21},
+		{"SessionState.EarlyData", Field, 21},
+		{"SessionState.Extra", Field, 21},
+		{"SignatureScheme", Type, 8},
+		{"TLS_AES_128_GCM_SHA256", Const, 12},
+		{"TLS_AES_256_GCM_SHA384", Const, 12},
+		{"TLS_CHACHA20_POLY1305_SHA256", Const, 12},
+		{"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", Const, 2},
+		{"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", Const, 8},
+		{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", Const, 2},
+		{"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", Const, 2},
+		{"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", Const, 5},
+		{"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", Const, 8},
+		{"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", Const, 14},
+		{"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", Const, 2},
+		{"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", Const, 0},
+		{"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", Const, 0},
+		{"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", Const, 8},
+		{"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", Const, 2},
+		{"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", Const, 1},
+		{"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", Const, 5},
+		{"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", Const, 8},
+		{"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", Const, 14},
+		{"TLS_ECDHE_RSA_WITH_RC4_128_SHA", Const, 0},
+		{"TLS_FALLBACK_SCSV", Const, 4},
+		{"TLS_RSA_WITH_3DES_EDE_CBC_SHA", Const, 0},
+		{"TLS_RSA_WITH_AES_128_CBC_SHA", Const, 0},
+		{"TLS_RSA_WITH_AES_128_CBC_SHA256", Const, 8},
+		{"TLS_RSA_WITH_AES_128_GCM_SHA256", Const, 6},
+		{"TLS_RSA_WITH_AES_256_CBC_SHA", Const, 1},
+		{"TLS_RSA_WITH_AES_256_GCM_SHA384", Const, 6},
+		{"TLS_RSA_WITH_RC4_128_SHA", Const, 0},
+		{"VerifyClientCertIfGiven", Const, 0},
+		{"VersionName", Func, 21},
+		{"VersionSSL30", Const, 2},
+		{"VersionTLS10", Const, 2},
+		{"VersionTLS11", Const, 2},
+		{"VersionTLS12", Const, 2},
+		{"VersionTLS13", Const, 12},
+		{"X25519", Const, 8},
+		{"X25519MLKEM768", Const, 24},
+		{"X509KeyPair", Func, 0},
+	},
+	"crypto/x509": {
+		{"(*CertPool).AddCert", Method, 0},
+		{"(*CertPool).AddCertWithConstraint", Method, 22},
+		{"(*CertPool).AppendCertsFromPEM", Method, 0},
+		{"(*CertPool).Clone", Method, 19},
+		{"(*CertPool).Equal", Method, 19},
+		{"(*CertPool).Subjects", Method, 0},
+		{"(*Certificate).CheckCRLSignature", Method, 0},
+		{"(*Certificate).CheckSignature", Method, 0},
+		{"(*Certificate).CheckSignatureFrom", Method, 0},
+		{"(*Certificate).CreateCRL", Method, 0},
+		{"(*Certificate).Equal", Method, 0},
+		{"(*Certificate).Verify", Method, 0},
+		{"(*Certificate).VerifyHostname", Method, 0},
+		{"(*CertificateRequest).CheckSignature", Method, 5},
+		{"(*OID).UnmarshalBinary", Method, 23},
+		{"(*OID).UnmarshalText", Method, 23},
+		{"(*RevocationList).CheckSignatureFrom", Method, 19},
+		{"(CertificateInvalidError).Error", Method, 0},
+		{"(ConstraintViolationError).Error", Method, 0},
+		{"(HostnameError).Error", Method, 0},
+		{"(InsecureAlgorithmError).Error", Method, 6},
+		{"(OID).AppendBinary", Method, 24},
+		{"(OID).AppendText", Method, 24},
+		{"(OID).Equal", Method, 22},
+		{"(OID).EqualASN1OID", Method, 22},
+		{"(OID).MarshalBinary", Method, 23},
+		{"(OID).MarshalText", Method, 23},
+		{"(OID).String", Method, 22},
+		{"(PublicKeyAlgorithm).String", Method, 10},
+		{"(SignatureAlgorithm).String", Method, 6},
+		{"(SystemRootsError).Error", Method, 1},
+		{"(SystemRootsError).Unwrap", Method, 16},
+		{"(UnhandledCriticalExtension).Error", Method, 0},
+		{"(UnknownAuthorityError).Error", Method, 0},
+		{"CANotAuthorizedForExtKeyUsage", Const, 10},
+		{"CANotAuthorizedForThisName", Const, 0},
+		{"CertPool", Type, 0},
+		{"Certificate", Type, 0},
+		{"Certificate.AuthorityKeyId", Field, 0},
+		{"Certificate.BasicConstraintsValid", Field, 0},
+		{"Certificate.CRLDistributionPoints", Field, 2},
+		{"Certificate.DNSNames", Field, 0},
+		{"Certificate.EmailAddresses", Field, 0},
+		{"Certificate.ExcludedDNSDomains", Field, 9},
+		{"Certificate.ExcludedEmailAddresses", Field, 10},
+		{"Certificate.ExcludedIPRanges", Field, 10},
+		{"Certificate.ExcludedURIDomains", Field, 10},
+		{"Certificate.ExtKeyUsage", Field, 0},
+		{"Certificate.Extensions", Field, 2},
+		{"Certificate.ExtraExtensions", Field, 2},
+		{"Certificate.IPAddresses", Field, 1},
+		{"Certificate.InhibitAnyPolicy", Field, 24},
+		{"Certificate.InhibitAnyPolicyZero", Field, 24},
+		{"Certificate.InhibitPolicyMapping", Field, 24},
+		{"Certificate.InhibitPolicyMappingZero", Field, 24},
+		{"Certificate.IsCA", Field, 0},
+		{"Certificate.Issuer", Field, 0},
+		{"Certificate.IssuingCertificateURL", Field, 2},
+		{"Certificate.KeyUsage", Field, 0},
+		{"Certificate.MaxPathLen", Field, 0},
+		{"Certificate.MaxPathLenZero", Field, 4},
+		{"Certificate.NotAfter", Field, 0},
+		{"Certificate.NotBefore", Field, 0},
+		{"Certificate.OCSPServer", Field, 2},
+		{"Certificate.PermittedDNSDomains", Field, 0},
+		{"Certificate.PermittedDNSDomainsCritical", Field, 0},
+		{"Certificate.PermittedEmailAddresses", Field, 10},
+		{"Certificate.PermittedIPRanges", Field, 10},
+		{"Certificate.PermittedURIDomains", Field, 10},
+		{"Certificate.Policies", Field, 22},
+		{"Certificate.PolicyIdentifiers", Field, 0},
+		{"Certificate.PolicyMappings", Field, 24},
+		{"Certificate.PublicKey", Field, 0},
+		{"Certificate.PublicKeyAlgorithm", Field, 0},
+		{"Certificate.Raw", Field, 0},
+		{"Certificate.RawIssuer", Field, 0},
+		{"Certificate.RawSubject", Field, 0},
+		{"Certificate.RawSubjectPublicKeyInfo", Field, 0},
+		{"Certificate.RawTBSCertificate", Field, 0},
+		{"Certificate.RequireExplicitPolicy", Field, 24},
+		{"Certificate.RequireExplicitPolicyZero", Field, 24},
+		{"Certificate.SerialNumber", Field, 0},
+		{"Certificate.Signature", Field, 0},
+		{"Certificate.SignatureAlgorithm", Field, 0},
+		{"Certificate.Subject", Field, 0},
+		{"Certificate.SubjectKeyId", Field, 0},
+		{"Certificate.URIs", Field, 10},
+		{"Certificate.UnhandledCriticalExtensions", Field, 5},
+		{"Certificate.UnknownExtKeyUsage", Field, 0},
+		{"Certificate.Version", Field, 0},
+		{"CertificateInvalidError", Type, 0},
+		{"CertificateInvalidError.Cert", Field, 0},
+		{"CertificateInvalidError.Detail", Field, 10},
+		{"CertificateInvalidError.Reason", Field, 0},
+		{"CertificateRequest", Type, 3},
+		{"CertificateRequest.Attributes", Field, 3},
+		{"CertificateRequest.DNSNames", Field, 3},
+		{"CertificateRequest.EmailAddresses", Field, 3},
+		{"CertificateRequest.Extensions", Field, 3},
+		{"CertificateRequest.ExtraExtensions", Field, 3},
+		{"CertificateRequest.IPAddresses", Field, 3},
+		{"CertificateRequest.PublicKey", Field, 3},
+		{"CertificateRequest.PublicKeyAlgorithm", Field, 3},
+		{"CertificateRequest.Raw", Field, 3},
+		{"CertificateRequest.RawSubject", Field, 3},
+		{"CertificateRequest.RawSubjectPublicKeyInfo", Field, 3},
+		{"CertificateRequest.RawTBSCertificateRequest", Field, 3},
+		{"CertificateRequest.Signature", Field, 3},
+		{"CertificateRequest.SignatureAlgorithm", Field, 3},
+		{"CertificateRequest.Subject", Field, 3},
+		{"CertificateRequest.URIs", Field, 10},
+		{"CertificateRequest.Version", Field, 3},
+		{"ConstraintViolationError", Type, 0},
+		{"CreateCertificate", Func, 0},
+		{"CreateCertificateRequest", Func, 3},
+		{"CreateRevocationList", Func, 15},
+		{"DSA", Const, 0},
+		{"DSAWithSHA1", Const, 0},
+		{"DSAWithSHA256", Const, 0},
+		{"DecryptPEMBlock", Func, 1},
+		{"ECDSA", Const, 1},
+		{"ECDSAWithSHA1", Const, 1},
+		{"ECDSAWithSHA256", Const, 1},
+		{"ECDSAWithSHA384", Const, 1},
+		{"ECDSAWithSHA512", Const, 1},
+		{"Ed25519", Const, 13},
+		{"EncryptPEMBlock", Func, 1},
+		{"ErrUnsupportedAlgorithm", Var, 0},
+		{"Expired", Const, 0},
+		{"ExtKeyUsage", Type, 0},
+		{"ExtKeyUsageAny", Const, 0},
+		{"ExtKeyUsageClientAuth", Const, 0},
+		{"ExtKeyUsageCodeSigning", Const, 0},
+		{"ExtKeyUsageEmailProtection", Const, 0},
+		{"ExtKeyUsageIPSECEndSystem", Const, 1},
+		{"ExtKeyUsageIPSECTunnel", Const, 1},
+		{"ExtKeyUsageIPSECUser", Const, 1},
+		{"ExtKeyUsageMicrosoftCommercialCodeSigning", Const, 10},
+		{"ExtKeyUsageMicrosoftKernelCodeSigning", Const, 10},
+		{"ExtKeyUsageMicrosoftServerGatedCrypto", Const, 1},
+		{"ExtKeyUsageNetscapeServerGatedCrypto", Const, 1},
+		{"ExtKeyUsageOCSPSigning", Const, 0},
+		{"ExtKeyUsageServerAuth", Const, 0},
+		{"ExtKeyUsageTimeStamping", Const, 0},
+		{"HostnameError", Type, 0},
+		{"HostnameError.Certificate", Field, 0},
+		{"HostnameError.Host", Field, 0},
+		{"IncompatibleUsage", Const, 1},
+		{"IncorrectPasswordError", Var, 1},
+		{"InsecureAlgorithmError", Type, 6},
+		{"InvalidReason", Type, 0},
+		{"IsEncryptedPEMBlock", Func, 1},
+		{"KeyUsage", Type, 0},
+		{"KeyUsageCRLSign", Const, 0},
+		{"KeyUsageCertSign", Const, 0},
+		{"KeyUsageContentCommitment", Const, 0},
+		{"KeyUsageDataEncipherment", Const, 0},
+		{"KeyUsageDecipherOnly", Const, 0},
+		{"KeyUsageDigitalSignature", Const, 0},
+		{"KeyUsageEncipherOnly", Const, 0},
+		{"KeyUsageKeyAgreement", Const, 0},
+		{"KeyUsageKeyEncipherment", Const, 0},
+		{"MD2WithRSA", Const, 0},
+		{"MD5WithRSA", Const, 0},
+		{"MarshalECPrivateKey", Func, 2},
+		{"MarshalPKCS1PrivateKey", Func, 0},
+		{"MarshalPKCS1PublicKey", Func, 10},
+		{"MarshalPKCS8PrivateKey", Func, 10},
+		{"MarshalPKIXPublicKey", Func, 0},
+		{"NameConstraintsWithoutSANs", Const, 10},
+		{"NameMismatch", Const, 8},
+		{"NewCertPool", Func, 0},
+		{"NoValidChains", Const, 24},
+		{"NotAuthorizedToSign", Const, 0},
+		{"OID", Type, 22},
+		{"OIDFromInts", Func, 22},
+		{"PEMCipher", Type, 1},
+		{"PEMCipher3DES", Const, 1},
+		{"PEMCipherAES128", Const, 1},
+		{"PEMCipherAES192", Const, 1},
+		{"PEMCipherAES256", Const, 1},
+		{"PEMCipherDES", Const, 1},
+		{"ParseCRL", Func, 0},
+		{"ParseCertificate", Func, 0},
+		{"ParseCertificateRequest", Func, 3},
+		{"ParseCertificates", Func, 0},
+		{"ParseDERCRL", Func, 0},
+		{"ParseECPrivateKey", Func, 1},
+		{"ParseOID", Func, 23},
+		{"ParsePKCS1PrivateKey", Func, 0},
+		{"ParsePKCS1PublicKey", Func, 10},
+		{"ParsePKCS8PrivateKey", Func, 0},
+		{"ParsePKIXPublicKey", Func, 0},
+		{"ParseRevocationList", Func, 19},
+		{"PolicyMapping", Type, 24},
+		{"PolicyMapping.IssuerDomainPolicy", Field, 24},
+		{"PolicyMapping.SubjectDomainPolicy", Field, 24},
+		{"PublicKeyAlgorithm", Type, 0},
+		{"PureEd25519", Const, 13},
+		{"RSA", Const, 0},
+		{"RevocationList", Type, 15},
+		{"RevocationList.AuthorityKeyId", Field, 19},
+		{"RevocationList.Extensions", Field, 19},
+		{"RevocationList.ExtraExtensions", Field, 15},
+		{"RevocationList.Issuer", Field, 19},
+		{"RevocationList.NextUpdate", Field, 15},
+		{"RevocationList.Number", Field, 15},
+		{"RevocationList.Raw", Field, 19},
+		{"RevocationList.RawIssuer", Field, 19},
+		{"RevocationList.RawTBSRevocationList", Field, 19},
+		{"RevocationList.RevokedCertificateEntries", Field, 21},
+		{"RevocationList.RevokedCertificates", Field, 15},
+		{"RevocationList.Signature", Field, 19},
+		{"RevocationList.SignatureAlgorithm", Field, 15},
+		{"RevocationList.ThisUpdate", Field, 15},
+		{"RevocationListEntry", Type, 21},
+		{"RevocationListEntry.Extensions", Field, 21},
+		{"RevocationListEntry.ExtraExtensions", Field, 21},
+		{"RevocationListEntry.Raw", Field, 21},
+		{"RevocationListEntry.ReasonCode", Field, 21},
+		{"RevocationListEntry.RevocationTime", Field, 21},
+		{"RevocationListEntry.SerialNumber", Field, 21},
+		{"SHA1WithRSA", Const, 0},
+		{"SHA256WithRSA", Const, 0},
+		{"SHA256WithRSAPSS", Const, 8},
+		{"SHA384WithRSA", Const, 0},
+		{"SHA384WithRSAPSS", Const, 8},
+		{"SHA512WithRSA", Const, 0},
+		{"SHA512WithRSAPSS", Const, 8},
+		{"SetFallbackRoots", Func, 20},
+		{"SignatureAlgorithm", Type, 0},
+		{"SystemCertPool", Func, 7},
+		{"SystemRootsError", Type, 1},
+		{"SystemRootsError.Err", Field, 7},
+		{"TooManyConstraints", Const, 10},
+		{"TooManyIntermediates", Const, 0},
+		{"UnconstrainedName", Const, 10},
+		{"UnhandledCriticalExtension", Type, 0},
+		{"UnknownAuthorityError", Type, 0},
+		{"UnknownAuthorityError.Cert", Field, 8},
+		{"UnknownPublicKeyAlgorithm", Const, 0},
+		{"UnknownSignatureAlgorithm", Const, 0},
+		{"VerifyOptions", Type, 0},
+		{"VerifyOptions.CertificatePolicies", Field, 24},
+		{"VerifyOptions.CurrentTime", Field, 0},
+		{"VerifyOptions.DNSName", Field, 0},
+		{"VerifyOptions.Intermediates", Field, 0},
+		{"VerifyOptions.KeyUsages", Field, 1},
+		{"VerifyOptions.MaxConstraintComparisions", Field, 10},
+		{"VerifyOptions.Roots", Field, 0},
+	},
+	"crypto/x509/pkix": {
+		{"(*CertificateList).HasExpired", Method, 0},
+		{"(*Name).FillFromRDNSequence", Method, 0},
+		{"(Name).String", Method, 10},
+		{"(Name).ToRDNSequence", Method, 0},
+		{"(RDNSequence).String", Method, 10},
+		{"AlgorithmIdentifier", Type, 0},
+		{"AlgorithmIdentifier.Algorithm", Field, 0},
+		{"AlgorithmIdentifier.Parameters", Field, 0},
+		{"AttributeTypeAndValue", Type, 0},
+		{"AttributeTypeAndValue.Type", Field, 0},
+		{"AttributeTypeAndValue.Value", Field, 0},
+		{"AttributeTypeAndValueSET", Type, 3},
+		{"AttributeTypeAndValueSET.Type", Field, 3},
+		{"AttributeTypeAndValueSET.Value", Field, 3},
+		{"CertificateList", Type, 0},
+		{"CertificateList.SignatureAlgorithm", Field, 0},
+		{"CertificateList.SignatureValue", Field, 0},
+		{"CertificateList.TBSCertList", Field, 0},
+		{"Extension", Type, 0},
+		{"Extension.Critical", Field, 0},
+		{"Extension.Id", Field, 0},
+		{"Extension.Value", Field, 0},
+		{"Name", Type, 0},
+		{"Name.CommonName", Field, 0},
+		{"Name.Country", Field, 0},
+		{"Name.ExtraNames", Field, 5},
+		{"Name.Locality", Field, 0},
+		{"Name.Names", Field, 0},
+		{"Name.Organization", Field, 0},
+		{"Name.OrganizationalUnit", Field, 0},
+		{"Name.PostalCode", Field, 0},
+		{"Name.Province", Field, 0},
+		{"Name.SerialNumber", Field, 0},
+		{"Name.StreetAddress", Field, 0},
+		{"RDNSequence", Type, 0},
+		{"RelativeDistinguishedNameSET", Type, 0},
+		{"RevokedCertificate", Type, 0},
+		{"RevokedCertificate.Extensions", Field, 0},
+		{"RevokedCertificate.RevocationTime", Field, 0},
+		{"RevokedCertificate.SerialNumber", Field, 0},
+		{"TBSCertificateList", Type, 0},
+		{"TBSCertificateList.Extensions", Field, 0},
+		{"TBSCertificateList.Issuer", Field, 0},
+		{"TBSCertificateList.NextUpdate", Field, 0},
+		{"TBSCertificateList.Raw", Field, 0},
+		{"TBSCertificateList.RevokedCertificates", Field, 0},
+		{"TBSCertificateList.Signature", Field, 0},
+		{"TBSCertificateList.ThisUpdate", Field, 0},
+		{"TBSCertificateList.Version", Field, 0},
+	},
+	"database/sql": {
+		{"(*ColumnType).DatabaseTypeName", Method, 8},
+		{"(*ColumnType).DecimalSize", Method, 8},
+		{"(*ColumnType).Length", Method, 8},
+		{"(*ColumnType).Name", Method, 8},
+		{"(*ColumnType).Nullable", Method, 8},
+		{"(*ColumnType).ScanType", Method, 8},
+		{"(*Conn).BeginTx", Method, 9},
+		{"(*Conn).Close", Method, 9},
+		{"(*Conn).ExecContext", Method, 9},
+		{"(*Conn).PingContext", Method, 9},
+		{"(*Conn).PrepareContext", Method, 9},
+		{"(*Conn).QueryContext", Method, 9},
+		{"(*Conn).QueryRowContext", Method, 9},
+		{"(*Conn).Raw", Method, 13},
+		{"(*DB).Begin", Method, 0},
+		{"(*DB).BeginTx", Method, 8},
+		{"(*DB).Close", Method, 0},
+		{"(*DB).Conn", Method, 9},
+		{"(*DB).Driver", Method, 0},
+		{"(*DB).Exec", Method, 0},
+		{"(*DB).ExecContext", Method, 8},
+		{"(*DB).Ping", Method, 1},
+		{"(*DB).PingContext", Method, 8},
+		{"(*DB).Prepare", Method, 0},
+		{"(*DB).PrepareContext", Method, 8},
+		{"(*DB).Query", Method, 0},
+		{"(*DB).QueryContext", Method, 8},
+		{"(*DB).QueryRow", Method, 0},
+		{"(*DB).QueryRowContext", Method, 8},
+		{"(*DB).SetConnMaxIdleTime", Method, 15},
+		{"(*DB).SetConnMaxLifetime", Method, 6},
+		{"(*DB).SetMaxIdleConns", Method, 1},
+		{"(*DB).SetMaxOpenConns", Method, 2},
+		{"(*DB).Stats", Method, 5},
+		{"(*Null).Scan", Method, 22},
+		{"(*NullBool).Scan", Method, 0},
+		{"(*NullByte).Scan", Method, 17},
+		{"(*NullFloat64).Scan", Method, 0},
+		{"(*NullInt16).Scan", Method, 17},
+		{"(*NullInt32).Scan", Method, 13},
+		{"(*NullInt64).Scan", Method, 0},
+		{"(*NullString).Scan", Method, 0},
+		{"(*NullTime).Scan", Method, 13},
+		{"(*Row).Err", Method, 15},
+		{"(*Row).Scan", Method, 0},
+		{"(*Rows).Close", Method, 0},
+		{"(*Rows).ColumnTypes", Method, 8},
+		{"(*Rows).Columns", Method, 0},
+		{"(*Rows).Err", Method, 0},
+		{"(*Rows).Next", Method, 0},
+		{"(*Rows).NextResultSet", Method, 8},
+		{"(*Rows).Scan", Method, 0},
+		{"(*Stmt).Close", Method, 0},
+		{"(*Stmt).Exec", Method, 0},
+		{"(*Stmt).ExecContext", Method, 8},
+		{"(*Stmt).Query", Method, 0},
+		{"(*Stmt).QueryContext", Method, 8},
+		{"(*Stmt).QueryRow", Method, 0},
+		{"(*Stmt).QueryRowContext", Method, 8},
+		{"(*Tx).Commit", Method, 0},
+		{"(*Tx).Exec", Method, 0},
+		{"(*Tx).ExecContext", Method, 8},
+		{"(*Tx).Prepare", Method, 0},
+		{"(*Tx).PrepareContext", Method, 8},
+		{"(*Tx).Query", Method, 0},
+		{"(*Tx).QueryContext", Method, 8},
+		{"(*Tx).QueryRow", Method, 0},
+		{"(*Tx).QueryRowContext", Method, 8},
+		{"(*Tx).Rollback", Method, 0},
+		{"(*Tx).Stmt", Method, 0},
+		{"(*Tx).StmtContext", Method, 8},
+		{"(IsolationLevel).String", Method, 11},
+		{"(Null).Value", Method, 22},
+		{"(NullBool).Value", Method, 0},
+		{"(NullByte).Value", Method, 17},
+		{"(NullFloat64).Value", Method, 0},
+		{"(NullInt16).Value", Method, 17},
+		{"(NullInt32).Value", Method, 13},
+		{"(NullInt64).Value", Method, 0},
+		{"(NullString).Value", Method, 0},
+		{"(NullTime).Value", Method, 13},
+		{"ColumnType", Type, 8},
+		{"Conn", Type, 9},
+		{"DB", Type, 0},
+		{"DBStats", Type, 5},
+		{"DBStats.Idle", Field, 11},
+		{"DBStats.InUse", Field, 11},
+		{"DBStats.MaxIdleClosed", Field, 11},
+		{"DBStats.MaxIdleTimeClosed", Field, 15},
+		{"DBStats.MaxLifetimeClosed", Field, 11},
+		{"DBStats.MaxOpenConnections", Field, 11},
+		{"DBStats.OpenConnections", Field, 5},
+		{"DBStats.WaitCount", Field, 11},
+		{"DBStats.WaitDuration", Field, 11},
+		{"Drivers", Func, 4},
+		{"ErrConnDone", Var, 9},
+		{"ErrNoRows", Var, 0},
+		{"ErrTxDone", Var, 0},
+		{"IsolationLevel", Type, 8},
+		{"LevelDefault", Const, 8},
+		{"LevelLinearizable", Const, 8},
+		{"LevelReadCommitted", Const, 8},
+		{"LevelReadUncommitted", Const, 8},
+		{"LevelRepeatableRead", Const, 8},
+		{"LevelSerializable", Const, 8},
+		{"LevelSnapshot", Const, 8},
+		{"LevelWriteCommitted", Const, 8},
+		{"Named", Func, 8},
+		{"NamedArg", Type, 8},
+		{"NamedArg.Name", Field, 8},
+		{"NamedArg.Value", Field, 8},
+		{"Null", Type, 22},
+		{"Null.V", Field, 22},
+		{"Null.Valid", Field, 22},
+		{"NullBool", Type, 0},
+		{"NullBool.Bool", Field, 0},
+		{"NullBool.Valid", Field, 0},
+		{"NullByte", Type, 17},
+		{"NullByte.Byte", Field, 17},
+		{"NullByte.Valid", Field, 17},
+		{"NullFloat64", Type, 0},
+		{"NullFloat64.Float64", Field, 0},
+		{"NullFloat64.Valid", Field, 0},
+		{"NullInt16", Type, 17},
+		{"NullInt16.Int16", Field, 17},
+		{"NullInt16.Valid", Field, 17},
+		{"NullInt32", Type, 13},
+		{"NullInt32.Int32", Field, 13},
+		{"NullInt32.Valid", Field, 13},
+		{"NullInt64", Type, 0},
+		{"NullInt64.Int64", Field, 0},
+		{"NullInt64.Valid", Field, 0},
+		{"NullString", Type, 0},
+		{"NullString.String", Field, 0},
+		{"NullString.Valid", Field, 0},
+		{"NullTime", Type, 13},
+		{"NullTime.Time", Field, 13},
+		{"NullTime.Valid", Field, 13},
+		{"Open", Func, 0},
+		{"OpenDB", Func, 10},
+		{"Out", Type, 9},
+		{"Out.Dest", Field, 9},
+		{"Out.In", Field, 9},
+		{"RawBytes", Type, 0},
+		{"Register", Func, 0},
+		{"Result", Type, 0},
+		{"Row", Type, 0},
+		{"Rows", Type, 0},
+		{"Scanner", Type, 0},
+		{"Stmt", Type, 0},
+		{"Tx", Type, 0},
+		{"TxOptions", Type, 8},
+		{"TxOptions.Isolation", Field, 8},
+		{"TxOptions.ReadOnly", Field, 8},
+	},
+	"database/sql/driver": {
+		{"(NotNull).ConvertValue", Method, 0},
+		{"(Null).ConvertValue", Method, 0},
+		{"(RowsAffected).LastInsertId", Method, 0},
+		{"(RowsAffected).RowsAffected", Method, 0},
+		{"Bool", Var, 0},
+		{"ColumnConverter", Type, 0},
+		{"Conn", Type, 0},
+		{"ConnBeginTx", Type, 8},
+		{"ConnPrepareContext", Type, 8},
+		{"Connector", Type, 10},
+		{"DefaultParameterConverter", Var, 0},
+		{"Driver", Type, 0},
+		{"DriverContext", Type, 10},
+		{"ErrBadConn", Var, 0},
+		{"ErrRemoveArgument", Var, 9},
+		{"ErrSkip", Var, 0},
+		{"Execer", Type, 0},
+		{"ExecerContext", Type, 8},
+		{"Int32", Var, 0},
+		{"IsScanValue", Func, 0},
+		{"IsValue", Func, 0},
+		{"IsolationLevel", Type, 8},
+		{"NamedValue", Type, 8},
+		{"NamedValue.Name", Field, 8},
+		{"NamedValue.Ordinal", Field, 8},
+		{"NamedValue.Value", Field, 8},
+		{"NamedValueChecker", Type, 9},
+		{"NotNull", Type, 0},
+		{"NotNull.Converter", Field, 0},
+		{"Null", Type, 0},
+		{"Null.Converter", Field, 0},
+		{"Pinger", Type, 8},
+		{"Queryer", Type, 1},
+		{"QueryerContext", Type, 8},
+		{"Result", Type, 0},
+		{"ResultNoRows", Var, 0},
+		{"Rows", Type, 0},
+		{"RowsAffected", Type, 0},
+		{"RowsColumnTypeDatabaseTypeName", Type, 8},
+		{"RowsColumnTypeLength", Type, 8},
+		{"RowsColumnTypeNullable", Type, 8},
+		{"RowsColumnTypePrecisionScale", Type, 8},
+		{"RowsColumnTypeScanType", Type, 8},
+		{"RowsNextResultSet", Type, 8},
+		{"SessionResetter", Type, 10},
+		{"Stmt", Type, 0},
+		{"StmtExecContext", Type, 8},
+		{"StmtQueryContext", Type, 8},
+		{"String", Var, 0},
+		{"Tx", Type, 0},
+		{"TxOptions", Type, 8},
+		{"TxOptions.Isolation", Field, 8},
+		{"TxOptions.ReadOnly", Field, 8},
+		{"Validator", Type, 15},
+		{"Value", Type, 0},
+		{"ValueConverter", Type, 0},
+		{"Valuer", Type, 0},
+	},
+	"debug/buildinfo": {
+		{"BuildInfo", Type, 18},
+		{"Read", Func, 18},
+		{"ReadFile", Func, 18},
+	},
+	"debug/dwarf": {
+		{"(*AddrType).Basic", Method, 0},
+		{"(*AddrType).Common", Method, 0},
+		{"(*AddrType).Size", Method, 0},
+		{"(*AddrType).String", Method, 0},
+		{"(*ArrayType).Common", Method, 0},
+		{"(*ArrayType).Size", Method, 0},
+		{"(*ArrayType).String", Method, 0},
+		{"(*BasicType).Basic", Method, 0},
+		{"(*BasicType).Common", Method, 0},
+		{"(*BasicType).Size", Method, 0},
+		{"(*BasicType).String", Method, 0},
+		{"(*BoolType).Basic", Method, 0},
+		{"(*BoolType).Common", Method, 0},
+		{"(*BoolType).Size", Method, 0},
+		{"(*BoolType).String", Method, 0},
+		{"(*CharType).Basic", Method, 0},
+		{"(*CharType).Common", Method, 0},
+		{"(*CharType).Size", Method, 0},
+		{"(*CharType).String", Method, 0},
+		{"(*CommonType).Common", Method, 0},
+		{"(*CommonType).Size", Method, 0},
+		{"(*ComplexType).Basic", Method, 0},
+		{"(*ComplexType).Common", Method, 0},
+		{"(*ComplexType).Size", Method, 0},
+		{"(*ComplexType).String", Method, 0},
+		{"(*Data).AddSection", Method, 14},
+		{"(*Data).AddTypes", Method, 3},
+		{"(*Data).LineReader", Method, 5},
+		{"(*Data).Ranges", Method, 7},
+		{"(*Data).Reader", Method, 0},
+		{"(*Data).Type", Method, 0},
+		{"(*DotDotDotType).Common", Method, 0},
+		{"(*DotDotDotType).Size", Method, 0},
+		{"(*DotDotDotType).String", Method, 0},
+		{"(*Entry).AttrField", Method, 5},
+		{"(*Entry).Val", Method, 0},
+		{"(*EnumType).Common", Method, 0},
+		{"(*EnumType).Size", Method, 0},
+		{"(*EnumType).String", Method, 0},
+		{"(*FloatType).Basic", Method, 0},
+		{"(*FloatType).Common", Method, 0},
+		{"(*FloatType).Size", Method, 0},
+		{"(*FloatType).String", Method, 0},
+		{"(*FuncType).Common", Method, 0},
+		{"(*FuncType).Size", Method, 0},
+		{"(*FuncType).String", Method, 0},
+		{"(*IntType).Basic", Method, 0},
+		{"(*IntType).Common", Method, 0},
+		{"(*IntType).Size", Method, 0},
+		{"(*IntType).String", Method, 0},
+		{"(*LineReader).Files", Method, 14},
+		{"(*LineReader).Next", Method, 5},
+		{"(*LineReader).Reset", Method, 5},
+		{"(*LineReader).Seek", Method, 5},
+		{"(*LineReader).SeekPC", Method, 5},
+		{"(*LineReader).Tell", Method, 5},
+		{"(*PtrType).Common", Method, 0},
+		{"(*PtrType).Size", Method, 0},
+		{"(*PtrType).String", Method, 0},
+		{"(*QualType).Common", Method, 0},
+		{"(*QualType).Size", Method, 0},
+		{"(*QualType).String", Method, 0},
+		{"(*Reader).AddressSize", Method, 5},
+		{"(*Reader).ByteOrder", Method, 14},
+		{"(*Reader).Next", Method, 0},
+		{"(*Reader).Seek", Method, 0},
+		{"(*Reader).SeekPC", Method, 7},
+		{"(*Reader).SkipChildren", Method, 0},
+		{"(*StructType).Common", Method, 0},
+		{"(*StructType).Defn", Method, 0},
+		{"(*StructType).Size", Method, 0},
+		{"(*StructType).String", Method, 0},
+		{"(*TypedefType).Common", Method, 0},
+		{"(*TypedefType).Size", Method, 0},
+		{"(*TypedefType).String", Method, 0},
+		{"(*UcharType).Basic", Method, 0},
+		{"(*UcharType).Common", Method, 0},
+		{"(*UcharType).Size", Method, 0},
+		{"(*UcharType).String", Method, 0},
+		{"(*UintType).Basic", Method, 0},
+		{"(*UintType).Common", Method, 0},
+		{"(*UintType).Size", Method, 0},
+		{"(*UintType).String", Method, 0},
+		{"(*UnspecifiedType).Basic", Method, 4},
+		{"(*UnspecifiedType).Common", Method, 4},
+		{"(*UnspecifiedType).Size", Method, 4},
+		{"(*UnspecifiedType).String", Method, 4},
+		{"(*UnsupportedType).Common", Method, 13},
+		{"(*UnsupportedType).Size", Method, 13},
+		{"(*UnsupportedType).String", Method, 13},
+		{"(*VoidType).Common", Method, 0},
+		{"(*VoidType).Size", Method, 0},
+		{"(*VoidType).String", Method, 0},
+		{"(Attr).GoString", Method, 0},
+		{"(Attr).String", Method, 0},
+		{"(Class).GoString", Method, 5},
+		{"(Class).String", Method, 5},
+		{"(DecodeError).Error", Method, 0},
+		{"(Tag).GoString", Method, 0},
+		{"(Tag).String", Method, 0},
+		{"AddrType", Type, 0},
+		{"AddrType.BasicType", Field, 0},
+		{"ArrayType", Type, 0},
+		{"ArrayType.CommonType", Field, 0},
+		{"ArrayType.Count", Field, 0},
+		{"ArrayType.StrideBitSize", Field, 0},
+		{"ArrayType.Type", Field, 0},
+		{"Attr", Type, 0},
+		{"AttrAbstractOrigin", Const, 0},
+		{"AttrAccessibility", Const, 0},
+		{"AttrAddrBase", Const, 14},
+		{"AttrAddrClass", Const, 0},
+		{"AttrAlignment", Const, 14},
+		{"AttrAllocated", Const, 0},
+		{"AttrArtificial", Const, 0},
+		{"AttrAssociated", Const, 0},
+		{"AttrBaseTypes", Const, 0},
+		{"AttrBinaryScale", Const, 14},
+		{"AttrBitOffset", Const, 0},
+		{"AttrBitSize", Const, 0},
+		{"AttrByteSize", Const, 0},
+		{"AttrCallAllCalls", Const, 14},
+		{"AttrCallAllSourceCalls", Const, 14},
+		{"AttrCallAllTailCalls", Const, 14},
+		{"AttrCallColumn", Const, 0},
+		{"AttrCallDataLocation", Const, 14},
+		{"AttrCallDataValue", Const, 14},
+		{"AttrCallFile", Const, 0},
+		{"AttrCallLine", Const, 0},
+		{"AttrCallOrigin", Const, 14},
+		{"AttrCallPC", Const, 14},
+		{"AttrCallParameter", Const, 14},
+		{"AttrCallReturnPC", Const, 14},
+		{"AttrCallTailCall", Const, 14},
+		{"AttrCallTarget", Const, 14},
+		{"AttrCallTargetClobbered", Const, 14},
+		{"AttrCallValue", Const, 14},
+		{"AttrCalling", Const, 0},
+		{"AttrCommonRef", Const, 0},
+		{"AttrCompDir", Const, 0},
+		{"AttrConstExpr", Const, 14},
+		{"AttrConstValue", Const, 0},
+		{"AttrContainingType", Const, 0},
+		{"AttrCount", Const, 0},
+		{"AttrDataBitOffset", Const, 14},
+		{"AttrDataLocation", Const, 0},
+		{"AttrDataMemberLoc", Const, 0},
+		{"AttrDecimalScale", Const, 14},
+		{"AttrDecimalSign", Const, 14},
+		{"AttrDeclColumn", Const, 0},
+		{"AttrDeclFile", Const, 0},
+		{"AttrDeclLine", Const, 0},
+		{"AttrDeclaration", Const, 0},
+		{"AttrDefaultValue", Const, 0},
+		{"AttrDefaulted", Const, 14},
+		{"AttrDeleted", Const, 14},
+		{"AttrDescription", Const, 0},
+		{"AttrDigitCount", Const, 14},
+		{"AttrDiscr", Const, 0},
+		{"AttrDiscrList", Const, 0},
+		{"AttrDiscrValue", Const, 0},
+		{"AttrDwoName", Const, 14},
+		{"AttrElemental", Const, 14},
+		{"AttrEncoding", Const, 0},
+		{"AttrEndianity", Const, 14},
+		{"AttrEntrypc", Const, 0},
+		{"AttrEnumClass", Const, 14},
+		{"AttrExplicit", Const, 14},
+		{"AttrExportSymbols", Const, 14},
+		{"AttrExtension", Const, 0},
+		{"AttrExternal", Const, 0},
+		{"AttrFrameBase", Const, 0},
+		{"AttrFriend", Const, 0},
+		{"AttrHighpc", Const, 0},
+		{"AttrIdentifierCase", Const, 0},
+		{"AttrImport", Const, 0},
+		{"AttrInline", Const, 0},
+		{"AttrIsOptional", Const, 0},
+		{"AttrLanguage", Const, 0},
+		{"AttrLinkageName", Const, 14},
+		{"AttrLocation", Const, 0},
+		{"AttrLoclistsBase", Const, 14},
+		{"AttrLowerBound", Const, 0},
+		{"AttrLowpc", Const, 0},
+		{"AttrMacroInfo", Const, 0},
+		{"AttrMacros", Const, 14},
+		{"AttrMainSubprogram", Const, 14},
+		{"AttrMutable", Const, 14},
+		{"AttrName", Const, 0},
+		{"AttrNamelistItem", Const, 0},
+		{"AttrNoreturn", Const, 14},
+		{"AttrObjectPointer", Const, 14},
+		{"AttrOrdering", Const, 0},
+		{"AttrPictureString", Const, 14},
+		{"AttrPriority", Const, 0},
+		{"AttrProducer", Const, 0},
+		{"AttrPrototyped", Const, 0},
+		{"AttrPure", Const, 14},
+		{"AttrRanges", Const, 0},
+		{"AttrRank", Const, 14},
+		{"AttrRecursive", Const, 14},
+		{"AttrReference", Const, 14},
+		{"AttrReturnAddr", Const, 0},
+		{"AttrRnglistsBase", Const, 14},
+		{"AttrRvalueReference", Const, 14},
+		{"AttrSegment", Const, 0},
+		{"AttrSibling", Const, 0},
+		{"AttrSignature", Const, 14},
+		{"AttrSmall", Const, 14},
+		{"AttrSpecification", Const, 0},
+		{"AttrStartScope", Const, 0},
+		{"AttrStaticLink", Const, 0},
+		{"AttrStmtList", Const, 0},
+		{"AttrStrOffsetsBase", Const, 14},
+		{"AttrStride", Const, 0},
+		{"AttrStrideSize", Const, 0},
+		{"AttrStringLength", Const, 0},
+		{"AttrStringLengthBitSize", Const, 14},
+		{"AttrStringLengthByteSize", Const, 14},
+		{"AttrThreadsScaled", Const, 14},
+		{"AttrTrampoline", Const, 0},
+		{"AttrType", Const, 0},
+		{"AttrUpperBound", Const, 0},
+		{"AttrUseLocation", Const, 0},
+		{"AttrUseUTF8", Const, 0},
+		{"AttrVarParam", Const, 0},
+		{"AttrVirtuality", Const, 0},
+		{"AttrVisibility", Const, 0},
+		{"AttrVtableElemLoc", Const, 0},
+		{"BasicType", Type, 0},
+		{"BasicType.BitOffset", Field, 0},
+		{"BasicType.BitSize", Field, 0},
+		{"BasicType.CommonType", Field, 0},
+		{"BasicType.DataBitOffset", Field, 18},
+		{"BoolType", Type, 0},
+		{"BoolType.BasicType", Field, 0},
+		{"CharType", Type, 0},
+		{"CharType.BasicType", Field, 0},
+		{"Class", Type, 5},
+		{"ClassAddrPtr", Const, 14},
+		{"ClassAddress", Const, 5},
+		{"ClassBlock", Const, 5},
+		{"ClassConstant", Const, 5},
+		{"ClassExprLoc", Const, 5},
+		{"ClassFlag", Const, 5},
+		{"ClassLinePtr", Const, 5},
+		{"ClassLocList", Const, 14},
+		{"ClassLocListPtr", Const, 5},
+		{"ClassMacPtr", Const, 5},
+		{"ClassRangeListPtr", Const, 5},
+		{"ClassReference", Const, 5},
+		{"ClassReferenceAlt", Const, 5},
+		{"ClassReferenceSig", Const, 5},
+		{"ClassRngList", Const, 14},
+		{"ClassRngListsPtr", Const, 14},
+		{"ClassStrOffsetsPtr", Const, 14},
+		{"ClassString", Const, 5},
+		{"ClassStringAlt", Const, 5},
+		{"ClassUnknown", Const, 6},
+		{"CommonType", Type, 0},
+		{"CommonType.ByteSize", Field, 0},
+		{"CommonType.Name", Field, 0},
+		{"ComplexType", Type, 0},
+		{"ComplexType.BasicType", Field, 0},
+		{"Data", Type, 0},
+		{"DecodeError", Type, 0},
+		{"DecodeError.Err", Field, 0},
+		{"DecodeError.Name", Field, 0},
+		{"DecodeError.Offset", Field, 0},
+		{"DotDotDotType", Type, 0},
+		{"DotDotDotType.CommonType", Field, 0},
+		{"Entry", Type, 0},
+		{"Entry.Children", Field, 0},
+		{"Entry.Field", Field, 0},
+		{"Entry.Offset", Field, 0},
+		{"Entry.Tag", Field, 0},
+		{"EnumType", Type, 0},
+		{"EnumType.CommonType", Field, 0},
+		{"EnumType.EnumName", Field, 0},
+		{"EnumType.Val", Field, 0},
+		{"EnumValue", Type, 0},
+		{"EnumValue.Name", Field, 0},
+		{"EnumValue.Val", Field, 0},
+		{"ErrUnknownPC", Var, 5},
+		{"Field", Type, 0},
+		{"Field.Attr", Field, 0},
+		{"Field.Class", Field, 5},
+		{"Field.Val", Field, 0},
+		{"FloatType", Type, 0},
+		{"FloatType.BasicType", Field, 0},
+		{"FuncType", Type, 0},
+		{"FuncType.CommonType", Field, 0},
+		{"FuncType.ParamType", Field, 0},
+		{"FuncType.ReturnType", Field, 0},
+		{"IntType", Type, 0},
+		{"IntType.BasicType", Field, 0},
+		{"LineEntry", Type, 5},
+		{"LineEntry.Address", Field, 5},
+		{"LineEntry.BasicBlock", Field, 5},
+		{"LineEntry.Column", Field, 5},
+		{"LineEntry.Discriminator", Field, 5},
+		{"LineEntry.EndSequence", Field, 5},
+		{"LineEntry.EpilogueBegin", Field, 5},
+		{"LineEntry.File", Field, 5},
+		{"LineEntry.ISA", Field, 5},
+		{"LineEntry.IsStmt", Field, 5},
+		{"LineEntry.Line", Field, 5},
+		{"LineEntry.OpIndex", Field, 5},
+		{"LineEntry.PrologueEnd", Field, 5},
+		{"LineFile", Type, 5},
+		{"LineFile.Length", Field, 5},
+		{"LineFile.Mtime", Field, 5},
+		{"LineFile.Name", Field, 5},
+		{"LineReader", Type, 5},
+		{"LineReaderPos", Type, 5},
+		{"New", Func, 0},
+		{"Offset", Type, 0},
+		{"PtrType", Type, 0},
+		{"PtrType.CommonType", Field, 0},
+		{"PtrType.Type", Field, 0},
+		{"QualType", Type, 0},
+		{"QualType.CommonType", Field, 0},
+		{"QualType.Qual", Field, 0},
+		{"QualType.Type", Field, 0},
+		{"Reader", Type, 0},
+		{"StructField", Type, 0},
+		{"StructField.BitOffset", Field, 0},
+		{"StructField.BitSize", Field, 0},
+		{"StructField.ByteOffset", Field, 0},
+		{"StructField.ByteSize", Field, 0},
+		{"StructField.DataBitOffset", Field, 18},
+		{"StructField.Name", Field, 0},
+		{"StructField.Type", Field, 0},
+		{"StructType", Type, 0},
+		{"StructType.CommonType", Field, 0},
+		{"StructType.Field", Field, 0},
+		{"StructType.Incomplete", Field, 0},
+		{"StructType.Kind", Field, 0},
+		{"StructType.StructName", Field, 0},
+		{"Tag", Type, 0},
+		{"TagAccessDeclaration", Const, 0},
+		{"TagArrayType", Const, 0},
+		{"TagAtomicType", Const, 14},
+		{"TagBaseType", Const, 0},
+		{"TagCallSite", Const, 14},
+		{"TagCallSiteParameter", Const, 14},
+		{"TagCatchDwarfBlock", Const, 0},
+		{"TagClassType", Const, 0},
+		{"TagCoarrayType", Const, 14},
+		{"TagCommonDwarfBlock", Const, 0},
+		{"TagCommonInclusion", Const, 0},
+		{"TagCompileUnit", Const, 0},
+		{"TagCondition", Const, 3},
+		{"TagConstType", Const, 0},
+		{"TagConstant", Const, 0},
+		{"TagDwarfProcedure", Const, 0},
+		{"TagDynamicType", Const, 14},
+		{"TagEntryPoint", Const, 0},
+		{"TagEnumerationType", Const, 0},
+		{"TagEnumerator", Const, 0},
+		{"TagFileType", Const, 0},
+		{"TagFormalParameter", Const, 0},
+		{"TagFriend", Const, 0},
+		{"TagGenericSubrange", Const, 14},
+		{"TagImmutableType", Const, 14},
+		{"TagImportedDeclaration", Const, 0},
+		{"TagImportedModule", Const, 0},
+		{"TagImportedUnit", Const, 0},
+		{"TagInheritance", Const, 0},
+		{"TagInlinedSubroutine", Const, 0},
+		{"TagInterfaceType", Const, 0},
+		{"TagLabel", Const, 0},
+		{"TagLexDwarfBlock", Const, 0},
+		{"TagMember", Const, 0},
+		{"TagModule", Const, 0},
+		{"TagMutableType", Const, 0},
+		{"TagNamelist", Const, 0},
+		{"TagNamelistItem", Const, 0},
+		{"TagNamespace", Const, 0},
+		{"TagPackedType", Const, 0},
+		{"TagPartialUnit", Const, 0},
+		{"TagPointerType", Const, 0},
+		{"TagPtrToMemberType", Const, 0},
+		{"TagReferenceType", Const, 0},
+		{"TagRestrictType", Const, 0},
+		{"TagRvalueReferenceType", Const, 3},
+		{"TagSetType", Const, 0},
+		{"TagSharedType", Const, 3},
+		{"TagSkeletonUnit", Const, 14},
+		{"TagStringType", Const, 0},
+		{"TagStructType", Const, 0},
+		{"TagSubprogram", Const, 0},
+		{"TagSubrangeType", Const, 0},
+		{"TagSubroutineType", Const, 0},
+		{"TagTemplateAlias", Const, 3},
+		{"TagTemplateTypeParameter", Const, 0},
+		{"TagTemplateValueParameter", Const, 0},
+		{"TagThrownType", Const, 0},
+		{"TagTryDwarfBlock", Const, 0},
+		{"TagTypeUnit", Const, 3},
+		{"TagTypedef", Const, 0},
+		{"TagUnionType", Const, 0},
+		{"TagUnspecifiedParameters", Const, 0},
+		{"TagUnspecifiedType", Const, 0},
+		{"TagVariable", Const, 0},
+		{"TagVariant", Const, 0},
+		{"TagVariantPart", Const, 0},
+		{"TagVolatileType", Const, 0},
+		{"TagWithStmt", Const, 0},
+		{"Type", Type, 0},
+		{"TypedefType", Type, 0},
+		{"TypedefType.CommonType", Field, 0},
+		{"TypedefType.Type", Field, 0},
+		{"UcharType", Type, 0},
+		{"UcharType.BasicType", Field, 0},
+		{"UintType", Type, 0},
+		{"UintType.BasicType", Field, 0},
+		{"UnspecifiedType", Type, 4},
+		{"UnspecifiedType.BasicType", Field, 4},
+		{"UnsupportedType", Type, 13},
+		{"UnsupportedType.CommonType", Field, 13},
+		{"UnsupportedType.Tag", Field, 13},
+		{"VoidType", Type, 0},
+		{"VoidType.CommonType", Field, 0},
+	},
+	"debug/elf": {
+		{"(*File).Close", Method, 0},
+		{"(*File).DWARF", Method, 0},
+		{"(*File).DynString", Method, 1},
+		{"(*File).DynValue", Method, 21},
+		{"(*File).DynamicSymbols", Method, 4},
+		{"(*File).DynamicVersionNeeds", Method, 24},
+		{"(*File).DynamicVersions", Method, 24},
+		{"(*File).ImportedLibraries", Method, 0},
+		{"(*File).ImportedSymbols", Method, 0},
+		{"(*File).Section", Method, 0},
+		{"(*File).SectionByType", Method, 0},
+		{"(*File).Symbols", Method, 0},
+		{"(*FormatError).Error", Method, 0},
+		{"(*Prog).Open", Method, 0},
+		{"(*Section).Data", Method, 0},
+		{"(*Section).Open", Method, 0},
+		{"(Class).GoString", Method, 0},
+		{"(Class).String", Method, 0},
+		{"(CompressionType).GoString", Method, 6},
+		{"(CompressionType).String", Method, 6},
+		{"(Data).GoString", Method, 0},
+		{"(Data).String", Method, 0},
+		{"(DynFlag).GoString", Method, 0},
+		{"(DynFlag).String", Method, 0},
+		{"(DynFlag1).GoString", Method, 21},
+		{"(DynFlag1).String", Method, 21},
+		{"(DynTag).GoString", Method, 0},
+		{"(DynTag).String", Method, 0},
+		{"(Machine).GoString", Method, 0},
+		{"(Machine).String", Method, 0},
+		{"(NType).GoString", Method, 0},
+		{"(NType).String", Method, 0},
+		{"(OSABI).GoString", Method, 0},
+		{"(OSABI).String", Method, 0},
+		{"(Prog).ReadAt", Method, 0},
+		{"(ProgFlag).GoString", Method, 0},
+		{"(ProgFlag).String", Method, 0},
+		{"(ProgType).GoString", Method, 0},
+		{"(ProgType).String", Method, 0},
+		{"(R_386).GoString", Method, 0},
+		{"(R_386).String", Method, 0},
+		{"(R_390).GoString", Method, 7},
+		{"(R_390).String", Method, 7},
+		{"(R_AARCH64).GoString", Method, 4},
+		{"(R_AARCH64).String", Method, 4},
+		{"(R_ALPHA).GoString", Method, 0},
+		{"(R_ALPHA).String", Method, 0},
+		{"(R_ARM).GoString", Method, 0},
+		{"(R_ARM).String", Method, 0},
+		{"(R_LARCH).GoString", Method, 19},
+		{"(R_LARCH).String", Method, 19},
+		{"(R_MIPS).GoString", Method, 6},
+		{"(R_MIPS).String", Method, 6},
+		{"(R_PPC).GoString", Method, 0},
+		{"(R_PPC).String", Method, 0},
+		{"(R_PPC64).GoString", Method, 5},
+		{"(R_PPC64).String", Method, 5},
+		{"(R_RISCV).GoString", Method, 11},
+		{"(R_RISCV).String", Method, 11},
+		{"(R_SPARC).GoString", Method, 0},
+		{"(R_SPARC).String", Method, 0},
+		{"(R_X86_64).GoString", Method, 0},
+		{"(R_X86_64).String", Method, 0},
+		{"(Section).ReadAt", Method, 0},
+		{"(SectionFlag).GoString", Method, 0},
+		{"(SectionFlag).String", Method, 0},
+		{"(SectionIndex).GoString", Method, 0},
+		{"(SectionIndex).String", Method, 0},
+		{"(SectionType).GoString", Method, 0},
+		{"(SectionType).String", Method, 0},
+		{"(SymBind).GoString", Method, 0},
+		{"(SymBind).String", Method, 0},
+		{"(SymType).GoString", Method, 0},
+		{"(SymType).String", Method, 0},
+		{"(SymVis).GoString", Method, 0},
+		{"(SymVis).String", Method, 0},
+		{"(Type).GoString", Method, 0},
+		{"(Type).String", Method, 0},
+		{"(Version).GoString", Method, 0},
+		{"(Version).String", Method, 0},
+		{"(VersionIndex).Index", Method, 24},
+		{"(VersionIndex).IsHidden", Method, 24},
+		{"ARM_MAGIC_TRAMP_NUMBER", Const, 0},
+		{"COMPRESS_HIOS", Const, 6},
+		{"COMPRESS_HIPROC", Const, 6},
+		{"COMPRESS_LOOS", Const, 6},
+		{"COMPRESS_LOPROC", Const, 6},
+		{"COMPRESS_ZLIB", Const, 6},
+		{"COMPRESS_ZSTD", Const, 21},
+		{"Chdr32", Type, 6},
+		{"Chdr32.Addralign", Field, 6},
+		{"Chdr32.Size", Field, 6},
+		{"Chdr32.Type", Field, 6},
+		{"Chdr64", Type, 6},
+		{"Chdr64.Addralign", Field, 6},
+		{"Chdr64.Size", Field, 6},
+		{"Chdr64.Type", Field, 6},
+		{"Class", Type, 0},
+		{"CompressionType", Type, 6},
+		{"DF_1_CONFALT", Const, 21},
+		{"DF_1_DIRECT", Const, 21},
+		{"DF_1_DISPRELDNE", Const, 21},
+		{"DF_1_DISPRELPND", Const, 21},
+		{"DF_1_EDITED", Const, 21},
+		{"DF_1_ENDFILTEE", Const, 21},
+		{"DF_1_GLOBAL", Const, 21},
+		{"DF_1_GLOBAUDIT", Const, 21},
+		{"DF_1_GROUP", Const, 21},
+		{"DF_1_IGNMULDEF", Const, 21},
+		{"DF_1_INITFIRST", Const, 21},
+		{"DF_1_INTERPOSE", Const, 21},
+		{"DF_1_KMOD", Const, 21},
+		{"DF_1_LOADFLTR", Const, 21},
+		{"DF_1_NOCOMMON", Const, 21},
+		{"DF_1_NODEFLIB", Const, 21},
+		{"DF_1_NODELETE", Const, 21},
+		{"DF_1_NODIRECT", Const, 21},
+		{"DF_1_NODUMP", Const, 21},
+		{"DF_1_NOHDR", Const, 21},
+		{"DF_1_NOKSYMS", Const, 21},
+		{"DF_1_NOOPEN", Const, 21},
+		{"DF_1_NORELOC", Const, 21},
+		{"DF_1_NOW", Const, 21},
+		{"DF_1_ORIGIN", Const, 21},
+		{"DF_1_PIE", Const, 21},
+		{"DF_1_SINGLETON", Const, 21},
+		{"DF_1_STUB", Const, 21},
+		{"DF_1_SYMINTPOSE", Const, 21},
+		{"DF_1_TRANS", Const, 21},
+		{"DF_1_WEAKFILTER", Const, 21},
+		{"DF_BIND_NOW", Const, 0},
+		{"DF_ORIGIN", Const, 0},
+		{"DF_STATIC_TLS", Const, 0},
+		{"DF_SYMBOLIC", Const, 0},
+		{"DF_TEXTREL", Const, 0},
+		{"DT_ADDRRNGHI", Const, 16},
+		{"DT_ADDRRNGLO", Const, 16},
+		{"DT_AUDIT", Const, 16},
+		{"DT_AUXILIARY", Const, 16},
+		{"DT_BIND_NOW", Const, 0},
+		{"DT_CHECKSUM", Const, 16},
+		{"DT_CONFIG", Const, 16},
+		{"DT_DEBUG", Const, 0},
+		{"DT_DEPAUDIT", Const, 16},
+		{"DT_ENCODING", Const, 0},
+		{"DT_FEATURE", Const, 16},
+		{"DT_FILTER", Const, 16},
+		{"DT_FINI", Const, 0},
+		{"DT_FINI_ARRAY", Const, 0},
+		{"DT_FINI_ARRAYSZ", Const, 0},
+		{"DT_FLAGS", Const, 0},
+		{"DT_FLAGS_1", Const, 16},
+		{"DT_GNU_CONFLICT", Const, 16},
+		{"DT_GNU_CONFLICTSZ", Const, 16},
+		{"DT_GNU_HASH", Const, 16},
+		{"DT_GNU_LIBLIST", Const, 16},
+		{"DT_GNU_LIBLISTSZ", Const, 16},
+		{"DT_GNU_PRELINKED", Const, 16},
+		{"DT_HASH", Const, 0},
+		{"DT_HIOS", Const, 0},
+		{"DT_HIPROC", Const, 0},
+		{"DT_INIT", Const, 0},
+		{"DT_INIT_ARRAY", Const, 0},
+		{"DT_INIT_ARRAYSZ", Const, 0},
+		{"DT_JMPREL", Const, 0},
+		{"DT_LOOS", Const, 0},
+		{"DT_LOPROC", Const, 0},
+		{"DT_MIPS_AUX_DYNAMIC", Const, 16},
+		{"DT_MIPS_BASE_ADDRESS", Const, 16},
+		{"DT_MIPS_COMPACT_SIZE", Const, 16},
+		{"DT_MIPS_CONFLICT", Const, 16},
+		{"DT_MIPS_CONFLICTNO", Const, 16},
+		{"DT_MIPS_CXX_FLAGS", Const, 16},
+		{"DT_MIPS_DELTA_CLASS", Const, 16},
+		{"DT_MIPS_DELTA_CLASSSYM", Const, 16},
+		{"DT_MIPS_DELTA_CLASSSYM_NO", Const, 16},
+		{"DT_MIPS_DELTA_CLASS_NO", Const, 16},
+		{"DT_MIPS_DELTA_INSTANCE", Const, 16},
+		{"DT_MIPS_DELTA_INSTANCE_NO", Const, 16},
+		{"DT_MIPS_DELTA_RELOC", Const, 16},
+		{"DT_MIPS_DELTA_RELOC_NO", Const, 16},
+		{"DT_MIPS_DELTA_SYM", Const, 16},
+		{"DT_MIPS_DELTA_SYM_NO", Const, 16},
+		{"DT_MIPS_DYNSTR_ALIGN", Const, 16},
+		{"DT_MIPS_FLAGS", Const, 16},
+		{"DT_MIPS_GOTSYM", Const, 16},
+		{"DT_MIPS_GP_VALUE", Const, 16},
+		{"DT_MIPS_HIDDEN_GOTIDX", Const, 16},
+		{"DT_MIPS_HIPAGENO", Const, 16},
+		{"DT_MIPS_ICHECKSUM", Const, 16},
+		{"DT_MIPS_INTERFACE", Const, 16},
+		{"DT_MIPS_INTERFACE_SIZE", Const, 16},
+		{"DT_MIPS_IVERSION", Const, 16},
+		{"DT_MIPS_LIBLIST", Const, 16},
+		{"DT_MIPS_LIBLISTNO", Const, 16},
+		{"DT_MIPS_LOCALPAGE_GOTIDX", Const, 16},
+		{"DT_MIPS_LOCAL_GOTIDX", Const, 16},
+		{"DT_MIPS_LOCAL_GOTNO", Const, 16},
+		{"DT_MIPS_MSYM", Const, 16},
+		{"DT_MIPS_OPTIONS", Const, 16},
+		{"DT_MIPS_PERF_SUFFIX", Const, 16},
+		{"DT_MIPS_PIXIE_INIT", Const, 16},
+		{"DT_MIPS_PLTGOT", Const, 16},
+		{"DT_MIPS_PROTECTED_GOTIDX", Const, 16},
+		{"DT_MIPS_RLD_MAP", Const, 16},
+		{"DT_MIPS_RLD_MAP_REL", Const, 16},
+		{"DT_MIPS_RLD_TEXT_RESOLVE_ADDR", Const, 16},
+		{"DT_MIPS_RLD_VERSION", Const, 16},
+		{"DT_MIPS_RWPLT", Const, 16},
+		{"DT_MIPS_SYMBOL_LIB", Const, 16},
+		{"DT_MIPS_SYMTABNO", Const, 16},
+		{"DT_MIPS_TIME_STAMP", Const, 16},
+		{"DT_MIPS_UNREFEXTNO", Const, 16},
+		{"DT_MOVEENT", Const, 16},
+		{"DT_MOVESZ", Const, 16},
+		{"DT_MOVETAB", Const, 16},
+		{"DT_NEEDED", Const, 0},
+		{"DT_NULL", Const, 0},
+		{"DT_PLTGOT", Const, 0},
+		{"DT_PLTPAD", Const, 16},
+		{"DT_PLTPADSZ", Const, 16},
+		{"DT_PLTREL", Const, 0},
+		{"DT_PLTRELSZ", Const, 0},
+		{"DT_POSFLAG_1", Const, 16},
+		{"DT_PPC64_GLINK", Const, 16},
+		{"DT_PPC64_OPD", Const, 16},
+		{"DT_PPC64_OPDSZ", Const, 16},
+		{"DT_PPC64_OPT", Const, 16},
+		{"DT_PPC_GOT", Const, 16},
+		{"DT_PPC_OPT", Const, 16},
+		{"DT_PREINIT_ARRAY", Const, 0},
+		{"DT_PREINIT_ARRAYSZ", Const, 0},
+		{"DT_REL", Const, 0},
+		{"DT_RELA", Const, 0},
+		{"DT_RELACOUNT", Const, 16},
+		{"DT_RELAENT", Const, 0},
+		{"DT_RELASZ", Const, 0},
+		{"DT_RELCOUNT", Const, 16},
+		{"DT_RELENT", Const, 0},
+		{"DT_RELSZ", Const, 0},
+		{"DT_RPATH", Const, 0},
+		{"DT_RUNPATH", Const, 0},
+		{"DT_SONAME", Const, 0},
+		{"DT_SPARC_REGISTER", Const, 16},
+		{"DT_STRSZ", Const, 0},
+		{"DT_STRTAB", Const, 0},
+		{"DT_SYMBOLIC", Const, 0},
+		{"DT_SYMENT", Const, 0},
+		{"DT_SYMINENT", Const, 16},
+		{"DT_SYMINFO", Const, 16},
+		{"DT_SYMINSZ", Const, 16},
+		{"DT_SYMTAB", Const, 0},
+		{"DT_SYMTAB_SHNDX", Const, 16},
+		{"DT_TEXTREL", Const, 0},
+		{"DT_TLSDESC_GOT", Const, 16},
+		{"DT_TLSDESC_PLT", Const, 16},
+		{"DT_USED", Const, 16},
+		{"DT_VALRNGHI", Const, 16},
+		{"DT_VALRNGLO", Const, 16},
+		{"DT_VERDEF", Const, 16},
+		{"DT_VERDEFNUM", Const, 16},
+		{"DT_VERNEED", Const, 0},
+		{"DT_VERNEEDNUM", Const, 0},
+		{"DT_VERSYM", Const, 0},
+		{"Data", Type, 0},
+		{"Dyn32", Type, 0},
+		{"Dyn32.Tag", Field, 0},
+		{"Dyn32.Val", Field, 0},
+		{"Dyn64", Type, 0},
+		{"Dyn64.Tag", Field, 0},
+		{"Dyn64.Val", Field, 0},
+		{"DynFlag", Type, 0},
+		{"DynFlag1", Type, 21},
+		{"DynTag", Type, 0},
+		{"DynamicVersion", Type, 24},
+		{"DynamicVersion.Deps", Field, 24},
+		{"DynamicVersion.Flags", Field, 24},
+		{"DynamicVersion.Index", Field, 24},
+		{"DynamicVersion.Name", Field, 24},
+		{"DynamicVersionDep", Type, 24},
+		{"DynamicVersionDep.Dep", Field, 24},
+		{"DynamicVersionDep.Flags", Field, 24},
+		{"DynamicVersionDep.Index", Field, 24},
+		{"DynamicVersionFlag", Type, 24},
+		{"DynamicVersionNeed", Type, 24},
+		{"DynamicVersionNeed.Name", Field, 24},
+		{"DynamicVersionNeed.Needs", Field, 24},
+		{"EI_ABIVERSION", Const, 0},
+		{"EI_CLASS", Const, 0},
+		{"EI_DATA", Const, 0},
+		{"EI_NIDENT", Const, 0},
+		{"EI_OSABI", Const, 0},
+		{"EI_PAD", Const, 0},
+		{"EI_VERSION", Const, 0},
+		{"ELFCLASS32", Const, 0},
+		{"ELFCLASS64", Const, 0},
+		{"ELFCLASSNONE", Const, 0},
+		{"ELFDATA2LSB", Const, 0},
+		{"ELFDATA2MSB", Const, 0},
+		{"ELFDATANONE", Const, 0},
+		{"ELFMAG", Const, 0},
+		{"ELFOSABI_86OPEN", Const, 0},
+		{"ELFOSABI_AIX", Const, 0},
+		{"ELFOSABI_ARM", Const, 0},
+		{"ELFOSABI_AROS", Const, 11},
+		{"ELFOSABI_CLOUDABI", Const, 11},
+		{"ELFOSABI_FENIXOS", Const, 11},
+		{"ELFOSABI_FREEBSD", Const, 0},
+		{"ELFOSABI_HPUX", Const, 0},
+		{"ELFOSABI_HURD", Const, 0},
+		{"ELFOSABI_IRIX", Const, 0},
+		{"ELFOSABI_LINUX", Const, 0},
+		{"ELFOSABI_MODESTO", Const, 0},
+		{"ELFOSABI_NETBSD", Const, 0},
+		{"ELFOSABI_NONE", Const, 0},
+		{"ELFOSABI_NSK", Const, 0},
+		{"ELFOSABI_OPENBSD", Const, 0},
+		{"ELFOSABI_OPENVMS", Const, 0},
+		{"ELFOSABI_SOLARIS", Const, 0},
+		{"ELFOSABI_STANDALONE", Const, 0},
+		{"ELFOSABI_TRU64", Const, 0},
+		{"EM_386", Const, 0},
+		{"EM_486", Const, 0},
+		{"EM_56800EX", Const, 11},
+		{"EM_68HC05", Const, 11},
+		{"EM_68HC08", Const, 11},
+		{"EM_68HC11", Const, 11},
+		{"EM_68HC12", Const, 0},
+		{"EM_68HC16", Const, 11},
+		{"EM_68K", Const, 0},
+		{"EM_78KOR", Const, 11},
+		{"EM_8051", Const, 11},
+		{"EM_860", Const, 0},
+		{"EM_88K", Const, 0},
+		{"EM_960", Const, 0},
+		{"EM_AARCH64", Const, 4},
+		{"EM_ALPHA", Const, 0},
+		{"EM_ALPHA_STD", Const, 0},
+		{"EM_ALTERA_NIOS2", Const, 11},
+		{"EM_AMDGPU", Const, 11},
+		{"EM_ARC", Const, 0},
+		{"EM_ARCA", Const, 11},
+		{"EM_ARC_COMPACT", Const, 11},
+		{"EM_ARC_COMPACT2", Const, 11},
+		{"EM_ARM", Const, 0},
+		{"EM_AVR", Const, 11},
+		{"EM_AVR32", Const, 11},
+		{"EM_BA1", Const, 11},
+		{"EM_BA2", Const, 11},
+		{"EM_BLACKFIN", Const, 11},
+		{"EM_BPF", Const, 11},
+		{"EM_C166", Const, 11},
+		{"EM_CDP", Const, 11},
+		{"EM_CE", Const, 11},
+		{"EM_CLOUDSHIELD", Const, 11},
+		{"EM_COGE", Const, 11},
+		{"EM_COLDFIRE", Const, 0},
+		{"EM_COOL", Const, 11},
+		{"EM_COREA_1ST", Const, 11},
+		{"EM_COREA_2ND", Const, 11},
+		{"EM_CR", Const, 11},
+		{"EM_CR16", Const, 11},
+		{"EM_CRAYNV2", Const, 11},
+		{"EM_CRIS", Const, 11},
+		{"EM_CRX", Const, 11},
+		{"EM_CSR_KALIMBA", Const, 11},
+		{"EM_CUDA", Const, 11},
+		{"EM_CYPRESS_M8C", Const, 11},
+		{"EM_D10V", Const, 11},
+		{"EM_D30V", Const, 11},
+		{"EM_DSP24", Const, 11},
+		{"EM_DSPIC30F", Const, 11},
+		{"EM_DXP", Const, 11},
+		{"EM_ECOG1", Const, 11},
+		{"EM_ECOG16", Const, 11},
+		{"EM_ECOG1X", Const, 11},
+		{"EM_ECOG2", Const, 11},
+		{"EM_ETPU", Const, 11},
+		{"EM_EXCESS", Const, 11},
+		{"EM_F2MC16", Const, 11},
+		{"EM_FIREPATH", Const, 11},
+		{"EM_FR20", Const, 0},
+		{"EM_FR30", Const, 11},
+		{"EM_FT32", Const, 11},
+		{"EM_FX66", Const, 11},
+		{"EM_H8S", Const, 0},
+		{"EM_H8_300", Const, 0},
+		{"EM_H8_300H", Const, 0},
+		{"EM_H8_500", Const, 0},
+		{"EM_HUANY", Const, 11},
+		{"EM_IA_64", Const, 0},
+		{"EM_INTEL205", Const, 11},
+		{"EM_INTEL206", Const, 11},
+		{"EM_INTEL207", Const, 11},
+		{"EM_INTEL208", Const, 11},
+		{"EM_INTEL209", Const, 11},
+		{"EM_IP2K", Const, 11},
+		{"EM_JAVELIN", Const, 11},
+		{"EM_K10M", Const, 11},
+		{"EM_KM32", Const, 11},
+		{"EM_KMX16", Const, 11},
+		{"EM_KMX32", Const, 11},
+		{"EM_KMX8", Const, 11},
+		{"EM_KVARC", Const, 11},
+		{"EM_L10M", Const, 11},
+		{"EM_LANAI", Const, 11},
+		{"EM_LATTICEMICO32", Const, 11},
+		{"EM_LOONGARCH", Const, 19},
+		{"EM_M16C", Const, 11},
+		{"EM_M32", Const, 0},
+		{"EM_M32C", Const, 11},
+		{"EM_M32R", Const, 11},
+		{"EM_MANIK", Const, 11},
+		{"EM_MAX", Const, 11},
+		{"EM_MAXQ30", Const, 11},
+		{"EM_MCHP_PIC", Const, 11},
+		{"EM_MCST_ELBRUS", Const, 11},
+		{"EM_ME16", Const, 0},
+		{"EM_METAG", Const, 11},
+		{"EM_MICROBLAZE", Const, 11},
+		{"EM_MIPS", Const, 0},
+		{"EM_MIPS_RS3_LE", Const, 0},
+		{"EM_MIPS_RS4_BE", Const, 0},
+		{"EM_MIPS_X", Const, 0},
+		{"EM_MMA", Const, 0},
+		{"EM_MMDSP_PLUS", Const, 11},
+		{"EM_MMIX", Const, 11},
+		{"EM_MN10200", Const, 11},
+		{"EM_MN10300", Const, 11},
+		{"EM_MOXIE", Const, 11},
+		{"EM_MSP430", Const, 11},
+		{"EM_NCPU", Const, 0},
+		{"EM_NDR1", Const, 0},
+		{"EM_NDS32", Const, 11},
+		{"EM_NONE", Const, 0},
+		{"EM_NORC", Const, 11},
+		{"EM_NS32K", Const, 11},
+		{"EM_OPEN8", Const, 11},
+		{"EM_OPENRISC", Const, 11},
+		{"EM_PARISC", Const, 0},
+		{"EM_PCP", Const, 0},
+		{"EM_PDP10", Const, 11},
+		{"EM_PDP11", Const, 11},
+		{"EM_PDSP", Const, 11},
+		{"EM_PJ", Const, 11},
+		{"EM_PPC", Const, 0},
+		{"EM_PPC64", Const, 0},
+		{"EM_PRISM", Const, 11},
+		{"EM_QDSP6", Const, 11},
+		{"EM_R32C", Const, 11},
+		{"EM_RCE", Const, 0},
+		{"EM_RH32", Const, 0},
+		{"EM_RISCV", Const, 11},
+		{"EM_RL78", Const, 11},
+		{"EM_RS08", Const, 11},
+		{"EM_RX", Const, 11},
+		{"EM_S370", Const, 0},
+		{"EM_S390", Const, 0},
+		{"EM_SCORE7", Const, 11},
+		{"EM_SEP", Const, 11},
+		{"EM_SE_C17", Const, 11},
+		{"EM_SE_C33", Const, 11},
+		{"EM_SH", Const, 0},
+		{"EM_SHARC", Const, 11},
+		{"EM_SLE9X", Const, 11},
+		{"EM_SNP1K", Const, 11},
+		{"EM_SPARC", Const, 0},
+		{"EM_SPARC32PLUS", Const, 0},
+		{"EM_SPARCV9", Const, 0},
+		{"EM_ST100", Const, 0},
+		{"EM_ST19", Const, 11},
+		{"EM_ST200", Const, 11},
+		{"EM_ST7", Const, 11},
+		{"EM_ST9PLUS", Const, 11},
+		{"EM_STARCORE", Const, 0},
+		{"EM_STM8", Const, 11},
+		{"EM_STXP7X", Const, 11},
+		{"EM_SVX", Const, 11},
+		{"EM_TILE64", Const, 11},
+		{"EM_TILEGX", Const, 11},
+		{"EM_TILEPRO", Const, 11},
+		{"EM_TINYJ", Const, 0},
+		{"EM_TI_ARP32", Const, 11},
+		{"EM_TI_C2000", Const, 11},
+		{"EM_TI_C5500", Const, 11},
+		{"EM_TI_C6000", Const, 11},
+		{"EM_TI_PRU", Const, 11},
+		{"EM_TMM_GPP", Const, 11},
+		{"EM_TPC", Const, 11},
+		{"EM_TRICORE", Const, 0},
+		{"EM_TRIMEDIA", Const, 11},
+		{"EM_TSK3000", Const, 11},
+		{"EM_UNICORE", Const, 11},
+		{"EM_V800", Const, 0},
+		{"EM_V850", Const, 11},
+		{"EM_VAX", Const, 11},
+		{"EM_VIDEOCORE", Const, 11},
+		{"EM_VIDEOCORE3", Const, 11},
+		{"EM_VIDEOCORE5", Const, 11},
+		{"EM_VISIUM", Const, 11},
+		{"EM_VPP500", Const, 0},
+		{"EM_X86_64", Const, 0},
+		{"EM_XCORE", Const, 11},
+		{"EM_XGATE", Const, 11},
+		{"EM_XIMO16", Const, 11},
+		{"EM_XTENSA", Const, 11},
+		{"EM_Z80", Const, 11},
+		{"EM_ZSP", Const, 11},
+		{"ET_CORE", Const, 0},
+		{"ET_DYN", Const, 0},
+		{"ET_EXEC", Const, 0},
+		{"ET_HIOS", Const, 0},
+		{"ET_HIPROC", Const, 0},
+		{"ET_LOOS", Const, 0},
+		{"ET_LOPROC", Const, 0},
+		{"ET_NONE", Const, 0},
+		{"ET_REL", Const, 0},
+		{"EV_CURRENT", Const, 0},
+		{"EV_NONE", Const, 0},
+		{"ErrNoSymbols", Var, 4},
+		{"File", Type, 0},
+		{"File.FileHeader", Field, 0},
+		{"File.Progs", Field, 0},
+		{"File.Sections", Field, 0},
+		{"FileHeader", Type, 0},
+		{"FileHeader.ABIVersion", Field, 0},
+		{"FileHeader.ByteOrder", Field, 0},
+		{"FileHeader.Class", Field, 0},
+		{"FileHeader.Data", Field, 0},
+		{"FileHeader.Entry", Field, 1},
+		{"FileHeader.Machine", Field, 0},
+		{"FileHeader.OSABI", Field, 0},
+		{"FileHeader.Type", Field, 0},
+		{"FileHeader.Version", Field, 0},
+		{"FormatError", Type, 0},
+		{"Header32", Type, 0},
+		{"Header32.Ehsize", Field, 0},
+		{"Header32.Entry", Field, 0},
+		{"Header32.Flags", Field, 0},
+		{"Header32.Ident", Field, 0},
+		{"Header32.Machine", Field, 0},
+		{"Header32.Phentsize", Field, 0},
+		{"Header32.Phnum", Field, 0},
+		{"Header32.Phoff", Field, 0},
+		{"Header32.Shentsize", Field, 0},
+		{"Header32.Shnum", Field, 0},
+		{"Header32.Shoff", Field, 0},
+		{"Header32.Shstrndx", Field, 0},
+		{"Header32.Type", Field, 0},
+		{"Header32.Version", Field, 0},
+		{"Header64", Type, 0},
+		{"Header64.Ehsize", Field, 0},
+		{"Header64.Entry", Field, 0},
+		{"Header64.Flags", Field, 0},
+		{"Header64.Ident", Field, 0},
+		{"Header64.Machine", Field, 0},
+		{"Header64.Phentsize", Field, 0},
+		{"Header64.Phnum", Field, 0},
+		{"Header64.Phoff", Field, 0},
+		{"Header64.Shentsize", Field, 0},
+		{"Header64.Shnum", Field, 0},
+		{"Header64.Shoff", Field, 0},
+		{"Header64.Shstrndx", Field, 0},
+		{"Header64.Type", Field, 0},
+		{"Header64.Version", Field, 0},
+		{"ImportedSymbol", Type, 0},
+		{"ImportedSymbol.Library", Field, 0},
+		{"ImportedSymbol.Name", Field, 0},
+		{"ImportedSymbol.Version", Field, 0},
+		{"Machine", Type, 0},
+		{"NT_FPREGSET", Const, 0},
+		{"NT_PRPSINFO", Const, 0},
+		{"NT_PRSTATUS", Const, 0},
+		{"NType", Type, 0},
+		{"NewFile", Func, 0},
+		{"OSABI", Type, 0},
+		{"Open", Func, 0},
+		{"PF_MASKOS", Const, 0},
+		{"PF_MASKPROC", Const, 0},
+		{"PF_R", Const, 0},
+		{"PF_W", Const, 0},
+		{"PF_X", Const, 0},
+		{"PT_AARCH64_ARCHEXT", Const, 16},
+		{"PT_AARCH64_UNWIND", Const, 16},
+		{"PT_ARM_ARCHEXT", Const, 16},
+		{"PT_ARM_EXIDX", Const, 16},
+		{"PT_DYNAMIC", Const, 0},
+		{"PT_GNU_EH_FRAME", Const, 16},
+		{"PT_GNU_MBIND_HI", Const, 16},
+		{"PT_GNU_MBIND_LO", Const, 16},
+		{"PT_GNU_PROPERTY", Const, 16},
+		{"PT_GNU_RELRO", Const, 16},
+		{"PT_GNU_STACK", Const, 16},
+		{"PT_HIOS", Const, 0},
+		{"PT_HIPROC", Const, 0},
+		{"PT_INTERP", Const, 0},
+		{"PT_LOAD", Const, 0},
+		{"PT_LOOS", Const, 0},
+		{"PT_LOPROC", Const, 0},
+		{"PT_MIPS_ABIFLAGS", Const, 16},
+		{"PT_MIPS_OPTIONS", Const, 16},
+		{"PT_MIPS_REGINFO", Const, 16},
+		{"PT_MIPS_RTPROC", Const, 16},
+		{"PT_NOTE", Const, 0},
+		{"PT_NULL", Const, 0},
+		{"PT_OPENBSD_BOOTDATA", Const, 16},
+		{"PT_OPENBSD_NOBTCFI", Const, 23},
+		{"PT_OPENBSD_RANDOMIZE", Const, 16},
+		{"PT_OPENBSD_WXNEEDED", Const, 16},
+		{"PT_PAX_FLAGS", Const, 16},
+		{"PT_PHDR", Const, 0},
+		{"PT_S390_PGSTE", Const, 16},
+		{"PT_SHLIB", Const, 0},
+		{"PT_SUNWSTACK", Const, 16},
+		{"PT_SUNW_EH_FRAME", Const, 16},
+		{"PT_TLS", Const, 0},
+		{"Prog", Type, 0},
+		{"Prog.ProgHeader", Field, 0},
+		{"Prog.ReaderAt", Field, 0},
+		{"Prog32", Type, 0},
+		{"Prog32.Align", Field, 0},
+		{"Prog32.Filesz", Field, 0},
+		{"Prog32.Flags", Field, 0},
+		{"Prog32.Memsz", Field, 0},
+		{"Prog32.Off", Field, 0},
+		{"Prog32.Paddr", Field, 0},
+		{"Prog32.Type", Field, 0},
+		{"Prog32.Vaddr", Field, 0},
+		{"Prog64", Type, 0},
+		{"Prog64.Align", Field, 0},
+		{"Prog64.Filesz", Field, 0},
+		{"Prog64.Flags", Field, 0},
+		{"Prog64.Memsz", Field, 0},
+		{"Prog64.Off", Field, 0},
+		{"Prog64.Paddr", Field, 0},
+		{"Prog64.Type", Field, 0},
+		{"Prog64.Vaddr", Field, 0},
+		{"ProgFlag", Type, 0},
+		{"ProgHeader", Type, 0},
+		{"ProgHeader.Align", Field, 0},
+		{"ProgHeader.Filesz", Field, 0},
+		{"ProgHeader.Flags", Field, 0},
+		{"ProgHeader.Memsz", Field, 0},
+		{"ProgHeader.Off", Field, 0},
+		{"ProgHeader.Paddr", Field, 0},
+		{"ProgHeader.Type", Field, 0},
+		{"ProgHeader.Vaddr", Field, 0},
+		{"ProgType", Type, 0},
+		{"R_386", Type, 0},
+		{"R_386_16", Const, 10},
+		{"R_386_32", Const, 0},
+		{"R_386_32PLT", Const, 10},
+		{"R_386_8", Const, 10},
+		{"R_386_COPY", Const, 0},
+		{"R_386_GLOB_DAT", Const, 0},
+		{"R_386_GOT32", Const, 0},
+		{"R_386_GOT32X", Const, 10},
+		{"R_386_GOTOFF", Const, 0},
+		{"R_386_GOTPC", Const, 0},
+		{"R_386_IRELATIVE", Const, 10},
+		{"R_386_JMP_SLOT", Const, 0},
+		{"R_386_NONE", Const, 0},
+		{"R_386_PC16", Const, 10},
+		{"R_386_PC32", Const, 0},
+		{"R_386_PC8", Const, 10},
+		{"R_386_PLT32", Const, 0},
+		{"R_386_RELATIVE", Const, 0},
+		{"R_386_SIZE32", Const, 10},
+		{"R_386_TLS_DESC", Const, 10},
+		{"R_386_TLS_DESC_CALL", Const, 10},
+		{"R_386_TLS_DTPMOD32", Const, 0},
+		{"R_386_TLS_DTPOFF32", Const, 0},
+		{"R_386_TLS_GD", Const, 0},
+		{"R_386_TLS_GD_32", Const, 0},
+		{"R_386_TLS_GD_CALL", Const, 0},
+		{"R_386_TLS_GD_POP", Const, 0},
+		{"R_386_TLS_GD_PUSH", Const, 0},
+		{"R_386_TLS_GOTDESC", Const, 10},
+		{"R_386_TLS_GOTIE", Const, 0},
+		{"R_386_TLS_IE", Const, 0},
+		{"R_386_TLS_IE_32", Const, 0},
+		{"R_386_TLS_LDM", Const, 0},
+		{"R_386_TLS_LDM_32", Const, 0},
+		{"R_386_TLS_LDM_CALL", Const, 0},
+		{"R_386_TLS_LDM_POP", Const, 0},
+		{"R_386_TLS_LDM_PUSH", Const, 0},
+		{"R_386_TLS_LDO_32", Const, 0},
+		{"R_386_TLS_LE", Const, 0},
+		{"R_386_TLS_LE_32", Const, 0},
+		{"R_386_TLS_TPOFF", Const, 0},
+		{"R_386_TLS_TPOFF32", Const, 0},
+		{"R_390", Type, 7},
+		{"R_390_12", Const, 7},
+		{"R_390_16", Const, 7},
+		{"R_390_20", Const, 7},
+		{"R_390_32", Const, 7},
+		{"R_390_64", Const, 7},
+		{"R_390_8", Const, 7},
+		{"R_390_COPY", Const, 7},
+		{"R_390_GLOB_DAT", Const, 7},
+		{"R_390_GOT12", Const, 7},
+		{"R_390_GOT16", Const, 7},
+		{"R_390_GOT20", Const, 7},
+		{"R_390_GOT32", Const, 7},
+		{"R_390_GOT64", Const, 7},
+		{"R_390_GOTENT", Const, 7},
+		{"R_390_GOTOFF", Const, 7},
+		{"R_390_GOTOFF16", Const, 7},
+		{"R_390_GOTOFF64", Const, 7},
+		{"R_390_GOTPC", Const, 7},
+		{"R_390_GOTPCDBL", Const, 7},
+		{"R_390_GOTPLT12", Const, 7},
+		{"R_390_GOTPLT16", Const, 7},
+		{"R_390_GOTPLT20", Const, 7},
+		{"R_390_GOTPLT32", Const, 7},
+		{"R_390_GOTPLT64", Const, 7},
+		{"R_390_GOTPLTENT", Const, 7},
+		{"R_390_GOTPLTOFF16", Const, 7},
+		{"R_390_GOTPLTOFF32", Const, 7},
+		{"R_390_GOTPLTOFF64", Const, 7},
+		{"R_390_JMP_SLOT", Const, 7},
+		{"R_390_NONE", Const, 7},
+		{"R_390_PC16", Const, 7},
+		{"R_390_PC16DBL", Const, 7},
+		{"R_390_PC32", Const, 7},
+		{"R_390_PC32DBL", Const, 7},
+		{"R_390_PC64", Const, 7},
+		{"R_390_PLT16DBL", Const, 7},
+		{"R_390_PLT32", Const, 7},
+		{"R_390_PLT32DBL", Const, 7},
+		{"R_390_PLT64", Const, 7},
+		{"R_390_RELATIVE", Const, 7},
+		{"R_390_TLS_DTPMOD", Const, 7},
+		{"R_390_TLS_DTPOFF", Const, 7},
+		{"R_390_TLS_GD32", Const, 7},
+		{"R_390_TLS_GD64", Const, 7},
+		{"R_390_TLS_GDCALL", Const, 7},
+		{"R_390_TLS_GOTIE12", Const, 7},
+		{"R_390_TLS_GOTIE20", Const, 7},
+		{"R_390_TLS_GOTIE32", Const, 7},
+		{"R_390_TLS_GOTIE64", Const, 7},
+		{"R_390_TLS_IE32", Const, 7},
+		{"R_390_TLS_IE64", Const, 7},
+		{"R_390_TLS_IEENT", Const, 7},
+		{"R_390_TLS_LDCALL", Const, 7},
+		{"R_390_TLS_LDM32", Const, 7},
+		{"R_390_TLS_LDM64", Const, 7},
+		{"R_390_TLS_LDO32", Const, 7},
+		{"R_390_TLS_LDO64", Const, 7},
+		{"R_390_TLS_LE32", Const, 7},
+		{"R_390_TLS_LE64", Const, 7},
+		{"R_390_TLS_LOAD", Const, 7},
+		{"R_390_TLS_TPOFF", Const, 7},
+		{"R_AARCH64", Type, 4},
+		{"R_AARCH64_ABS16", Const, 4},
+		{"R_AARCH64_ABS32", Const, 4},
+		{"R_AARCH64_ABS64", Const, 4},
+		{"R_AARCH64_ADD_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_ADR_GOT_PAGE", Const, 4},
+		{"R_AARCH64_ADR_PREL_LO21", Const, 4},
+		{"R_AARCH64_ADR_PREL_PG_HI21", Const, 4},
+		{"R_AARCH64_ADR_PREL_PG_HI21_NC", Const, 4},
+		{"R_AARCH64_CALL26", Const, 4},
+		{"R_AARCH64_CONDBR19", Const, 4},
+		{"R_AARCH64_COPY", Const, 4},
+		{"R_AARCH64_GLOB_DAT", Const, 4},
+		{"R_AARCH64_GOT_LD_PREL19", Const, 4},
+		{"R_AARCH64_IRELATIVE", Const, 4},
+		{"R_AARCH64_JUMP26", Const, 4},
+		{"R_AARCH64_JUMP_SLOT", Const, 4},
+		{"R_AARCH64_LD64_GOTOFF_LO15", Const, 10},
+		{"R_AARCH64_LD64_GOTPAGE_LO15", Const, 10},
+		{"R_AARCH64_LD64_GOT_LO12_NC", Const, 4},
+		{"R_AARCH64_LDST128_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_LDST16_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_LDST32_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_LDST64_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_LDST8_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_LD_PREL_LO19", Const, 4},
+		{"R_AARCH64_MOVW_SABS_G0", Const, 4},
+		{"R_AARCH64_MOVW_SABS_G1", Const, 4},
+		{"R_AARCH64_MOVW_SABS_G2", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G0", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G0_NC", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G1", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G1_NC", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G2", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G2_NC", Const, 4},
+		{"R_AARCH64_MOVW_UABS_G3", Const, 4},
+		{"R_AARCH64_NONE", Const, 4},
+		{"R_AARCH64_NULL", Const, 4},
+		{"R_AARCH64_P32_ABS16", Const, 4},
+		{"R_AARCH64_P32_ABS32", Const, 4},
+		{"R_AARCH64_P32_ADD_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_ADR_GOT_PAGE", Const, 4},
+		{"R_AARCH64_P32_ADR_PREL_LO21", Const, 4},
+		{"R_AARCH64_P32_ADR_PREL_PG_HI21", Const, 4},
+		{"R_AARCH64_P32_CALL26", Const, 4},
+		{"R_AARCH64_P32_CONDBR19", Const, 4},
+		{"R_AARCH64_P32_COPY", Const, 4},
+		{"R_AARCH64_P32_GLOB_DAT", Const, 4},
+		{"R_AARCH64_P32_GOT_LD_PREL19", Const, 4},
+		{"R_AARCH64_P32_IRELATIVE", Const, 4},
+		{"R_AARCH64_P32_JUMP26", Const, 4},
+		{"R_AARCH64_P32_JUMP_SLOT", Const, 4},
+		{"R_AARCH64_P32_LD32_GOT_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LDST128_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LDST16_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LDST32_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LDST64_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LDST8_ABS_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_LD_PREL_LO19", Const, 4},
+		{"R_AARCH64_P32_MOVW_SABS_G0", Const, 4},
+		{"R_AARCH64_P32_MOVW_UABS_G0", Const, 4},
+		{"R_AARCH64_P32_MOVW_UABS_G0_NC", Const, 4},
+		{"R_AARCH64_P32_MOVW_UABS_G1", Const, 4},
+		{"R_AARCH64_P32_PREL16", Const, 4},
+		{"R_AARCH64_P32_PREL32", Const, 4},
+		{"R_AARCH64_P32_RELATIVE", Const, 4},
+		{"R_AARCH64_P32_TLSDESC", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_ADD_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_ADR_PAGE21", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_ADR_PREL21", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_CALL", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_LD32_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_TLSDESC_LD_PREL19", Const, 4},
+		{"R_AARCH64_P32_TLSGD_ADD_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_TLSGD_ADR_PAGE21", Const, 4},
+		{"R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21", Const, 4},
+		{"R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19", Const, 4},
+		{"R_AARCH64_P32_TLSLE_ADD_TPREL_HI12", Const, 4},
+		{"R_AARCH64_P32_TLSLE_ADD_TPREL_LO12", Const, 4},
+		{"R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC", Const, 4},
+		{"R_AARCH64_P32_TLSLE_MOVW_TPREL_G0", Const, 4},
+		{"R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC", Const, 4},
+		{"R_AARCH64_P32_TLSLE_MOVW_TPREL_G1", Const, 4},
+		{"R_AARCH64_P32_TLS_DTPMOD", Const, 4},
+		{"R_AARCH64_P32_TLS_DTPREL", Const, 4},
+		{"R_AARCH64_P32_TLS_TPREL", Const, 4},
+		{"R_AARCH64_P32_TSTBR14", Const, 4},
+		{"R_AARCH64_PREL16", Const, 4},
+		{"R_AARCH64_PREL32", Const, 4},
+		{"R_AARCH64_PREL64", Const, 4},
+		{"R_AARCH64_RELATIVE", Const, 4},
+		{"R_AARCH64_TLSDESC", Const, 4},
+		{"R_AARCH64_TLSDESC_ADD", Const, 4},
+		{"R_AARCH64_TLSDESC_ADD_LO12_NC", Const, 4},
+		{"R_AARCH64_TLSDESC_ADR_PAGE21", Const, 4},
+		{"R_AARCH64_TLSDESC_ADR_PREL21", Const, 4},
+		{"R_AARCH64_TLSDESC_CALL", Const, 4},
+		{"R_AARCH64_TLSDESC_LD64_LO12_NC", Const, 4},
+		{"R_AARCH64_TLSDESC_LDR", Const, 4},
+		{"R_AARCH64_TLSDESC_LD_PREL19", Const, 4},
+		{"R_AARCH64_TLSDESC_OFF_G0_NC", Const, 4},
+		{"R_AARCH64_TLSDESC_OFF_G1", Const, 4},
+		{"R_AARCH64_TLSGD_ADD_LO12_NC", Const, 4},
+		{"R_AARCH64_TLSGD_ADR_PAGE21", Const, 4},
+		{"R_AARCH64_TLSGD_ADR_PREL21", Const, 10},
+		{"R_AARCH64_TLSGD_MOVW_G0_NC", Const, 10},
+		{"R_AARCH64_TLSGD_MOVW_G1", Const, 10},
+		{"R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21", Const, 4},
+		{"R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC", Const, 4},
+		{"R_AARCH64_TLSIE_LD_GOTTPREL_PREL19", Const, 4},
+		{"R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC", Const, 4},
+		{"R_AARCH64_TLSIE_MOVW_GOTTPREL_G1", Const, 4},
+		{"R_AARCH64_TLSLD_ADR_PAGE21", Const, 10},
+		{"R_AARCH64_TLSLD_ADR_PREL21", Const, 10},
+		{"R_AARCH64_TLSLD_LDST128_DTPREL_LO12", Const, 10},
+		{"R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC", Const, 10},
+		{"R_AARCH64_TLSLE_ADD_TPREL_HI12", Const, 4},
+		{"R_AARCH64_TLSLE_ADD_TPREL_LO12", Const, 4},
+		{"R_AARCH64_TLSLE_ADD_TPREL_LO12_NC", Const, 4},
+		{"R_AARCH64_TLSLE_LDST128_TPREL_LO12", Const, 10},
+		{"R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC", Const, 10},
+		{"R_AARCH64_TLSLE_MOVW_TPREL_G0", Const, 4},
+		{"R_AARCH64_TLSLE_MOVW_TPREL_G0_NC", Const, 4},
+		{"R_AARCH64_TLSLE_MOVW_TPREL_G1", Const, 4},
+		{"R_AARCH64_TLSLE_MOVW_TPREL_G1_NC", Const, 4},
+		{"R_AARCH64_TLSLE_MOVW_TPREL_G2", Const, 4},
+		{"R_AARCH64_TLS_DTPMOD64", Const, 4},
+		{"R_AARCH64_TLS_DTPREL64", Const, 4},
+		{"R_AARCH64_TLS_TPREL64", Const, 4},
+		{"R_AARCH64_TSTBR14", Const, 4},
+		{"R_ALPHA", Type, 0},
+		{"R_ALPHA_BRADDR", Const, 0},
+		{"R_ALPHA_COPY", Const, 0},
+		{"R_ALPHA_GLOB_DAT", Const, 0},
+		{"R_ALPHA_GPDISP", Const, 0},
+		{"R_ALPHA_GPREL32", Const, 0},
+		{"R_ALPHA_GPRELHIGH", Const, 0},
+		{"R_ALPHA_GPRELLOW", Const, 0},
+		{"R_ALPHA_GPVALUE", Const, 0},
+		{"R_ALPHA_HINT", Const, 0},
+		{"R_ALPHA_IMMED_BR_HI32", Const, 0},
+		{"R_ALPHA_IMMED_GP_16", Const, 0},
+		{"R_ALPHA_IMMED_GP_HI32", Const, 0},
+		{"R_ALPHA_IMMED_LO32", Const, 0},
+		{"R_ALPHA_IMMED_SCN_HI32", Const, 0},
+		{"R_ALPHA_JMP_SLOT", Const, 0},
+		{"R_ALPHA_LITERAL", Const, 0},
+		{"R_ALPHA_LITUSE", Const, 0},
+		{"R_ALPHA_NONE", Const, 0},
+		{"R_ALPHA_OP_PRSHIFT", Const, 0},
+		{"R_ALPHA_OP_PSUB", Const, 0},
+		{"R_ALPHA_OP_PUSH", Const, 0},
+		{"R_ALPHA_OP_STORE", Const, 0},
+		{"R_ALPHA_REFLONG", Const, 0},
+		{"R_ALPHA_REFQUAD", Const, 0},
+		{"R_ALPHA_RELATIVE", Const, 0},
+		{"R_ALPHA_SREL16", Const, 0},
+		{"R_ALPHA_SREL32", Const, 0},
+		{"R_ALPHA_SREL64", Const, 0},
+		{"R_ARM", Type, 0},
+		{"R_ARM_ABS12", Const, 0},
+		{"R_ARM_ABS16", Const, 0},
+		{"R_ARM_ABS32", Const, 0},
+		{"R_ARM_ABS32_NOI", Const, 10},
+		{"R_ARM_ABS8", Const, 0},
+		{"R_ARM_ALU_PCREL_15_8", Const, 10},
+		{"R_ARM_ALU_PCREL_23_15", Const, 10},
+		{"R_ARM_ALU_PCREL_7_0", Const, 10},
+		{"R_ARM_ALU_PC_G0", Const, 10},
+		{"R_ARM_ALU_PC_G0_NC", Const, 10},
+		{"R_ARM_ALU_PC_G1", Const, 10},
+		{"R_ARM_ALU_PC_G1_NC", Const, 10},
+		{"R_ARM_ALU_PC_G2", Const, 10},
+		{"R_ARM_ALU_SBREL_19_12_NC", Const, 10},
+		{"R_ARM_ALU_SBREL_27_20_CK", Const, 10},
+		{"R_ARM_ALU_SB_G0", Const, 10},
+		{"R_ARM_ALU_SB_G0_NC", Const, 10},
+		{"R_ARM_ALU_SB_G1", Const, 10},
+		{"R_ARM_ALU_SB_G1_NC", Const, 10},
+		{"R_ARM_ALU_SB_G2", Const, 10},
+		{"R_ARM_AMP_VCALL9", Const, 0},
+		{"R_ARM_BASE_ABS", Const, 10},
+		{"R_ARM_CALL", Const, 10},
+		{"R_ARM_COPY", Const, 0},
+		{"R_ARM_GLOB_DAT", Const, 0},
+		{"R_ARM_GNU_VTENTRY", Const, 0},
+		{"R_ARM_GNU_VTINHERIT", Const, 0},
+		{"R_ARM_GOT32", Const, 0},
+		{"R_ARM_GOTOFF", Const, 0},
+		{"R_ARM_GOTOFF12", Const, 10},
+		{"R_ARM_GOTPC", Const, 0},
+		{"R_ARM_GOTRELAX", Const, 10},
+		{"R_ARM_GOT_ABS", Const, 10},
+		{"R_ARM_GOT_BREL12", Const, 10},
+		{"R_ARM_GOT_PREL", Const, 10},
+		{"R_ARM_IRELATIVE", Const, 10},
+		{"R_ARM_JUMP24", Const, 10},
+		{"R_ARM_JUMP_SLOT", Const, 0},
+		{"R_ARM_LDC_PC_G0", Const, 10},
+		{"R_ARM_LDC_PC_G1", Const, 10},
+		{"R_ARM_LDC_PC_G2", Const, 10},
+		{"R_ARM_LDC_SB_G0", Const, 10},
+		{"R_ARM_LDC_SB_G1", Const, 10},
+		{"R_ARM_LDC_SB_G2", Const, 10},
+		{"R_ARM_LDRS_PC_G0", Const, 10},
+		{"R_ARM_LDRS_PC_G1", Const, 10},
+		{"R_ARM_LDRS_PC_G2", Const, 10},
+		{"R_ARM_LDRS_SB_G0", Const, 10},
+		{"R_ARM_LDRS_SB_G1", Const, 10},
+		{"R_ARM_LDRS_SB_G2", Const, 10},
+		{"R_ARM_LDR_PC_G1", Const, 10},
+		{"R_ARM_LDR_PC_G2", Const, 10},
+		{"R_ARM_LDR_SBREL_11_10_NC", Const, 10},
+		{"R_ARM_LDR_SB_G0", Const, 10},
+		{"R_ARM_LDR_SB_G1", Const, 10},
+		{"R_ARM_LDR_SB_G2", Const, 10},
+		{"R_ARM_ME_TOO", Const, 10},
+		{"R_ARM_MOVT_ABS", Const, 10},
+		{"R_ARM_MOVT_BREL", Const, 10},
+		{"R_ARM_MOVT_PREL", Const, 10},
+		{"R_ARM_MOVW_ABS_NC", Const, 10},
+		{"R_ARM_MOVW_BREL", Const, 10},
+		{"R_ARM_MOVW_BREL_NC", Const, 10},
+		{"R_ARM_MOVW_PREL_NC", Const, 10},
+		{"R_ARM_NONE", Const, 0},
+		{"R_ARM_PC13", Const, 0},
+		{"R_ARM_PC24", Const, 0},
+		{"R_ARM_PLT32", Const, 0},
+		{"R_ARM_PLT32_ABS", Const, 10},
+		{"R_ARM_PREL31", Const, 10},
+		{"R_ARM_PRIVATE_0", Const, 10},
+		{"R_ARM_PRIVATE_1", Const, 10},
+		{"R_ARM_PRIVATE_10", Const, 10},
+		{"R_ARM_PRIVATE_11", Const, 10},
+		{"R_ARM_PRIVATE_12", Const, 10},
+		{"R_ARM_PRIVATE_13", Const, 10},
+		{"R_ARM_PRIVATE_14", Const, 10},
+		{"R_ARM_PRIVATE_15", Const, 10},
+		{"R_ARM_PRIVATE_2", Const, 10},
+		{"R_ARM_PRIVATE_3", Const, 10},
+		{"R_ARM_PRIVATE_4", Const, 10},
+		{"R_ARM_PRIVATE_5", Const, 10},
+		{"R_ARM_PRIVATE_6", Const, 10},
+		{"R_ARM_PRIVATE_7", Const, 10},
+		{"R_ARM_PRIVATE_8", Const, 10},
+		{"R_ARM_PRIVATE_9", Const, 10},
+		{"R_ARM_RABS32", Const, 0},
+		{"R_ARM_RBASE", Const, 0},
+		{"R_ARM_REL32", Const, 0},
+		{"R_ARM_REL32_NOI", Const, 10},
+		{"R_ARM_RELATIVE", Const, 0},
+		{"R_ARM_RPC24", Const, 0},
+		{"R_ARM_RREL32", Const, 0},
+		{"R_ARM_RSBREL32", Const, 0},
+		{"R_ARM_RXPC25", Const, 10},
+		{"R_ARM_SBREL31", Const, 10},
+		{"R_ARM_SBREL32", Const, 0},
+		{"R_ARM_SWI24", Const, 0},
+		{"R_ARM_TARGET1", Const, 10},
+		{"R_ARM_TARGET2", Const, 10},
+		{"R_ARM_THM_ABS5", Const, 0},
+		{"R_ARM_THM_ALU_ABS_G0_NC", Const, 10},
+		{"R_ARM_THM_ALU_ABS_G1_NC", Const, 10},
+		{"R_ARM_THM_ALU_ABS_G2_NC", Const, 10},
+		{"R_ARM_THM_ALU_ABS_G3", Const, 10},
+		{"R_ARM_THM_ALU_PREL_11_0", Const, 10},
+		{"R_ARM_THM_GOT_BREL12", Const, 10},
+		{"R_ARM_THM_JUMP11", Const, 10},
+		{"R_ARM_THM_JUMP19", Const, 10},
+		{"R_ARM_THM_JUMP24", Const, 10},
+		{"R_ARM_THM_JUMP6", Const, 10},
+		{"R_ARM_THM_JUMP8", Const, 10},
+		{"R_ARM_THM_MOVT_ABS", Const, 10},
+		{"R_ARM_THM_MOVT_BREL", Const, 10},
+		{"R_ARM_THM_MOVT_PREL", Const, 10},
+		{"R_ARM_THM_MOVW_ABS_NC", Const, 10},
+		{"R_ARM_THM_MOVW_BREL", Const, 10},
+		{"R_ARM_THM_MOVW_BREL_NC", Const, 10},
+		{"R_ARM_THM_MOVW_PREL_NC", Const, 10},
+		{"R_ARM_THM_PC12", Const, 10},
+		{"R_ARM_THM_PC22", Const, 0},
+		{"R_ARM_THM_PC8", Const, 0},
+		{"R_ARM_THM_RPC22", Const, 0},
+		{"R_ARM_THM_SWI8", Const, 0},
+		{"R_ARM_THM_TLS_CALL", Const, 10},
+		{"R_ARM_THM_TLS_DESCSEQ16", Const, 10},
+		{"R_ARM_THM_TLS_DESCSEQ32", Const, 10},
+		{"R_ARM_THM_XPC22", Const, 0},
+		{"R_ARM_TLS_CALL", Const, 10},
+		{"R_ARM_TLS_DESCSEQ", Const, 10},
+		{"R_ARM_TLS_DTPMOD32", Const, 10},
+		{"R_ARM_TLS_DTPOFF32", Const, 10},
+		{"R_ARM_TLS_GD32", Const, 10},
+		{"R_ARM_TLS_GOTDESC", Const, 10},
+		{"R_ARM_TLS_IE12GP", Const, 10},
+		{"R_ARM_TLS_IE32", Const, 10},
+		{"R_ARM_TLS_LDM32", Const, 10},
+		{"R_ARM_TLS_LDO12", Const, 10},
+		{"R_ARM_TLS_LDO32", Const, 10},
+		{"R_ARM_TLS_LE12", Const, 10},
+		{"R_ARM_TLS_LE32", Const, 10},
+		{"R_ARM_TLS_TPOFF32", Const, 10},
+		{"R_ARM_V4BX", Const, 10},
+		{"R_ARM_XPC25", Const, 0},
+		{"R_INFO", Func, 0},
+		{"R_INFO32", Func, 0},
+		{"R_LARCH", Type, 19},
+		{"R_LARCH_32", Const, 19},
+		{"R_LARCH_32_PCREL", Const, 20},
+		{"R_LARCH_64", Const, 19},
+		{"R_LARCH_64_PCREL", Const, 22},
+		{"R_LARCH_ABS64_HI12", Const, 20},
+		{"R_LARCH_ABS64_LO20", Const, 20},
+		{"R_LARCH_ABS_HI20", Const, 20},
+		{"R_LARCH_ABS_LO12", Const, 20},
+		{"R_LARCH_ADD16", Const, 19},
+		{"R_LARCH_ADD24", Const, 19},
+		{"R_LARCH_ADD32", Const, 19},
+		{"R_LARCH_ADD6", Const, 22},
+		{"R_LARCH_ADD64", Const, 19},
+		{"R_LARCH_ADD8", Const, 19},
+		{"R_LARCH_ADD_ULEB128", Const, 22},
+		{"R_LARCH_ALIGN", Const, 22},
+		{"R_LARCH_B16", Const, 20},
+		{"R_LARCH_B21", Const, 20},
+		{"R_LARCH_B26", Const, 20},
+		{"R_LARCH_CFA", Const, 22},
+		{"R_LARCH_COPY", Const, 19},
+		{"R_LARCH_DELETE", Const, 22},
+		{"R_LARCH_GNU_VTENTRY", Const, 20},
+		{"R_LARCH_GNU_VTINHERIT", Const, 20},
+		{"R_LARCH_GOT64_HI12", Const, 20},
+		{"R_LARCH_GOT64_LO20", Const, 20},
+		{"R_LARCH_GOT64_PC_HI12", Const, 20},
+		{"R_LARCH_GOT64_PC_LO20", Const, 20},
+		{"R_LARCH_GOT_HI20", Const, 20},
+		{"R_LARCH_GOT_LO12", Const, 20},
+		{"R_LARCH_GOT_PC_HI20", Const, 20},
+		{"R_LARCH_GOT_PC_LO12", Const, 20},
+		{"R_LARCH_IRELATIVE", Const, 19},
+		{"R_LARCH_JUMP_SLOT", Const, 19},
+		{"R_LARCH_MARK_LA", Const, 19},
+		{"R_LARCH_MARK_PCREL", Const, 19},
+		{"R_LARCH_NONE", Const, 19},
+		{"R_LARCH_PCALA64_HI12", Const, 20},
+		{"R_LARCH_PCALA64_LO20", Const, 20},
+		{"R_LARCH_PCALA_HI20", Const, 20},
+		{"R_LARCH_PCALA_LO12", Const, 20},
+		{"R_LARCH_PCREL20_S2", Const, 22},
+		{"R_LARCH_RELATIVE", Const, 19},
+		{"R_LARCH_RELAX", Const, 20},
+		{"R_LARCH_SOP_ADD", Const, 19},
+		{"R_LARCH_SOP_AND", Const, 19},
+		{"R_LARCH_SOP_ASSERT", Const, 19},
+		{"R_LARCH_SOP_IF_ELSE", Const, 19},
+		{"R_LARCH_SOP_NOT", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_0_10_10_16_S2", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_0_5_10_16_S2", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_10_12", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_10_16", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_10_16_S2", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_10_5", Const, 19},
+		{"R_LARCH_SOP_POP_32_S_5_20", Const, 19},
+		{"R_LARCH_SOP_POP_32_U", Const, 19},
+		{"R_LARCH_SOP_POP_32_U_10_12", Const, 19},
+		{"R_LARCH_SOP_PUSH_ABSOLUTE", Const, 19},
+		{"R_LARCH_SOP_PUSH_DUP", Const, 19},
+		{"R_LARCH_SOP_PUSH_GPREL", Const, 19},
+		{"R_LARCH_SOP_PUSH_PCREL", Const, 19},
+		{"R_LARCH_SOP_PUSH_PLT_PCREL", Const, 19},
+		{"R_LARCH_SOP_PUSH_TLS_GD", Const, 19},
+		{"R_LARCH_SOP_PUSH_TLS_GOT", Const, 19},
+		{"R_LARCH_SOP_PUSH_TLS_TPREL", Const, 19},
+		{"R_LARCH_SOP_SL", Const, 19},
+		{"R_LARCH_SOP_SR", Const, 19},
+		{"R_LARCH_SOP_SUB", Const, 19},
+		{"R_LARCH_SUB16", Const, 19},
+		{"R_LARCH_SUB24", Const, 19},
+		{"R_LARCH_SUB32", Const, 19},
+		{"R_LARCH_SUB6", Const, 22},
+		{"R_LARCH_SUB64", Const, 19},
+		{"R_LARCH_SUB8", Const, 19},
+		{"R_LARCH_SUB_ULEB128", Const, 22},
+		{"R_LARCH_TLS_DTPMOD32", Const, 19},
+		{"R_LARCH_TLS_DTPMOD64", Const, 19},
+		{"R_LARCH_TLS_DTPREL32", Const, 19},
+		{"R_LARCH_TLS_DTPREL64", Const, 19},
+		{"R_LARCH_TLS_GD_HI20", Const, 20},
+		{"R_LARCH_TLS_GD_PC_HI20", Const, 20},
+		{"R_LARCH_TLS_IE64_HI12", Const, 20},
+		{"R_LARCH_TLS_IE64_LO20", Const, 20},
+		{"R_LARCH_TLS_IE64_PC_HI12", Const, 20},
+		{"R_LARCH_TLS_IE64_PC_LO20", Const, 20},
+		{"R_LARCH_TLS_IE_HI20", Const, 20},
+		{"R_LARCH_TLS_IE_LO12", Const, 20},
+		{"R_LARCH_TLS_IE_PC_HI20", Const, 20},
+		{"R_LARCH_TLS_IE_PC_LO12", Const, 20},
+		{"R_LARCH_TLS_LD_HI20", Const, 20},
+		{"R_LARCH_TLS_LD_PC_HI20", Const, 20},
+		{"R_LARCH_TLS_LE64_HI12", Const, 20},
+		{"R_LARCH_TLS_LE64_LO20", Const, 20},
+		{"R_LARCH_TLS_LE_HI20", Const, 20},
+		{"R_LARCH_TLS_LE_LO12", Const, 20},
+		{"R_LARCH_TLS_TPREL32", Const, 19},
+		{"R_LARCH_TLS_TPREL64", Const, 19},
+		{"R_MIPS", Type, 6},
+		{"R_MIPS_16", Const, 6},
+		{"R_MIPS_26", Const, 6},
+		{"R_MIPS_32", Const, 6},
+		{"R_MIPS_64", Const, 6},
+		{"R_MIPS_ADD_IMMEDIATE", Const, 6},
+		{"R_MIPS_CALL16", Const, 6},
+		{"R_MIPS_CALL_HI16", Const, 6},
+		{"R_MIPS_CALL_LO16", Const, 6},
+		{"R_MIPS_DELETE", Const, 6},
+		{"R_MIPS_GOT16", Const, 6},
+		{"R_MIPS_GOT_DISP", Const, 6},
+		{"R_MIPS_GOT_HI16", Const, 6},
+		{"R_MIPS_GOT_LO16", Const, 6},
+		{"R_MIPS_GOT_OFST", Const, 6},
+		{"R_MIPS_GOT_PAGE", Const, 6},
+		{"R_MIPS_GPREL16", Const, 6},
+		{"R_MIPS_GPREL32", Const, 6},
+		{"R_MIPS_HI16", Const, 6},
+		{"R_MIPS_HIGHER", Const, 6},
+		{"R_MIPS_HIGHEST", Const, 6},
+		{"R_MIPS_INSERT_A", Const, 6},
+		{"R_MIPS_INSERT_B", Const, 6},
+		{"R_MIPS_JALR", Const, 6},
+		{"R_MIPS_LITERAL", Const, 6},
+		{"R_MIPS_LO16", Const, 6},
+		{"R_MIPS_NONE", Const, 6},
+		{"R_MIPS_PC16", Const, 6},
+		{"R_MIPS_PC32", Const, 22},
+		{"R_MIPS_PJUMP", Const, 6},
+		{"R_MIPS_REL16", Const, 6},
+		{"R_MIPS_REL32", Const, 6},
+		{"R_MIPS_RELGOT", Const, 6},
+		{"R_MIPS_SCN_DISP", Const, 6},
+		{"R_MIPS_SHIFT5", Const, 6},
+		{"R_MIPS_SHIFT6", Const, 6},
+		{"R_MIPS_SUB", Const, 6},
+		{"R_MIPS_TLS_DTPMOD32", Const, 6},
+		{"R_MIPS_TLS_DTPMOD64", Const, 6},
+		{"R_MIPS_TLS_DTPREL32", Const, 6},
+		{"R_MIPS_TLS_DTPREL64", Const, 6},
+		{"R_MIPS_TLS_DTPREL_HI16", Const, 6},
+		{"R_MIPS_TLS_DTPREL_LO16", Const, 6},
+		{"R_MIPS_TLS_GD", Const, 6},
+		{"R_MIPS_TLS_GOTTPREL", Const, 6},
+		{"R_MIPS_TLS_LDM", Const, 6},
+		{"R_MIPS_TLS_TPREL32", Const, 6},
+		{"R_MIPS_TLS_TPREL64", Const, 6},
+		{"R_MIPS_TLS_TPREL_HI16", Const, 6},
+		{"R_MIPS_TLS_TPREL_LO16", Const, 6},
+		{"R_PPC", Type, 0},
+		{"R_PPC64", Type, 5},
+		{"R_PPC64_ADDR14", Const, 5},
+		{"R_PPC64_ADDR14_BRNTAKEN", Const, 5},
+		{"R_PPC64_ADDR14_BRTAKEN", Const, 5},
+		{"R_PPC64_ADDR16", Const, 5},
+		{"R_PPC64_ADDR16_DS", Const, 5},
+		{"R_PPC64_ADDR16_HA", Const, 5},
+		{"R_PPC64_ADDR16_HI", Const, 5},
+		{"R_PPC64_ADDR16_HIGH", Const, 10},
+		{"R_PPC64_ADDR16_HIGHA", Const, 10},
+		{"R_PPC64_ADDR16_HIGHER", Const, 5},
+		{"R_PPC64_ADDR16_HIGHER34", Const, 20},
+		{"R_PPC64_ADDR16_HIGHERA", Const, 5},
+		{"R_PPC64_ADDR16_HIGHERA34", Const, 20},
+		{"R_PPC64_ADDR16_HIGHEST", Const, 5},
+		{"R_PPC64_ADDR16_HIGHEST34", Const, 20},
+		{"R_PPC64_ADDR16_HIGHESTA", Const, 5},
+		{"R_PPC64_ADDR16_HIGHESTA34", Const, 20},
+		{"R_PPC64_ADDR16_LO", Const, 5},
+		{"R_PPC64_ADDR16_LO_DS", Const, 5},
+		{"R_PPC64_ADDR24", Const, 5},
+		{"R_PPC64_ADDR32", Const, 5},
+		{"R_PPC64_ADDR64", Const, 5},
+		{"R_PPC64_ADDR64_LOCAL", Const, 10},
+		{"R_PPC64_COPY", Const, 20},
+		{"R_PPC64_D28", Const, 20},
+		{"R_PPC64_D34", Const, 20},
+		{"R_PPC64_D34_HA30", Const, 20},
+		{"R_PPC64_D34_HI30", Const, 20},
+		{"R_PPC64_D34_LO", Const, 20},
+		{"R_PPC64_DTPMOD64", Const, 5},
+		{"R_PPC64_DTPREL16", Const, 5},
+		{"R_PPC64_DTPREL16_DS", Const, 5},
+		{"R_PPC64_DTPREL16_HA", Const, 5},
+		{"R_PPC64_DTPREL16_HI", Const, 5},
+		{"R_PPC64_DTPREL16_HIGH", Const, 10},
+		{"R_PPC64_DTPREL16_HIGHA", Const, 10},
+		{"R_PPC64_DTPREL16_HIGHER", Const, 5},
+		{"R_PPC64_DTPREL16_HIGHERA", Const, 5},
+		{"R_PPC64_DTPREL16_HIGHEST", Const, 5},
+		{"R_PPC64_DTPREL16_HIGHESTA", Const, 5},
+		{"R_PPC64_DTPREL16_LO", Const, 5},
+		{"R_PPC64_DTPREL16_LO_DS", Const, 5},
+		{"R_PPC64_DTPREL34", Const, 20},
+		{"R_PPC64_DTPREL64", Const, 5},
+		{"R_PPC64_ENTRY", Const, 10},
+		{"R_PPC64_GLOB_DAT", Const, 20},
+		{"R_PPC64_GNU_VTENTRY", Const, 20},
+		{"R_PPC64_GNU_VTINHERIT", Const, 20},
+		{"R_PPC64_GOT16", Const, 5},
+		{"R_PPC64_GOT16_DS", Const, 5},
+		{"R_PPC64_GOT16_HA", Const, 5},
+		{"R_PPC64_GOT16_HI", Const, 5},
+		{"R_PPC64_GOT16_LO", Const, 5},
+		{"R_PPC64_GOT16_LO_DS", Const, 5},
+		{"R_PPC64_GOT_DTPREL16_DS", Const, 5},
+		{"R_PPC64_GOT_DTPREL16_HA", Const, 5},
+		{"R_PPC64_GOT_DTPREL16_HI", Const, 5},
+		{"R_PPC64_GOT_DTPREL16_LO_DS", Const, 5},
+		{"R_PPC64_GOT_DTPREL_PCREL34", Const, 20},
+		{"R_PPC64_GOT_PCREL34", Const, 20},
+		{"R_PPC64_GOT_TLSGD16", Const, 5},
+		{"R_PPC64_GOT_TLSGD16_HA", Const, 5},
+		{"R_PPC64_GOT_TLSGD16_HI", Const, 5},
+		{"R_PPC64_GOT_TLSGD16_LO", Const, 5},
+		{"R_PPC64_GOT_TLSGD_PCREL34", Const, 20},
+		{"R_PPC64_GOT_TLSLD16", Const, 5},
+		{"R_PPC64_GOT_TLSLD16_HA", Const, 5},
+		{"R_PPC64_GOT_TLSLD16_HI", Const, 5},
+		{"R_PPC64_GOT_TLSLD16_LO", Const, 5},
+		{"R_PPC64_GOT_TLSLD_PCREL34", Const, 20},
+		{"R_PPC64_GOT_TPREL16_DS", Const, 5},
+		{"R_PPC64_GOT_TPREL16_HA", Const, 5},
+		{"R_PPC64_GOT_TPREL16_HI", Const, 5},
+		{"R_PPC64_GOT_TPREL16_LO_DS", Const, 5},
+		{"R_PPC64_GOT_TPREL_PCREL34", Const, 20},
+		{"R_PPC64_IRELATIVE", Const, 10},
+		{"R_PPC64_JMP_IREL", Const, 10},
+		{"R_PPC64_JMP_SLOT", Const, 5},
+		{"R_PPC64_NONE", Const, 5},
+		{"R_PPC64_PCREL28", Const, 20},
+		{"R_PPC64_PCREL34", Const, 20},
+		{"R_PPC64_PCREL_OPT", Const, 20},
+		{"R_PPC64_PLT16_HA", Const, 20},
+		{"R_PPC64_PLT16_HI", Const, 20},
+		{"R_PPC64_PLT16_LO", Const, 20},
+		{"R_PPC64_PLT16_LO_DS", Const, 10},
+		{"R_PPC64_PLT32", Const, 20},
+		{"R_PPC64_PLT64", Const, 20},
+		{"R_PPC64_PLTCALL", Const, 20},
+		{"R_PPC64_PLTCALL_NOTOC", Const, 20},
+		{"R_PPC64_PLTGOT16", Const, 10},
+		{"R_PPC64_PLTGOT16_DS", Const, 10},
+		{"R_PPC64_PLTGOT16_HA", Const, 10},
+		{"R_PPC64_PLTGOT16_HI", Const, 10},
+		{"R_PPC64_PLTGOT16_LO", Const, 10},
+		{"R_PPC64_PLTGOT_LO_DS", Const, 10},
+		{"R_PPC64_PLTREL32", Const, 20},
+		{"R_PPC64_PLTREL64", Const, 20},
+		{"R_PPC64_PLTSEQ", Const, 20},
+		{"R_PPC64_PLTSEQ_NOTOC", Const, 20},
+		{"R_PPC64_PLT_PCREL34", Const, 20},
+		{"R_PPC64_PLT_PCREL34_NOTOC", Const, 20},
+		{"R_PPC64_REL14", Const, 5},
+		{"R_PPC64_REL14_BRNTAKEN", Const, 5},
+		{"R_PPC64_REL14_BRTAKEN", Const, 5},
+		{"R_PPC64_REL16", Const, 5},
+		{"R_PPC64_REL16DX_HA", Const, 10},
+		{"R_PPC64_REL16_HA", Const, 5},
+		{"R_PPC64_REL16_HI", Const, 5},
+		{"R_PPC64_REL16_HIGH", Const, 20},
+		{"R_PPC64_REL16_HIGHA", Const, 20},
+		{"R_PPC64_REL16_HIGHER", Const, 20},
+		{"R_PPC64_REL16_HIGHER34", Const, 20},
+		{"R_PPC64_REL16_HIGHERA", Const, 20},
+		{"R_PPC64_REL16_HIGHERA34", Const, 20},
+		{"R_PPC64_REL16_HIGHEST", Const, 20},
+		{"R_PPC64_REL16_HIGHEST34", Const, 20},
+		{"R_PPC64_REL16_HIGHESTA", Const, 20},
+		{"R_PPC64_REL16_HIGHESTA34", Const, 20},
+		{"R_PPC64_REL16_LO", Const, 5},
+		{"R_PPC64_REL24", Const, 5},
+		{"R_PPC64_REL24_NOTOC", Const, 10},
+		{"R_PPC64_REL24_P9NOTOC", Const, 21},
+		{"R_PPC64_REL30", Const, 20},
+		{"R_PPC64_REL32", Const, 5},
+		{"R_PPC64_REL64", Const, 5},
+		{"R_PPC64_RELATIVE", Const, 18},
+		{"R_PPC64_SECTOFF", Const, 20},
+		{"R_PPC64_SECTOFF_DS", Const, 10},
+		{"R_PPC64_SECTOFF_HA", Const, 20},
+		{"R_PPC64_SECTOFF_HI", Const, 20},
+		{"R_PPC64_SECTOFF_LO", Const, 20},
+		{"R_PPC64_SECTOFF_LO_DS", Const, 10},
+		{"R_PPC64_TLS", Const, 5},
+		{"R_PPC64_TLSGD", Const, 5},
+		{"R_PPC64_TLSLD", Const, 5},
+		{"R_PPC64_TOC", Const, 5},
+		{"R_PPC64_TOC16", Const, 5},
+		{"R_PPC64_TOC16_DS", Const, 5},
+		{"R_PPC64_TOC16_HA", Const, 5},
+		{"R_PPC64_TOC16_HI", Const, 5},
+		{"R_PPC64_TOC16_LO", Const, 5},
+		{"R_PPC64_TOC16_LO_DS", Const, 5},
+		{"R_PPC64_TOCSAVE", Const, 10},
+		{"R_PPC64_TPREL16", Const, 5},
+		{"R_PPC64_TPREL16_DS", Const, 5},
+		{"R_PPC64_TPREL16_HA", Const, 5},
+		{"R_PPC64_TPREL16_HI", Const, 5},
+		{"R_PPC64_TPREL16_HIGH", Const, 10},
+		{"R_PPC64_TPREL16_HIGHA", Const, 10},
+		{"R_PPC64_TPREL16_HIGHER", Const, 5},
+		{"R_PPC64_TPREL16_HIGHERA", Const, 5},
+		{"R_PPC64_TPREL16_HIGHEST", Const, 5},
+		{"R_PPC64_TPREL16_HIGHESTA", Const, 5},
+		{"R_PPC64_TPREL16_LO", Const, 5},
+		{"R_PPC64_TPREL16_LO_DS", Const, 5},
+		{"R_PPC64_TPREL34", Const, 20},
+		{"R_PPC64_TPREL64", Const, 5},
+		{"R_PPC64_UADDR16", Const, 20},
+		{"R_PPC64_UADDR32", Const, 20},
+		{"R_PPC64_UADDR64", Const, 20},
+		{"R_PPC_ADDR14", Const, 0},
+		{"R_PPC_ADDR14_BRNTAKEN", Const, 0},
+		{"R_PPC_ADDR14_BRTAKEN", Const, 0},
+		{"R_PPC_ADDR16", Const, 0},
+		{"R_PPC_ADDR16_HA", Const, 0},
+		{"R_PPC_ADDR16_HI", Const, 0},
+		{"R_PPC_ADDR16_LO", Const, 0},
+		{"R_PPC_ADDR24", Const, 0},
+		{"R_PPC_ADDR32", Const, 0},
+		{"R_PPC_COPY", Const, 0},
+		{"R_PPC_DTPMOD32", Const, 0},
+		{"R_PPC_DTPREL16", Const, 0},
+		{"R_PPC_DTPREL16_HA", Const, 0},
+		{"R_PPC_DTPREL16_HI", Const, 0},
+		{"R_PPC_DTPREL16_LO", Const, 0},
+		{"R_PPC_DTPREL32", Const, 0},
+		{"R_PPC_EMB_BIT_FLD", Const, 0},
+		{"R_PPC_EMB_MRKREF", Const, 0},
+		{"R_PPC_EMB_NADDR16", Const, 0},
+		{"R_PPC_EMB_NADDR16_HA", Const, 0},
+		{"R_PPC_EMB_NADDR16_HI", Const, 0},
+		{"R_PPC_EMB_NADDR16_LO", Const, 0},
+		{"R_PPC_EMB_NADDR32", Const, 0},
+		{"R_PPC_EMB_RELSDA", Const, 0},
+		{"R_PPC_EMB_RELSEC16", Const, 0},
+		{"R_PPC_EMB_RELST_HA", Const, 0},
+		{"R_PPC_EMB_RELST_HI", Const, 0},
+		{"R_PPC_EMB_RELST_LO", Const, 0},
+		{"R_PPC_EMB_SDA21", Const, 0},
+		{"R_PPC_EMB_SDA2I16", Const, 0},
+		{"R_PPC_EMB_SDA2REL", Const, 0},
+		{"R_PPC_EMB_SDAI16", Const, 0},
+		{"R_PPC_GLOB_DAT", Const, 0},
+		{"R_PPC_GOT16", Const, 0},
+		{"R_PPC_GOT16_HA", Const, 0},
+		{"R_PPC_GOT16_HI", Const, 0},
+		{"R_PPC_GOT16_LO", Const, 0},
+		{"R_PPC_GOT_TLSGD16", Const, 0},
+		{"R_PPC_GOT_TLSGD16_HA", Const, 0},
+		{"R_PPC_GOT_TLSGD16_HI", Const, 0},
+		{"R_PPC_GOT_TLSGD16_LO", Const, 0},
+		{"R_PPC_GOT_TLSLD16", Const, 0},
+		{"R_PPC_GOT_TLSLD16_HA", Const, 0},
+		{"R_PPC_GOT_TLSLD16_HI", Const, 0},
+		{"R_PPC_GOT_TLSLD16_LO", Const, 0},
+		{"R_PPC_GOT_TPREL16", Const, 0},
+		{"R_PPC_GOT_TPREL16_HA", Const, 0},
+		{"R_PPC_GOT_TPREL16_HI", Const, 0},
+		{"R_PPC_GOT_TPREL16_LO", Const, 0},
+		{"R_PPC_JMP_SLOT", Const, 0},
+		{"R_PPC_LOCAL24PC", Const, 0},
+		{"R_PPC_NONE", Const, 0},
+		{"R_PPC_PLT16_HA", Const, 0},
+		{"R_PPC_PLT16_HI", Const, 0},
+		{"R_PPC_PLT16_LO", Const, 0},
+		{"R_PPC_PLT32", Const, 0},
+		{"R_PPC_PLTREL24", Const, 0},
+		{"R_PPC_PLTREL32", Const, 0},
+		{"R_PPC_REL14", Const, 0},
+		{"R_PPC_REL14_BRNTAKEN", Const, 0},
+		{"R_PPC_REL14_BRTAKEN", Const, 0},
+		{"R_PPC_REL24", Const, 0},
+		{"R_PPC_REL32", Const, 0},
+		{"R_PPC_RELATIVE", Const, 0},
+		{"R_PPC_SDAREL16", Const, 0},
+		{"R_PPC_SECTOFF", Const, 0},
+		{"R_PPC_SECTOFF_HA", Const, 0},
+		{"R_PPC_SECTOFF_HI", Const, 0},
+		{"R_PPC_SECTOFF_LO", Const, 0},
+		{"R_PPC_TLS", Const, 0},
+		{"R_PPC_TPREL16", Const, 0},
+		{"R_PPC_TPREL16_HA", Const, 0},
+		{"R_PPC_TPREL16_HI", Const, 0},
+		{"R_PPC_TPREL16_LO", Const, 0},
+		{"R_PPC_TPREL32", Const, 0},
+		{"R_PPC_UADDR16", Const, 0},
+		{"R_PPC_UADDR32", Const, 0},
+		{"R_RISCV", Type, 11},
+		{"R_RISCV_32", Const, 11},
+		{"R_RISCV_32_PCREL", Const, 12},
+		{"R_RISCV_64", Const, 11},
+		{"R_RISCV_ADD16", Const, 11},
+		{"R_RISCV_ADD32", Const, 11},
+		{"R_RISCV_ADD64", Const, 11},
+		{"R_RISCV_ADD8", Const, 11},
+		{"R_RISCV_ALIGN", Const, 11},
+		{"R_RISCV_BRANCH", Const, 11},
+		{"R_RISCV_CALL", Const, 11},
+		{"R_RISCV_CALL_PLT", Const, 11},
+		{"R_RISCV_COPY", Const, 11},
+		{"R_RISCV_GNU_VTENTRY", Const, 11},
+		{"R_RISCV_GNU_VTINHERIT", Const, 11},
+		{"R_RISCV_GOT_HI20", Const, 11},
+		{"R_RISCV_GPREL_I", Const, 11},
+		{"R_RISCV_GPREL_S", Const, 11},
+		{"R_RISCV_HI20", Const, 11},
+		{"R_RISCV_JAL", Const, 11},
+		{"R_RISCV_JUMP_SLOT", Const, 11},
+		{"R_RISCV_LO12_I", Const, 11},
+		{"R_RISCV_LO12_S", Const, 11},
+		{"R_RISCV_NONE", Const, 11},
+		{"R_RISCV_PCREL_HI20", Const, 11},
+		{"R_RISCV_PCREL_LO12_I", Const, 11},
+		{"R_RISCV_PCREL_LO12_S", Const, 11},
+		{"R_RISCV_RELATIVE", Const, 11},
+		{"R_RISCV_RELAX", Const, 11},
+		{"R_RISCV_RVC_BRANCH", Const, 11},
+		{"R_RISCV_RVC_JUMP", Const, 11},
+		{"R_RISCV_RVC_LUI", Const, 11},
+		{"R_RISCV_SET16", Const, 11},
+		{"R_RISCV_SET32", Const, 11},
+		{"R_RISCV_SET6", Const, 11},
+		{"R_RISCV_SET8", Const, 11},
+		{"R_RISCV_SUB16", Const, 11},
+		{"R_RISCV_SUB32", Const, 11},
+		{"R_RISCV_SUB6", Const, 11},
+		{"R_RISCV_SUB64", Const, 11},
+		{"R_RISCV_SUB8", Const, 11},
+		{"R_RISCV_TLS_DTPMOD32", Const, 11},
+		{"R_RISCV_TLS_DTPMOD64", Const, 11},
+		{"R_RISCV_TLS_DTPREL32", Const, 11},
+		{"R_RISCV_TLS_DTPREL64", Const, 11},
+		{"R_RISCV_TLS_GD_HI20", Const, 11},
+		{"R_RISCV_TLS_GOT_HI20", Const, 11},
+		{"R_RISCV_TLS_TPREL32", Const, 11},
+		{"R_RISCV_TLS_TPREL64", Const, 11},
+		{"R_RISCV_TPREL_ADD", Const, 11},
+		{"R_RISCV_TPREL_HI20", Const, 11},
+		{"R_RISCV_TPREL_I", Const, 11},
+		{"R_RISCV_TPREL_LO12_I", Const, 11},
+		{"R_RISCV_TPREL_LO12_S", Const, 11},
+		{"R_RISCV_TPREL_S", Const, 11},
+		{"R_SPARC", Type, 0},
+		{"R_SPARC_10", Const, 0},
+		{"R_SPARC_11", Const, 0},
+		{"R_SPARC_13", Const, 0},
+		{"R_SPARC_16", Const, 0},
+		{"R_SPARC_22", Const, 0},
+		{"R_SPARC_32", Const, 0},
+		{"R_SPARC_5", Const, 0},
+		{"R_SPARC_6", Const, 0},
+		{"R_SPARC_64", Const, 0},
+		{"R_SPARC_7", Const, 0},
+		{"R_SPARC_8", Const, 0},
+		{"R_SPARC_COPY", Const, 0},
+		{"R_SPARC_DISP16", Const, 0},
+		{"R_SPARC_DISP32", Const, 0},
+		{"R_SPARC_DISP64", Const, 0},
+		{"R_SPARC_DISP8", Const, 0},
+		{"R_SPARC_GLOB_DAT", Const, 0},
+		{"R_SPARC_GLOB_JMP", Const, 0},
+		{"R_SPARC_GOT10", Const, 0},
+		{"R_SPARC_GOT13", Const, 0},
+		{"R_SPARC_GOT22", Const, 0},
+		{"R_SPARC_H44", Const, 0},
+		{"R_SPARC_HH22", Const, 0},
+		{"R_SPARC_HI22", Const, 0},
+		{"R_SPARC_HIPLT22", Const, 0},
+		{"R_SPARC_HIX22", Const, 0},
+		{"R_SPARC_HM10", Const, 0},
+		{"R_SPARC_JMP_SLOT", Const, 0},
+		{"R_SPARC_L44", Const, 0},
+		{"R_SPARC_LM22", Const, 0},
+		{"R_SPARC_LO10", Const, 0},
+		{"R_SPARC_LOPLT10", Const, 0},
+		{"R_SPARC_LOX10", Const, 0},
+		{"R_SPARC_M44", Const, 0},
+		{"R_SPARC_NONE", Const, 0},
+		{"R_SPARC_OLO10", Const, 0},
+		{"R_SPARC_PC10", Const, 0},
+		{"R_SPARC_PC22", Const, 0},
+		{"R_SPARC_PCPLT10", Const, 0},
+		{"R_SPARC_PCPLT22", Const, 0},
+		{"R_SPARC_PCPLT32", Const, 0},
+		{"R_SPARC_PC_HH22", Const, 0},
+		{"R_SPARC_PC_HM10", Const, 0},
+		{"R_SPARC_PC_LM22", Const, 0},
+		{"R_SPARC_PLT32", Const, 0},
+		{"R_SPARC_PLT64", Const, 0},
+		{"R_SPARC_REGISTER", Const, 0},
+		{"R_SPARC_RELATIVE", Const, 0},
+		{"R_SPARC_UA16", Const, 0},
+		{"R_SPARC_UA32", Const, 0},
+		{"R_SPARC_UA64", Const, 0},
+		{"R_SPARC_WDISP16", Const, 0},
+		{"R_SPARC_WDISP19", Const, 0},
+		{"R_SPARC_WDISP22", Const, 0},
+		{"R_SPARC_WDISP30", Const, 0},
+		{"R_SPARC_WPLT30", Const, 0},
+		{"R_SYM32", Func, 0},
+		{"R_SYM64", Func, 0},
+		{"R_TYPE32", Func, 0},
+		{"R_TYPE64", Func, 0},
+		{"R_X86_64", Type, 0},
+		{"R_X86_64_16", Const, 0},
+		{"R_X86_64_32", Const, 0},
+		{"R_X86_64_32S", Const, 0},
+		{"R_X86_64_64", Const, 0},
+		{"R_X86_64_8", Const, 0},
+		{"R_X86_64_COPY", Const, 0},
+		{"R_X86_64_DTPMOD64", Const, 0},
+		{"R_X86_64_DTPOFF32", Const, 0},
+		{"R_X86_64_DTPOFF64", Const, 0},
+		{"R_X86_64_GLOB_DAT", Const, 0},
+		{"R_X86_64_GOT32", Const, 0},
+		{"R_X86_64_GOT64", Const, 10},
+		{"R_X86_64_GOTOFF64", Const, 10},
+		{"R_X86_64_GOTPC32", Const, 10},
+		{"R_X86_64_GOTPC32_TLSDESC", Const, 10},
+		{"R_X86_64_GOTPC64", Const, 10},
+		{"R_X86_64_GOTPCREL", Const, 0},
+		{"R_X86_64_GOTPCREL64", Const, 10},
+		{"R_X86_64_GOTPCRELX", Const, 10},
+		{"R_X86_64_GOTPLT64", Const, 10},
+		{"R_X86_64_GOTTPOFF", Const, 0},
+		{"R_X86_64_IRELATIVE", Const, 10},
+		{"R_X86_64_JMP_SLOT", Const, 0},
+		{"R_X86_64_NONE", Const, 0},
+		{"R_X86_64_PC16", Const, 0},
+		{"R_X86_64_PC32", Const, 0},
+		{"R_X86_64_PC32_BND", Const, 10},
+		{"R_X86_64_PC64", Const, 10},
+		{"R_X86_64_PC8", Const, 0},
+		{"R_X86_64_PLT32", Const, 0},
+		{"R_X86_64_PLT32_BND", Const, 10},
+		{"R_X86_64_PLTOFF64", Const, 10},
+		{"R_X86_64_RELATIVE", Const, 0},
+		{"R_X86_64_RELATIVE64", Const, 10},
+		{"R_X86_64_REX_GOTPCRELX", Const, 10},
+		{"R_X86_64_SIZE32", Const, 10},
+		{"R_X86_64_SIZE64", Const, 10},
+		{"R_X86_64_TLSDESC", Const, 10},
+		{"R_X86_64_TLSDESC_CALL", Const, 10},
+		{"R_X86_64_TLSGD", Const, 0},
+		{"R_X86_64_TLSLD", Const, 0},
+		{"R_X86_64_TPOFF32", Const, 0},
+		{"R_X86_64_TPOFF64", Const, 0},
+		{"Rel32", Type, 0},
+		{"Rel32.Info", Field, 0},
+		{"Rel32.Off", Field, 0},
+		{"Rel64", Type, 0},
+		{"Rel64.Info", Field, 0},
+		{"Rel64.Off", Field, 0},
+		{"Rela32", Type, 0},
+		{"Rela32.Addend", Field, 0},
+		{"Rela32.Info", Field, 0},
+		{"Rela32.Off", Field, 0},
+		{"Rela64", Type, 0},
+		{"Rela64.Addend", Field, 0},
+		{"Rela64.Info", Field, 0},
+		{"Rela64.Off", Field, 0},
+		{"SHF_ALLOC", Const, 0},
+		{"SHF_COMPRESSED", Const, 6},
+		{"SHF_EXECINSTR", Const, 0},
+		{"SHF_GROUP", Const, 0},
+		{"SHF_INFO_LINK", Const, 0},
+		{"SHF_LINK_ORDER", Const, 0},
+		{"SHF_MASKOS", Const, 0},
+		{"SHF_MASKPROC", Const, 0},
+		{"SHF_MERGE", Const, 0},
+		{"SHF_OS_NONCONFORMING", Const, 0},
+		{"SHF_STRINGS", Const, 0},
+		{"SHF_TLS", Const, 0},
+		{"SHF_WRITE", Const, 0},
+		{"SHN_ABS", Const, 0},
+		{"SHN_COMMON", Const, 0},
+		{"SHN_HIOS", Const, 0},
+		{"SHN_HIPROC", Const, 0},
+		{"SHN_HIRESERVE", Const, 0},
+		{"SHN_LOOS", Const, 0},
+		{"SHN_LOPROC", Const, 0},
+		{"SHN_LORESERVE", Const, 0},
+		{"SHN_UNDEF", Const, 0},
+		{"SHN_XINDEX", Const, 0},
+		{"SHT_DYNAMIC", Const, 0},
+		{"SHT_DYNSYM", Const, 0},
+		{"SHT_FINI_ARRAY", Const, 0},
+		{"SHT_GNU_ATTRIBUTES", Const, 0},
+		{"SHT_GNU_HASH", Const, 0},
+		{"SHT_GNU_LIBLIST", Const, 0},
+		{"SHT_GNU_VERDEF", Const, 0},
+		{"SHT_GNU_VERNEED", Const, 0},
+		{"SHT_GNU_VERSYM", Const, 0},
+		{"SHT_GROUP", Const, 0},
+		{"SHT_HASH", Const, 0},
+		{"SHT_HIOS", Const, 0},
+		{"SHT_HIPROC", Const, 0},
+		{"SHT_HIUSER", Const, 0},
+		{"SHT_INIT_ARRAY", Const, 0},
+		{"SHT_LOOS", Const, 0},
+		{"SHT_LOPROC", Const, 0},
+		{"SHT_LOUSER", Const, 0},
+		{"SHT_MIPS_ABIFLAGS", Const, 17},
+		{"SHT_NOBITS", Const, 0},
+		{"SHT_NOTE", Const, 0},
+		{"SHT_NULL", Const, 0},
+		{"SHT_PREINIT_ARRAY", Const, 0},
+		{"SHT_PROGBITS", Const, 0},
+		{"SHT_REL", Const, 0},
+		{"SHT_RELA", Const, 0},
+		{"SHT_SHLIB", Const, 0},
+		{"SHT_STRTAB", Const, 0},
+		{"SHT_SYMTAB", Const, 0},
+		{"SHT_SYMTAB_SHNDX", Const, 0},
+		{"STB_GLOBAL", Const, 0},
+		{"STB_HIOS", Const, 0},
+		{"STB_HIPROC", Const, 0},
+		{"STB_LOCAL", Const, 0},
+		{"STB_LOOS", Const, 0},
+		{"STB_LOPROC", Const, 0},
+		{"STB_WEAK", Const, 0},
+		{"STT_COMMON", Const, 0},
+		{"STT_FILE", Const, 0},
+		{"STT_FUNC", Const, 0},
+		{"STT_GNU_IFUNC", Const, 23},
+		{"STT_HIOS", Const, 0},
+		{"STT_HIPROC", Const, 0},
+		{"STT_LOOS", Const, 0},
+		{"STT_LOPROC", Const, 0},
+		{"STT_NOTYPE", Const, 0},
+		{"STT_OBJECT", Const, 0},
+		{"STT_RELC", Const, 23},
+		{"STT_SECTION", Const, 0},
+		{"STT_SRELC", Const, 23},
+		{"STT_TLS", Const, 0},
+		{"STV_DEFAULT", Const, 0},
+		{"STV_HIDDEN", Const, 0},
+		{"STV_INTERNAL", Const, 0},
+		{"STV_PROTECTED", Const, 0},
+		{"ST_BIND", Func, 0},
+		{"ST_INFO", Func, 0},
+		{"ST_TYPE", Func, 0},
+		{"ST_VISIBILITY", Func, 0},
+		{"Section", Type, 0},
+		{"Section.ReaderAt", Field, 0},
+		{"Section.SectionHeader", Field, 0},
+		{"Section32", Type, 0},
+		{"Section32.Addr", Field, 0},
+		{"Section32.Addralign", Field, 0},
+		{"Section32.Entsize", Field, 0},
+		{"Section32.Flags", Field, 0},
+		{"Section32.Info", Field, 0},
+		{"Section32.Link", Field, 0},
+		{"Section32.Name", Field, 0},
+		{"Section32.Off", Field, 0},
+		{"Section32.Size", Field, 0},
+		{"Section32.Type", Field, 0},
+		{"Section64", Type, 0},
+		{"Section64.Addr", Field, 0},
+		{"Section64.Addralign", Field, 0},
+		{"Section64.Entsize", Field, 0},
+		{"Section64.Flags", Field, 0},
+		{"Section64.Info", Field, 0},
+		{"Section64.Link", Field, 0},
+		{"Section64.Name", Field, 0},
+		{"Section64.Off", Field, 0},
+		{"Section64.Size", Field, 0},
+		{"Section64.Type", Field, 0},
+		{"SectionFlag", Type, 0},
+		{"SectionHeader", Type, 0},
+		{"SectionHeader.Addr", Field, 0},
+		{"SectionHeader.Addralign", Field, 0},
+		{"SectionHeader.Entsize", Field, 0},
+		{"SectionHeader.FileSize", Field, 6},
+		{"SectionHeader.Flags", Field, 0},
+		{"SectionHeader.Info", Field, 0},
+		{"SectionHeader.Link", Field, 0},
+		{"SectionHeader.Name", Field, 0},
+		{"SectionHeader.Offset", Field, 0},
+		{"SectionHeader.Size", Field, 0},
+		{"SectionHeader.Type", Field, 0},
+		{"SectionIndex", Type, 0},
+		{"SectionType", Type, 0},
+		{"Sym32", Type, 0},
+		{"Sym32.Info", Field, 0},
+		{"Sym32.Name", Field, 0},
+		{"Sym32.Other", Field, 0},
+		{"Sym32.Shndx", Field, 0},
+		{"Sym32.Size", Field, 0},
+		{"Sym32.Value", Field, 0},
+		{"Sym32Size", Const, 0},
+		{"Sym64", Type, 0},
+		{"Sym64.Info", Field, 0},
+		{"Sym64.Name", Field, 0},
+		{"Sym64.Other", Field, 0},
+		{"Sym64.Shndx", Field, 0},
+		{"Sym64.Size", Field, 0},
+		{"Sym64.Value", Field, 0},
+		{"Sym64Size", Const, 0},
+		{"SymBind", Type, 0},
+		{"SymType", Type, 0},
+		{"SymVis", Type, 0},
+		{"Symbol", Type, 0},
+		{"Symbol.HasVersion", Field, 24},
+		{"Symbol.Info", Field, 0},
+		{"Symbol.Library", Field, 13},
+		{"Symbol.Name", Field, 0},
+		{"Symbol.Other", Field, 0},
+		{"Symbol.Section", Field, 0},
+		{"Symbol.Size", Field, 0},
+		{"Symbol.Value", Field, 0},
+		{"Symbol.Version", Field, 13},
+		{"Symbol.VersionIndex", Field, 24},
+		{"Type", Type, 0},
+		{"VER_FLG_BASE", Const, 24},
+		{"VER_FLG_INFO", Const, 24},
+		{"VER_FLG_WEAK", Const, 24},
+		{"Version", Type, 0},
+		{"VersionIndex", Type, 24},
+	},
+	"debug/gosym": {
+		{"(*DecodingError).Error", Method, 0},
+		{"(*LineTable).LineToPC", Method, 0},
+		{"(*LineTable).PCToLine", Method, 0},
+		{"(*Sym).BaseName", Method, 0},
+		{"(*Sym).PackageName", Method, 0},
+		{"(*Sym).ReceiverName", Method, 0},
+		{"(*Sym).Static", Method, 0},
+		{"(*Table).LineToPC", Method, 0},
+		{"(*Table).LookupFunc", Method, 0},
+		{"(*Table).LookupSym", Method, 0},
+		{"(*Table).PCToFunc", Method, 0},
+		{"(*Table).PCToLine", Method, 0},
+		{"(*Table).SymByAddr", Method, 0},
+		{"(*UnknownLineError).Error", Method, 0},
+		{"(Func).BaseName", Method, 0},
+		{"(Func).PackageName", Method, 0},
+		{"(Func).ReceiverName", Method, 0},
+		{"(Func).Static", Method, 0},
+		{"(UnknownFileError).Error", Method, 0},
+		{"DecodingError", Type, 0},
+		{"Func", Type, 0},
+		{"Func.End", Field, 0},
+		{"Func.Entry", Field, 0},
+		{"Func.FrameSize", Field, 0},
+		{"Func.LineTable", Field, 0},
+		{"Func.Locals", Field, 0},
+		{"Func.Obj", Field, 0},
+		{"Func.Params", Field, 0},
+		{"Func.Sym", Field, 0},
+		{"LineTable", Type, 0},
+		{"LineTable.Data", Field, 0},
+		{"LineTable.Line", Field, 0},
+		{"LineTable.PC", Field, 0},
+		{"NewLineTable", Func, 0},
+		{"NewTable", Func, 0},
+		{"Obj", Type, 0},
+		{"Obj.Funcs", Field, 0},
+		{"Obj.Paths", Field, 0},
+		{"Sym", Type, 0},
+		{"Sym.Func", Field, 0},
+		{"Sym.GoType", Field, 0},
+		{"Sym.Name", Field, 0},
+		{"Sym.Type", Field, 0},
+		{"Sym.Value", Field, 0},
+		{"Table", Type, 0},
+		{"Table.Files", Field, 0},
+		{"Table.Funcs", Field, 0},
+		{"Table.Objs", Field, 0},
+		{"Table.Syms", Field, 0},
+		{"UnknownFileError", Type, 0},
+		{"UnknownLineError", Type, 0},
+		{"UnknownLineError.File", Field, 0},
+		{"UnknownLineError.Line", Field, 0},
+	},
+	"debug/macho": {
+		{"(*FatFile).Close", Method, 3},
+		{"(*File).Close", Method, 0},
+		{"(*File).DWARF", Method, 0},
+		{"(*File).ImportedLibraries", Method, 0},
+		{"(*File).ImportedSymbols", Method, 0},
+		{"(*File).Section", Method, 0},
+		{"(*File).Segment", Method, 0},
+		{"(*FormatError).Error", Method, 0},
+		{"(*Section).Data", Method, 0},
+		{"(*Section).Open", Method, 0},
+		{"(*Segment).Data", Method, 0},
+		{"(*Segment).Open", Method, 0},
+		{"(Cpu).GoString", Method, 0},
+		{"(Cpu).String", Method, 0},
+		{"(Dylib).Raw", Method, 0},
+		{"(Dysymtab).Raw", Method, 0},
+		{"(FatArch).Close", Method, 3},
+		{"(FatArch).DWARF", Method, 3},
+		{"(FatArch).ImportedLibraries", Method, 3},
+		{"(FatArch).ImportedSymbols", Method, 3},
+		{"(FatArch).Section", Method, 3},
+		{"(FatArch).Segment", Method, 3},
+		{"(LoadBytes).Raw", Method, 0},
+		{"(LoadCmd).GoString", Method, 0},
+		{"(LoadCmd).String", Method, 0},
+		{"(RelocTypeARM).GoString", Method, 10},
+		{"(RelocTypeARM).String", Method, 10},
+		{"(RelocTypeARM64).GoString", Method, 10},
+		{"(RelocTypeARM64).String", Method, 10},
+		{"(RelocTypeGeneric).GoString", Method, 10},
+		{"(RelocTypeGeneric).String", Method, 10},
+		{"(RelocTypeX86_64).GoString", Method, 10},
+		{"(RelocTypeX86_64).String", Method, 10},
+		{"(Rpath).Raw", Method, 10},
+		{"(Section).ReadAt", Method, 0},
+		{"(Segment).Raw", Method, 0},
+		{"(Segment).ReadAt", Method, 0},
+		{"(Symtab).Raw", Method, 0},
+		{"(Type).GoString", Method, 10},
+		{"(Type).String", Method, 10},
+		{"ARM64_RELOC_ADDEND", Const, 10},
+		{"ARM64_RELOC_BRANCH26", Const, 10},
+		{"ARM64_RELOC_GOT_LOAD_PAGE21", Const, 10},
+		{"ARM64_RELOC_GOT_LOAD_PAGEOFF12", Const, 10},
+		{"ARM64_RELOC_PAGE21", Const, 10},
+		{"ARM64_RELOC_PAGEOFF12", Const, 10},
+		{"ARM64_RELOC_POINTER_TO_GOT", Const, 10},
+		{"ARM64_RELOC_SUBTRACTOR", Const, 10},
+		{"ARM64_RELOC_TLVP_LOAD_PAGE21", Const, 10},
+		{"ARM64_RELOC_TLVP_LOAD_PAGEOFF12", Const, 10},
+		{"ARM64_RELOC_UNSIGNED", Const, 10},
+		{"ARM_RELOC_BR24", Const, 10},
+		{"ARM_RELOC_HALF", Const, 10},
+		{"ARM_RELOC_HALF_SECTDIFF", Const, 10},
+		{"ARM_RELOC_LOCAL_SECTDIFF", Const, 10},
+		{"ARM_RELOC_PAIR", Const, 10},
+		{"ARM_RELOC_PB_LA_PTR", Const, 10},
+		{"ARM_RELOC_SECTDIFF", Const, 10},
+		{"ARM_RELOC_VANILLA", Const, 10},
+		{"ARM_THUMB_32BIT_BRANCH", Const, 10},
+		{"ARM_THUMB_RELOC_BR22", Const, 10},
+		{"Cpu", Type, 0},
+		{"Cpu386", Const, 0},
+		{"CpuAmd64", Const, 0},
+		{"CpuArm", Const, 3},
+		{"CpuArm64", Const, 11},
+		{"CpuPpc", Const, 3},
+		{"CpuPpc64", Const, 3},
+		{"Dylib", Type, 0},
+		{"Dylib.CompatVersion", Field, 0},
+		{"Dylib.CurrentVersion", Field, 0},
+		{"Dylib.LoadBytes", Field, 0},
+		{"Dylib.Name", Field, 0},
+		{"Dylib.Time", Field, 0},
+		{"DylibCmd", Type, 0},
+		{"DylibCmd.Cmd", Field, 0},
+		{"DylibCmd.CompatVersion", Field, 0},
+		{"DylibCmd.CurrentVersion", Field, 0},
+		{"DylibCmd.Len", Field, 0},
+		{"DylibCmd.Name", Field, 0},
+		{"DylibCmd.Time", Field, 0},
+		{"Dysymtab", Type, 0},
+		{"Dysymtab.DysymtabCmd", Field, 0},
+		{"Dysymtab.IndirectSyms", Field, 0},
+		{"Dysymtab.LoadBytes", Field, 0},
+		{"DysymtabCmd", Type, 0},
+		{"DysymtabCmd.Cmd", Field, 0},
+		{"DysymtabCmd.Extrefsymoff", Field, 0},
+		{"DysymtabCmd.Extreloff", Field, 0},
+		{"DysymtabCmd.Iextdefsym", Field, 0},
+		{"DysymtabCmd.Ilocalsym", Field, 0},
+		{"DysymtabCmd.Indirectsymoff", Field, 0},
+		{"DysymtabCmd.Iundefsym", Field, 0},
+		{"DysymtabCmd.Len", Field, 0},
+		{"DysymtabCmd.Locreloff", Field, 0},
+		{"DysymtabCmd.Modtaboff", Field, 0},
+		{"DysymtabCmd.Nextdefsym", Field, 0},
+		{"DysymtabCmd.Nextrefsyms", Field, 0},
+		{"DysymtabCmd.Nextrel", Field, 0},
+		{"DysymtabCmd.Nindirectsyms", Field, 0},
+		{"DysymtabCmd.Nlocalsym", Field, 0},
+		{"DysymtabCmd.Nlocrel", Field, 0},
+		{"DysymtabCmd.Nmodtab", Field, 0},
+		{"DysymtabCmd.Ntoc", Field, 0},
+		{"DysymtabCmd.Nundefsym", Field, 0},
+		{"DysymtabCmd.Tocoffset", Field, 0},
+		{"ErrNotFat", Var, 3},
+		{"FatArch", Type, 3},
+		{"FatArch.FatArchHeader", Field, 3},
+		{"FatArch.File", Field, 3},
+		{"FatArchHeader", Type, 3},
+		{"FatArchHeader.Align", Field, 3},
+		{"FatArchHeader.Cpu", Field, 3},
+		{"FatArchHeader.Offset", Field, 3},
+		{"FatArchHeader.Size", Field, 3},
+		{"FatArchHeader.SubCpu", Field, 3},
+		{"FatFile", Type, 3},
+		{"FatFile.Arches", Field, 3},
+		{"FatFile.Magic", Field, 3},
+		{"File", Type, 0},
+		{"File.ByteOrder", Field, 0},
+		{"File.Dysymtab", Field, 0},
+		{"File.FileHeader", Field, 0},
+		{"File.Loads", Field, 0},
+		{"File.Sections", Field, 0},
+		{"File.Symtab", Field, 0},
+		{"FileHeader", Type, 0},
+		{"FileHeader.Cmdsz", Field, 0},
+		{"FileHeader.Cpu", Field, 0},
+		{"FileHeader.Flags", Field, 0},
+		{"FileHeader.Magic", Field, 0},
+		{"FileHeader.Ncmd", Field, 0},
+		{"FileHeader.SubCpu", Field, 0},
+		{"FileHeader.Type", Field, 0},
+		{"FlagAllModsBound", Const, 10},
+		{"FlagAllowStackExecution", Const, 10},
+		{"FlagAppExtensionSafe", Const, 10},
+		{"FlagBindAtLoad", Const, 10},
+		{"FlagBindsToWeak", Const, 10},
+		{"FlagCanonical", Const, 10},
+		{"FlagDeadStrippableDylib", Const, 10},
+		{"FlagDyldLink", Const, 10},
+		{"FlagForceFlat", Const, 10},
+		{"FlagHasTLVDescriptors", Const, 10},
+		{"FlagIncrLink", Const, 10},
+		{"FlagLazyInit", Const, 10},
+		{"FlagNoFixPrebinding", Const, 10},
+		{"FlagNoHeapExecution", Const, 10},
+		{"FlagNoMultiDefs", Const, 10},
+		{"FlagNoReexportedDylibs", Const, 10},
+		{"FlagNoUndefs", Const, 10},
+		{"FlagPIE", Const, 10},
+		{"FlagPrebindable", Const, 10},
+		{"FlagPrebound", Const, 10},
+		{"FlagRootSafe", Const, 10},
+		{"FlagSetuidSafe", Const, 10},
+		{"FlagSplitSegs", Const, 10},
+		{"FlagSubsectionsViaSymbols", Const, 10},
+		{"FlagTwoLevel", Const, 10},
+		{"FlagWeakDefines", Const, 10},
+		{"FormatError", Type, 0},
+		{"GENERIC_RELOC_LOCAL_SECTDIFF", Const, 10},
+		{"GENERIC_RELOC_PAIR", Const, 10},
+		{"GENERIC_RELOC_PB_LA_PTR", Const, 10},
+		{"GENERIC_RELOC_SECTDIFF", Const, 10},
+		{"GENERIC_RELOC_TLV", Const, 10},
+		{"GENERIC_RELOC_VANILLA", Const, 10},
+		{"Load", Type, 0},
+		{"LoadBytes", Type, 0},
+		{"LoadCmd", Type, 0},
+		{"LoadCmdDylib", Const, 0},
+		{"LoadCmdDylinker", Const, 0},
+		{"LoadCmdDysymtab", Const, 0},
+		{"LoadCmdRpath", Const, 10},
+		{"LoadCmdSegment", Const, 0},
+		{"LoadCmdSegment64", Const, 0},
+		{"LoadCmdSymtab", Const, 0},
+		{"LoadCmdThread", Const, 0},
+		{"LoadCmdUnixThread", Const, 0},
+		{"Magic32", Const, 0},
+		{"Magic64", Const, 0},
+		{"MagicFat", Const, 3},
+		{"NewFatFile", Func, 3},
+		{"NewFile", Func, 0},
+		{"Nlist32", Type, 0},
+		{"Nlist32.Desc", Field, 0},
+		{"Nlist32.Name", Field, 0},
+		{"Nlist32.Sect", Field, 0},
+		{"Nlist32.Type", Field, 0},
+		{"Nlist32.Value", Field, 0},
+		{"Nlist64", Type, 0},
+		{"Nlist64.Desc", Field, 0},
+		{"Nlist64.Name", Field, 0},
+		{"Nlist64.Sect", Field, 0},
+		{"Nlist64.Type", Field, 0},
+		{"Nlist64.Value", Field, 0},
+		{"Open", Func, 0},
+		{"OpenFat", Func, 3},
+		{"Regs386", Type, 0},
+		{"Regs386.AX", Field, 0},
+		{"Regs386.BP", Field, 0},
+		{"Regs386.BX", Field, 0},
+		{"Regs386.CS", Field, 0},
+		{"Regs386.CX", Field, 0},
+		{"Regs386.DI", Field, 0},
+		{"Regs386.DS", Field, 0},
+		{"Regs386.DX", Field, 0},
+		{"Regs386.ES", Field, 0},
+		{"Regs386.FLAGS", Field, 0},
+		{"Regs386.FS", Field, 0},
+		{"Regs386.GS", Field, 0},
+		{"Regs386.IP", Field, 0},
+		{"Regs386.SI", Field, 0},
+		{"Regs386.SP", Field, 0},
+		{"Regs386.SS", Field, 0},
+		{"RegsAMD64", Type, 0},
+		{"RegsAMD64.AX", Field, 0},
+		{"RegsAMD64.BP", Field, 0},
+		{"RegsAMD64.BX", Field, 0},
+		{"RegsAMD64.CS", Field, 0},
+		{"RegsAMD64.CX", Field, 0},
+		{"RegsAMD64.DI", Field, 0},
+		{"RegsAMD64.DX", Field, 0},
+		{"RegsAMD64.FLAGS", Field, 0},
+		{"RegsAMD64.FS", Field, 0},
+		{"RegsAMD64.GS", Field, 0},
+		{"RegsAMD64.IP", Field, 0},
+		{"RegsAMD64.R10", Field, 0},
+		{"RegsAMD64.R11", Field, 0},
+		{"RegsAMD64.R12", Field, 0},
+		{"RegsAMD64.R13", Field, 0},
+		{"RegsAMD64.R14", Field, 0},
+		{"RegsAMD64.R15", Field, 0},
+		{"RegsAMD64.R8", Field, 0},
+		{"RegsAMD64.R9", Field, 0},
+		{"RegsAMD64.SI", Field, 0},
+		{"RegsAMD64.SP", Field, 0},
+		{"Reloc", Type, 10},
+		{"Reloc.Addr", Field, 10},
+		{"Reloc.Extern", Field, 10},
+		{"Reloc.Len", Field, 10},
+		{"Reloc.Pcrel", Field, 10},
+		{"Reloc.Scattered", Field, 10},
+		{"Reloc.Type", Field, 10},
+		{"Reloc.Value", Field, 10},
+		{"RelocTypeARM", Type, 10},
+		{"RelocTypeARM64", Type, 10},
+		{"RelocTypeGeneric", Type, 10},
+		{"RelocTypeX86_64", Type, 10},
+		{"Rpath", Type, 10},
+		{"Rpath.LoadBytes", Field, 10},
+		{"Rpath.Path", Field, 10},
+		{"RpathCmd", Type, 10},
+		{"RpathCmd.Cmd", Field, 10},
+		{"RpathCmd.Len", Field, 10},
+		{"RpathCmd.Path", Field, 10},
+		{"Section", Type, 0},
+		{"Section.ReaderAt", Field, 0},
+		{"Section.Relocs", Field, 10},
+		{"Section.SectionHeader", Field, 0},
+		{"Section32", Type, 0},
+		{"Section32.Addr", Field, 0},
+		{"Section32.Align", Field, 0},
+		{"Section32.Flags", Field, 0},
+		{"Section32.Name", Field, 0},
+		{"Section32.Nreloc", Field, 0},
+		{"Section32.Offset", Field, 0},
+		{"Section32.Reloff", Field, 0},
+		{"Section32.Reserve1", Field, 0},
+		{"Section32.Reserve2", Field, 0},
+		{"Section32.Seg", Field, 0},
+		{"Section32.Size", Field, 0},
+		{"Section64", Type, 0},
+		{"Section64.Addr", Field, 0},
+		{"Section64.Align", Field, 0},
+		{"Section64.Flags", Field, 0},
+		{"Section64.Name", Field, 0},
+		{"Section64.Nreloc", Field, 0},
+		{"Section64.Offset", Field, 0},
+		{"Section64.Reloff", Field, 0},
+		{"Section64.Reserve1", Field, 0},
+		{"Section64.Reserve2", Field, 0},
+		{"Section64.Reserve3", Field, 0},
+		{"Section64.Seg", Field, 0},
+		{"Section64.Size", Field, 0},
+		{"SectionHeader", Type, 0},
+		{"SectionHeader.Addr", Field, 0},
+		{"SectionHeader.Align", Field, 0},
+		{"SectionHeader.Flags", Field, 0},
+		{"SectionHeader.Name", Field, 0},
+		{"SectionHeader.Nreloc", Field, 0},
+		{"SectionHeader.Offset", Field, 0},
+		{"SectionHeader.Reloff", Field, 0},
+		{"SectionHeader.Seg", Field, 0},
+		{"SectionHeader.Size", Field, 0},
+		{"Segment", Type, 0},
+		{"Segment.LoadBytes", Field, 0},
+		{"Segment.ReaderAt", Field, 0},
+		{"Segment.SegmentHeader", Field, 0},
+		{"Segment32", Type, 0},
+		{"Segment32.Addr", Field, 0},
+		{"Segment32.Cmd", Field, 0},
+		{"Segment32.Filesz", Field, 0},
+		{"Segment32.Flag", Field, 0},
+		{"Segment32.Len", Field, 0},
+		{"Segment32.Maxprot", Field, 0},
+		{"Segment32.Memsz", Field, 0},
+		{"Segment32.Name", Field, 0},
+		{"Segment32.Nsect", Field, 0},
+		{"Segment32.Offset", Field, 0},
+		{"Segment32.Prot", Field, 0},
+		{"Segment64", Type, 0},
+		{"Segment64.Addr", Field, 0},
+		{"Segment64.Cmd", Field, 0},
+		{"Segment64.Filesz", Field, 0},
+		{"Segment64.Flag", Field, 0},
+		{"Segment64.Len", Field, 0},
+		{"Segment64.Maxprot", Field, 0},
+		{"Segment64.Memsz", Field, 0},
+		{"Segment64.Name", Field, 0},
+		{"Segment64.Nsect", Field, 0},
+		{"Segment64.Offset", Field, 0},
+		{"Segment64.Prot", Field, 0},
+		{"SegmentHeader", Type, 0},
+		{"SegmentHeader.Addr", Field, 0},
+		{"SegmentHeader.Cmd", Field, 0},
+		{"SegmentHeader.Filesz", Field, 0},
+		{"SegmentHeader.Flag", Field, 0},
+		{"SegmentHeader.Len", Field, 0},
+		{"SegmentHeader.Maxprot", Field, 0},
+		{"SegmentHeader.Memsz", Field, 0},
+		{"SegmentHeader.Name", Field, 0},
+		{"SegmentHeader.Nsect", Field, 0},
+		{"SegmentHeader.Offset", Field, 0},
+		{"SegmentHeader.Prot", Field, 0},
+		{"Symbol", Type, 0},
+		{"Symbol.Desc", Field, 0},
+		{"Symbol.Name", Field, 0},
+		{"Symbol.Sect", Field, 0},
+		{"Symbol.Type", Field, 0},
+		{"Symbol.Value", Field, 0},
+		{"Symtab", Type, 0},
+		{"Symtab.LoadBytes", Field, 0},
+		{"Symtab.Syms", Field, 0},
+		{"Symtab.SymtabCmd", Field, 0},
+		{"SymtabCmd", Type, 0},
+		{"SymtabCmd.Cmd", Field, 0},
+		{"SymtabCmd.Len", Field, 0},
+		{"SymtabCmd.Nsyms", Field, 0},
+		{"SymtabCmd.Stroff", Field, 0},
+		{"SymtabCmd.Strsize", Field, 0},
+		{"SymtabCmd.Symoff", Field, 0},
+		{"Thread", Type, 0},
+		{"Thread.Cmd", Field, 0},
+		{"Thread.Data", Field, 0},
+		{"Thread.Len", Field, 0},
+		{"Thread.Type", Field, 0},
+		{"Type", Type, 0},
+		{"TypeBundle", Const, 3},
+		{"TypeDylib", Const, 3},
+		{"TypeExec", Const, 0},
+		{"TypeObj", Const, 0},
+		{"X86_64_RELOC_BRANCH", Const, 10},
+		{"X86_64_RELOC_GOT", Const, 10},
+		{"X86_64_RELOC_GOT_LOAD", Const, 10},
+		{"X86_64_RELOC_SIGNED", Const, 10},
+		{"X86_64_RELOC_SIGNED_1", Const, 10},
+		{"X86_64_RELOC_SIGNED_2", Const, 10},
+		{"X86_64_RELOC_SIGNED_4", Const, 10},
+		{"X86_64_RELOC_SUBTRACTOR", Const, 10},
+		{"X86_64_RELOC_TLV", Const, 10},
+		{"X86_64_RELOC_UNSIGNED", Const, 10},
+	},
+	"debug/pe": {
+		{"(*COFFSymbol).FullName", Method, 8},
+		{"(*File).COFFSymbolReadSectionDefAux", Method, 19},
+		{"(*File).Close", Method, 0},
+		{"(*File).DWARF", Method, 0},
+		{"(*File).ImportedLibraries", Method, 0},
+		{"(*File).ImportedSymbols", Method, 0},
+		{"(*File).Section", Method, 0},
+		{"(*FormatError).Error", Method, 0},
+		{"(*Section).Data", Method, 0},
+		{"(*Section).Open", Method, 0},
+		{"(Section).ReadAt", Method, 0},
+		{"(StringTable).String", Method, 8},
+		{"COFFSymbol", Type, 1},
+		{"COFFSymbol.Name", Field, 1},
+		{"COFFSymbol.NumberOfAuxSymbols", Field, 1},
+		{"COFFSymbol.SectionNumber", Field, 1},
+		{"COFFSymbol.StorageClass", Field, 1},
+		{"COFFSymbol.Type", Field, 1},
+		{"COFFSymbol.Value", Field, 1},
+		{"COFFSymbolAuxFormat5", Type, 19},
+		{"COFFSymbolAuxFormat5.Checksum", Field, 19},
+		{"COFFSymbolAuxFormat5.NumLineNumbers", Field, 19},
+		{"COFFSymbolAuxFormat5.NumRelocs", Field, 19},
+		{"COFFSymbolAuxFormat5.SecNum", Field, 19},
+		{"COFFSymbolAuxFormat5.Selection", Field, 19},
+		{"COFFSymbolAuxFormat5.Size", Field, 19},
+		{"COFFSymbolSize", Const, 1},
+		{"DataDirectory", Type, 3},
+		{"DataDirectory.Size", Field, 3},
+		{"DataDirectory.VirtualAddress", Field, 3},
+		{"File", Type, 0},
+		{"File.COFFSymbols", Field, 8},
+		{"File.FileHeader", Field, 0},
+		{"File.OptionalHeader", Field, 3},
+		{"File.Sections", Field, 0},
+		{"File.StringTable", Field, 8},
+		{"File.Symbols", Field, 1},
+		{"FileHeader", Type, 0},
+		{"FileHeader.Characteristics", Field, 0},
+		{"FileHeader.Machine", Field, 0},
+		{"FileHeader.NumberOfSections", Field, 0},
+		{"FileHeader.NumberOfSymbols", Field, 0},
+		{"FileHeader.PointerToSymbolTable", Field, 0},
+		{"FileHeader.SizeOfOptionalHeader", Field, 0},
+		{"FileHeader.TimeDateStamp", Field, 0},
+		{"FormatError", Type, 0},
+		{"IMAGE_COMDAT_SELECT_ANY", Const, 19},
+		{"IMAGE_COMDAT_SELECT_ASSOCIATIVE", Const, 19},
+		{"IMAGE_COMDAT_SELECT_EXACT_MATCH", Const, 19},
+		{"IMAGE_COMDAT_SELECT_LARGEST", Const, 19},
+		{"IMAGE_COMDAT_SELECT_NODUPLICATES", Const, 19},
+		{"IMAGE_COMDAT_SELECT_SAME_SIZE", Const, 19},
+		{"IMAGE_DIRECTORY_ENTRY_ARCHITECTURE", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_BASERELOC", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_DEBUG", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_EXCEPTION", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_EXPORT", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_GLOBALPTR", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_IAT", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_IMPORT", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_RESOURCE", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_SECURITY", Const, 11},
+		{"IMAGE_DIRECTORY_ENTRY_TLS", Const, 11},
+		{"IMAGE_DLLCHARACTERISTICS_APPCONTAINER", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_GUARD_CF", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_NO_BIND", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_NO_ISOLATION", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_NO_SEH", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_NX_COMPAT", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE", Const, 15},
+		{"IMAGE_DLLCHARACTERISTICS_WDM_DRIVER", Const, 15},
+		{"IMAGE_FILE_32BIT_MACHINE", Const, 15},
+		{"IMAGE_FILE_AGGRESIVE_WS_TRIM", Const, 15},
+		{"IMAGE_FILE_BYTES_REVERSED_HI", Const, 15},
+		{"IMAGE_FILE_BYTES_REVERSED_LO", Const, 15},
+		{"IMAGE_FILE_DEBUG_STRIPPED", Const, 15},
+		{"IMAGE_FILE_DLL", Const, 15},
+		{"IMAGE_FILE_EXECUTABLE_IMAGE", Const, 15},
+		{"IMAGE_FILE_LARGE_ADDRESS_AWARE", Const, 15},
+		{"IMAGE_FILE_LINE_NUMS_STRIPPED", Const, 15},
+		{"IMAGE_FILE_LOCAL_SYMS_STRIPPED", Const, 15},
+		{"IMAGE_FILE_MACHINE_AM33", Const, 0},
+		{"IMAGE_FILE_MACHINE_AMD64", Const, 0},
+		{"IMAGE_FILE_MACHINE_ARM", Const, 0},
+		{"IMAGE_FILE_MACHINE_ARM64", Const, 11},
+		{"IMAGE_FILE_MACHINE_ARMNT", Const, 12},
+		{"IMAGE_FILE_MACHINE_EBC", Const, 0},
+		{"IMAGE_FILE_MACHINE_I386", Const, 0},
+		{"IMAGE_FILE_MACHINE_IA64", Const, 0},
+		{"IMAGE_FILE_MACHINE_LOONGARCH32", Const, 19},
+		{"IMAGE_FILE_MACHINE_LOONGARCH64", Const, 19},
+		{"IMAGE_FILE_MACHINE_M32R", Const, 0},
+		{"IMAGE_FILE_MACHINE_MIPS16", Const, 0},
+		{"IMAGE_FILE_MACHINE_MIPSFPU", Const, 0},
+		{"IMAGE_FILE_MACHINE_MIPSFPU16", Const, 0},
+		{"IMAGE_FILE_MACHINE_POWERPC", Const, 0},
+		{"IMAGE_FILE_MACHINE_POWERPCFP", Const, 0},
+		{"IMAGE_FILE_MACHINE_R4000", Const, 0},
+		{"IMAGE_FILE_MACHINE_RISCV128", Const, 20},
+		{"IMAGE_FILE_MACHINE_RISCV32", Const, 20},
+		{"IMAGE_FILE_MACHINE_RISCV64", Const, 20},
+		{"IMAGE_FILE_MACHINE_SH3", Const, 0},
+		{"IMAGE_FILE_MACHINE_SH3DSP", Const, 0},
+		{"IMAGE_FILE_MACHINE_SH4", Const, 0},
+		{"IMAGE_FILE_MACHINE_SH5", Const, 0},
+		{"IMAGE_FILE_MACHINE_THUMB", Const, 0},
+		{"IMAGE_FILE_MACHINE_UNKNOWN", Const, 0},
+		{"IMAGE_FILE_MACHINE_WCEMIPSV2", Const, 0},
+		{"IMAGE_FILE_NET_RUN_FROM_SWAP", Const, 15},
+		{"IMAGE_FILE_RELOCS_STRIPPED", Const, 15},
+		{"IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP", Const, 15},
+		{"IMAGE_FILE_SYSTEM", Const, 15},
+		{"IMAGE_FILE_UP_SYSTEM_ONLY", Const, 15},
+		{"IMAGE_SCN_CNT_CODE", Const, 19},
+		{"IMAGE_SCN_CNT_INITIALIZED_DATA", Const, 19},
+		{"IMAGE_SCN_CNT_UNINITIALIZED_DATA", Const, 19},
+		{"IMAGE_SCN_LNK_COMDAT", Const, 19},
+		{"IMAGE_SCN_MEM_DISCARDABLE", Const, 19},
+		{"IMAGE_SCN_MEM_EXECUTE", Const, 19},
+		{"IMAGE_SCN_MEM_READ", Const, 19},
+		{"IMAGE_SCN_MEM_WRITE", Const, 19},
+		{"IMAGE_SUBSYSTEM_EFI_APPLICATION", Const, 15},
+		{"IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER", Const, 15},
+		{"IMAGE_SUBSYSTEM_EFI_ROM", Const, 15},
+		{"IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER", Const, 15},
+		{"IMAGE_SUBSYSTEM_NATIVE", Const, 15},
+		{"IMAGE_SUBSYSTEM_NATIVE_WINDOWS", Const, 15},
+		{"IMAGE_SUBSYSTEM_OS2_CUI", Const, 15},
+		{"IMAGE_SUBSYSTEM_POSIX_CUI", Const, 15},
+		{"IMAGE_SUBSYSTEM_UNKNOWN", Const, 15},
+		{"IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION", Const, 15},
+		{"IMAGE_SUBSYSTEM_WINDOWS_CE_GUI", Const, 15},
+		{"IMAGE_SUBSYSTEM_WINDOWS_CUI", Const, 15},
+		{"IMAGE_SUBSYSTEM_WINDOWS_GUI", Const, 15},
+		{"IMAGE_SUBSYSTEM_XBOX", Const, 15},
+		{"ImportDirectory", Type, 0},
+		{"ImportDirectory.FirstThunk", Field, 0},
+		{"ImportDirectory.ForwarderChain", Field, 0},
+		{"ImportDirectory.Name", Field, 0},
+		{"ImportDirectory.OriginalFirstThunk", Field, 0},
+		{"ImportDirectory.TimeDateStamp", Field, 0},
+		{"NewFile", Func, 0},
+		{"Open", Func, 0},
+		{"OptionalHeader32", Type, 3},
+		{"OptionalHeader32.AddressOfEntryPoint", Field, 3},
+		{"OptionalHeader32.BaseOfCode", Field, 3},
+		{"OptionalHeader32.BaseOfData", Field, 3},
+		{"OptionalHeader32.CheckSum", Field, 3},
+		{"OptionalHeader32.DataDirectory", Field, 3},
+		{"OptionalHeader32.DllCharacteristics", Field, 3},
+		{"OptionalHeader32.FileAlignment", Field, 3},
+		{"OptionalHeader32.ImageBase", Field, 3},
+		{"OptionalHeader32.LoaderFlags", Field, 3},
+		{"OptionalHeader32.Magic", Field, 3},
+		{"OptionalHeader32.MajorImageVersion", Field, 3},
+		{"OptionalHeader32.MajorLinkerVersion", Field, 3},
+		{"OptionalHeader32.MajorOperatingSystemVersion", Field, 3},
+		{"OptionalHeader32.MajorSubsystemVersion", Field, 3},
+		{"OptionalHeader32.MinorImageVersion", Field, 3},
+		{"OptionalHeader32.MinorLinkerVersion", Field, 3},
+		{"OptionalHeader32.MinorOperatingSystemVersion", Field, 3},
+		{"OptionalHeader32.MinorSubsystemVersion", Field, 3},
+		{"OptionalHeader32.NumberOfRvaAndSizes", Field, 3},
+		{"OptionalHeader32.SectionAlignment", Field, 3},
+		{"OptionalHeader32.SizeOfCode", Field, 3},
+		{"OptionalHeader32.SizeOfHeaders", Field, 3},
+		{"OptionalHeader32.SizeOfHeapCommit", Field, 3},
+		{"OptionalHeader32.SizeOfHeapReserve", Field, 3},
+		{"OptionalHeader32.SizeOfImage", Field, 3},
+		{"OptionalHeader32.SizeOfInitializedData", Field, 3},
+		{"OptionalHeader32.SizeOfStackCommit", Field, 3},
+		{"OptionalHeader32.SizeOfStackReserve", Field, 3},
+		{"OptionalHeader32.SizeOfUninitializedData", Field, 3},
+		{"OptionalHeader32.Subsystem", Field, 3},
+		{"OptionalHeader32.Win32VersionValue", Field, 3},
+		{"OptionalHeader64", Type, 3},
+		{"OptionalHeader64.AddressOfEntryPoint", Field, 3},
+		{"OptionalHeader64.BaseOfCode", Field, 3},
+		{"OptionalHeader64.CheckSum", Field, 3},
+		{"OptionalHeader64.DataDirectory", Field, 3},
+		{"OptionalHeader64.DllCharacteristics", Field, 3},
+		{"OptionalHeader64.FileAlignment", Field, 3},
+		{"OptionalHeader64.ImageBase", Field, 3},
+		{"OptionalHeader64.LoaderFlags", Field, 3},
+		{"OptionalHeader64.Magic", Field, 3},
+		{"OptionalHeader64.MajorImageVersion", Field, 3},
+		{"OptionalHeader64.MajorLinkerVersion", Field, 3},
+		{"OptionalHeader64.MajorOperatingSystemVersion", Field, 3},
+		{"OptionalHeader64.MajorSubsystemVersion", Field, 3},
+		{"OptionalHeader64.MinorImageVersion", Field, 3},
+		{"OptionalHeader64.MinorLinkerVersion", Field, 3},
+		{"OptionalHeader64.MinorOperatingSystemVersion", Field, 3},
+		{"OptionalHeader64.MinorSubsystemVersion", Field, 3},
+		{"OptionalHeader64.NumberOfRvaAndSizes", Field, 3},
+		{"OptionalHeader64.SectionAlignment", Field, 3},
+		{"OptionalHeader64.SizeOfCode", Field, 3},
+		{"OptionalHeader64.SizeOfHeaders", Field, 3},
+		{"OptionalHeader64.SizeOfHeapCommit", Field, 3},
+		{"OptionalHeader64.SizeOfHeapReserve", Field, 3},
+		{"OptionalHeader64.SizeOfImage", Field, 3},
+		{"OptionalHeader64.SizeOfInitializedData", Field, 3},
+		{"OptionalHeader64.SizeOfStackCommit", Field, 3},
+		{"OptionalHeader64.SizeOfStackReserve", Field, 3},
+		{"OptionalHeader64.SizeOfUninitializedData", Field, 3},
+		{"OptionalHeader64.Subsystem", Field, 3},
+		{"OptionalHeader64.Win32VersionValue", Field, 3},
+		{"Reloc", Type, 8},
+		{"Reloc.SymbolTableIndex", Field, 8},
+		{"Reloc.Type", Field, 8},
+		{"Reloc.VirtualAddress", Field, 8},
+		{"Section", Type, 0},
+		{"Section.ReaderAt", Field, 0},
+		{"Section.Relocs", Field, 8},
+		{"Section.SectionHeader", Field, 0},
+		{"SectionHeader", Type, 0},
+		{"SectionHeader.Characteristics", Field, 0},
+		{"SectionHeader.Name", Field, 0},
+		{"SectionHeader.NumberOfLineNumbers", Field, 0},
+		{"SectionHeader.NumberOfRelocations", Field, 0},
+		{"SectionHeader.Offset", Field, 0},
+		{"SectionHeader.PointerToLineNumbers", Field, 0},
+		{"SectionHeader.PointerToRelocations", Field, 0},
+		{"SectionHeader.Size", Field, 0},
+		{"SectionHeader.VirtualAddress", Field, 0},
+		{"SectionHeader.VirtualSize", Field, 0},
+		{"SectionHeader32", Type, 0},
+		{"SectionHeader32.Characteristics", Field, 0},
+		{"SectionHeader32.Name", Field, 0},
+		{"SectionHeader32.NumberOfLineNumbers", Field, 0},
+		{"SectionHeader32.NumberOfRelocations", Field, 0},
+		{"SectionHeader32.PointerToLineNumbers", Field, 0},
+		{"SectionHeader32.PointerToRawData", Field, 0},
+		{"SectionHeader32.PointerToRelocations", Field, 0},
+		{"SectionHeader32.SizeOfRawData", Field, 0},
+		{"SectionHeader32.VirtualAddress", Field, 0},
+		{"SectionHeader32.VirtualSize", Field, 0},
+		{"StringTable", Type, 8},
+		{"Symbol", Type, 1},
+		{"Symbol.Name", Field, 1},
+		{"Symbol.SectionNumber", Field, 1},
+		{"Symbol.StorageClass", Field, 1},
+		{"Symbol.Type", Field, 1},
+		{"Symbol.Value", Field, 1},
+	},
+	"debug/plan9obj": {
+		{"(*File).Close", Method, 3},
+		{"(*File).Section", Method, 3},
+		{"(*File).Symbols", Method, 3},
+		{"(*Section).Data", Method, 3},
+		{"(*Section).Open", Method, 3},
+		{"(Section).ReadAt", Method, 3},
+		{"ErrNoSymbols", Var, 18},
+		{"File", Type, 3},
+		{"File.FileHeader", Field, 3},
+		{"File.Sections", Field, 3},
+		{"FileHeader", Type, 3},
+		{"FileHeader.Bss", Field, 3},
+		{"FileHeader.Entry", Field, 3},
+		{"FileHeader.HdrSize", Field, 4},
+		{"FileHeader.LoadAddress", Field, 4},
+		{"FileHeader.Magic", Field, 3},
+		{"FileHeader.PtrSize", Field, 3},
+		{"Magic386", Const, 3},
+		{"Magic64", Const, 3},
+		{"MagicAMD64", Const, 3},
+		{"MagicARM", Const, 3},
+		{"NewFile", Func, 3},
+		{"Open", Func, 3},
+		{"Section", Type, 3},
+		{"Section.ReaderAt", Field, 3},
+		{"Section.SectionHeader", Field, 3},
+		{"SectionHeader", Type, 3},
+		{"SectionHeader.Name", Field, 3},
+		{"SectionHeader.Offset", Field, 3},
+		{"SectionHeader.Size", Field, 3},
+		{"Sym", Type, 3},
+		{"Sym.Name", Field, 3},
+		{"Sym.Type", Field, 3},
+		{"Sym.Value", Field, 3},
+	},
+	"embed": {
+		{"(FS).Open", Method, 16},
+		{"(FS).ReadDir", Method, 16},
+		{"(FS).ReadFile", Method, 16},
+		{"FS", Type, 16},
+	},
+	"encoding": {
+		{"BinaryAppender", Type, 24},
+		{"BinaryMarshaler", Type, 2},
+		{"BinaryUnmarshaler", Type, 2},
+		{"TextAppender", Type, 24},
+		{"TextMarshaler", Type, 2},
+		{"TextUnmarshaler", Type, 2},
+	},
+	"encoding/ascii85": {
+		{"(CorruptInputError).Error", Method, 0},
+		{"CorruptInputError", Type, 0},
+		{"Decode", Func, 0},
+		{"Encode", Func, 0},
+		{"MaxEncodedLen", Func, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+	},
+	"encoding/asn1": {
+		{"(BitString).At", Method, 0},
+		{"(BitString).RightAlign", Method, 0},
+		{"(ObjectIdentifier).Equal", Method, 0},
+		{"(ObjectIdentifier).String", Method, 3},
+		{"(StructuralError).Error", Method, 0},
+		{"(SyntaxError).Error", Method, 0},
+		{"BitString", Type, 0},
+		{"BitString.BitLength", Field, 0},
+		{"BitString.Bytes", Field, 0},
+		{"ClassApplication", Const, 6},
+		{"ClassContextSpecific", Const, 6},
+		{"ClassPrivate", Const, 6},
+		{"ClassUniversal", Const, 6},
+		{"Enumerated", Type, 0},
+		{"Flag", Type, 0},
+		{"Marshal", Func, 0},
+		{"MarshalWithParams", Func, 10},
+		{"NullBytes", Var, 9},
+		{"NullRawValue", Var, 9},
+		{"ObjectIdentifier", Type, 0},
+		{"RawContent", Type, 0},
+		{"RawValue", Type, 0},
+		{"RawValue.Bytes", Field, 0},
+		{"RawValue.Class", Field, 0},
+		{"RawValue.FullBytes", Field, 0},
+		{"RawValue.IsCompound", Field, 0},
+		{"RawValue.Tag", Field, 0},
+		{"StructuralError", Type, 0},
+		{"StructuralError.Msg", Field, 0},
+		{"SyntaxError", Type, 0},
+		{"SyntaxError.Msg", Field, 0},
+		{"TagBMPString", Const, 14},
+		{"TagBitString", Const, 6},
+		{"TagBoolean", Const, 6},
+		{"TagEnum", Const, 6},
+		{"TagGeneralString", Const, 6},
+		{"TagGeneralizedTime", Const, 6},
+		{"TagIA5String", Const, 6},
+		{"TagInteger", Const, 6},
+		{"TagNull", Const, 9},
+		{"TagNumericString", Const, 10},
+		{"TagOID", Const, 6},
+		{"TagOctetString", Const, 6},
+		{"TagPrintableString", Const, 6},
+		{"TagSequence", Const, 6},
+		{"TagSet", Const, 6},
+		{"TagT61String", Const, 6},
+		{"TagUTCTime", Const, 6},
+		{"TagUTF8String", Const, 6},
+		{"Unmarshal", Func, 0},
+		{"UnmarshalWithParams", Func, 0},
+	},
+	"encoding/base32": {
+		{"(*Encoding).AppendDecode", Method, 22},
+		{"(*Encoding).AppendEncode", Method, 22},
+		{"(*Encoding).Decode", Method, 0},
+		{"(*Encoding).DecodeString", Method, 0},
+		{"(*Encoding).DecodedLen", Method, 0},
+		{"(*Encoding).Encode", Method, 0},
+		{"(*Encoding).EncodeToString", Method, 0},
+		{"(*Encoding).EncodedLen", Method, 0},
+		{"(CorruptInputError).Error", Method, 0},
+		{"(Encoding).WithPadding", Method, 9},
+		{"CorruptInputError", Type, 0},
+		{"Encoding", Type, 0},
+		{"HexEncoding", Var, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+		{"NewEncoding", Func, 0},
+		{"NoPadding", Const, 9},
+		{"StdEncoding", Var, 0},
+		{"StdPadding", Const, 9},
+	},
+	"encoding/base64": {
+		{"(*Encoding).AppendDecode", Method, 22},
+		{"(*Encoding).AppendEncode", Method, 22},
+		{"(*Encoding).Decode", Method, 0},
+		{"(*Encoding).DecodeString", Method, 0},
+		{"(*Encoding).DecodedLen", Method, 0},
+		{"(*Encoding).Encode", Method, 0},
+		{"(*Encoding).EncodeToString", Method, 0},
+		{"(*Encoding).EncodedLen", Method, 0},
+		{"(CorruptInputError).Error", Method, 0},
+		{"(Encoding).Strict", Method, 8},
+		{"(Encoding).WithPadding", Method, 5},
+		{"CorruptInputError", Type, 0},
+		{"Encoding", Type, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+		{"NewEncoding", Func, 0},
+		{"NoPadding", Const, 5},
+		{"RawStdEncoding", Var, 5},
+		{"RawURLEncoding", Var, 5},
+		{"StdEncoding", Var, 0},
+		{"StdPadding", Const, 5},
+		{"URLEncoding", Var, 0},
+	},
+	"encoding/binary": {
+		{"Append", Func, 23},
+		{"AppendByteOrder", Type, 19},
+		{"AppendUvarint", Func, 19},
+		{"AppendVarint", Func, 19},
+		{"BigEndian", Var, 0},
+		{"ByteOrder", Type, 0},
+		{"Decode", Func, 23},
+		{"Encode", Func, 23},
+		{"LittleEndian", Var, 0},
+		{"MaxVarintLen16", Const, 0},
+		{"MaxVarintLen32", Const, 0},
+		{"MaxVarintLen64", Const, 0},
+		{"NativeEndian", Var, 21},
+		{"PutUvarint", Func, 0},
+		{"PutVarint", Func, 0},
+		{"Read", Func, 0},
+		{"ReadUvarint", Func, 0},
+		{"ReadVarint", Func, 0},
+		{"Size", Func, 0},
+		{"Uvarint", Func, 0},
+		{"Varint", Func, 0},
+		{"Write", Func, 0},
+	},
+	"encoding/csv": {
+		{"(*ParseError).Error", Method, 0},
+		{"(*ParseError).Unwrap", Method, 13},
+		{"(*Reader).FieldPos", Method, 17},
+		{"(*Reader).InputOffset", Method, 19},
+		{"(*Reader).Read", Method, 0},
+		{"(*Reader).ReadAll", Method, 0},
+		{"(*Writer).Error", Method, 1},
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).Write", Method, 0},
+		{"(*Writer).WriteAll", Method, 0},
+		{"ErrBareQuote", Var, 0},
+		{"ErrFieldCount", Var, 0},
+		{"ErrQuote", Var, 0},
+		{"ErrTrailingComma", Var, 0},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"ParseError", Type, 0},
+		{"ParseError.Column", Field, 0},
+		{"ParseError.Err", Field, 0},
+		{"ParseError.Line", Field, 0},
+		{"ParseError.StartLine", Field, 10},
+		{"Reader", Type, 0},
+		{"Reader.Comma", Field, 0},
+		{"Reader.Comment", Field, 0},
+		{"Reader.FieldsPerRecord", Field, 0},
+		{"Reader.LazyQuotes", Field, 0},
+		{"Reader.ReuseRecord", Field, 9},
+		{"Reader.TrailingComma", Field, 0},
+		{"Reader.TrimLeadingSpace", Field, 0},
+		{"Writer", Type, 0},
+		{"Writer.Comma", Field, 0},
+		{"Writer.UseCRLF", Field, 0},
+	},
+	"encoding/gob": {
+		{"(*Decoder).Decode", Method, 0},
+		{"(*Decoder).DecodeValue", Method, 0},
+		{"(*Encoder).Encode", Method, 0},
+		{"(*Encoder).EncodeValue", Method, 0},
+		{"CommonType", Type, 0},
+		{"CommonType.Id", Field, 0},
+		{"CommonType.Name", Field, 0},
+		{"Decoder", Type, 0},
+		{"Encoder", Type, 0},
+		{"GobDecoder", Type, 0},
+		{"GobEncoder", Type, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+		{"Register", Func, 0},
+		{"RegisterName", Func, 0},
+	},
+	"encoding/hex": {
+		{"(InvalidByteError).Error", Method, 0},
+		{"AppendDecode", Func, 22},
+		{"AppendEncode", Func, 22},
+		{"Decode", Func, 0},
+		{"DecodeString", Func, 0},
+		{"DecodedLen", Func, 0},
+		{"Dump", Func, 0},
+		{"Dumper", Func, 0},
+		{"Encode", Func, 0},
+		{"EncodeToString", Func, 0},
+		{"EncodedLen", Func, 0},
+		{"ErrLength", Var, 0},
+		{"InvalidByteError", Type, 0},
+		{"NewDecoder", Func, 10},
+		{"NewEncoder", Func, 10},
+	},
+	"encoding/json": {
+		{"(*Decoder).Buffered", Method, 1},
+		{"(*Decoder).Decode", Method, 0},
+		{"(*Decoder).DisallowUnknownFields", Method, 10},
+		{"(*Decoder).InputOffset", Method, 14},
+		{"(*Decoder).More", Method, 5},
+		{"(*Decoder).Token", Method, 5},
+		{"(*Decoder).UseNumber", Method, 1},
+		{"(*Encoder).Encode", Method, 0},
+		{"(*Encoder).SetEscapeHTML", Method, 7},
+		{"(*Encoder).SetIndent", Method, 7},
+		{"(*InvalidUTF8Error).Error", Method, 0},
+		{"(*InvalidUnmarshalError).Error", Method, 0},
+		{"(*MarshalerError).Error", Method, 0},
+		{"(*MarshalerError).Unwrap", Method, 13},
+		{"(*RawMessage).MarshalJSON", Method, 0},
+		{"(*RawMessage).UnmarshalJSON", Method, 0},
+		{"(*SyntaxError).Error", Method, 0},
+		{"(*UnmarshalFieldError).Error", Method, 0},
+		{"(*UnmarshalTypeError).Error", Method, 0},
+		{"(*UnsupportedTypeError).Error", Method, 0},
+		{"(*UnsupportedValueError).Error", Method, 0},
+		{"(Delim).String", Method, 5},
+		{"(Number).Float64", Method, 1},
+		{"(Number).Int64", Method, 1},
+		{"(Number).String", Method, 1},
+		{"(RawMessage).MarshalJSON", Method, 8},
+		{"Compact", Func, 0},
+		{"Decoder", Type, 0},
+		{"Delim", Type, 5},
+		{"Encoder", Type, 0},
+		{"HTMLEscape", Func, 0},
+		{"Indent", Func, 0},
+		{"InvalidUTF8Error", Type, 0},
+		{"InvalidUTF8Error.S", Field, 0},
+		{"InvalidUnmarshalError", Type, 0},
+		{"InvalidUnmarshalError.Type", Field, 0},
+		{"Marshal", Func, 0},
+		{"MarshalIndent", Func, 0},
+		{"Marshaler", Type, 0},
+		{"MarshalerError", Type, 0},
+		{"MarshalerError.Err", Field, 0},
+		{"MarshalerError.Type", Field, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+		{"Number", Type, 1},
+		{"RawMessage", Type, 0},
+		{"SyntaxError", Type, 0},
+		{"SyntaxError.Offset", Field, 0},
+		{"Token", Type, 5},
+		{"Unmarshal", Func, 0},
+		{"UnmarshalFieldError", Type, 0},
+		{"UnmarshalFieldError.Field", Field, 0},
+		{"UnmarshalFieldError.Key", Field, 0},
+		{"UnmarshalFieldError.Type", Field, 0},
+		{"UnmarshalTypeError", Type, 0},
+		{"UnmarshalTypeError.Field", Field, 8},
+		{"UnmarshalTypeError.Offset", Field, 5},
+		{"UnmarshalTypeError.Struct", Field, 8},
+		{"UnmarshalTypeError.Type", Field, 0},
+		{"UnmarshalTypeError.Value", Field, 0},
+		{"Unmarshaler", Type, 0},
+		{"UnsupportedTypeError", Type, 0},
+		{"UnsupportedTypeError.Type", Field, 0},
+		{"UnsupportedValueError", Type, 0},
+		{"UnsupportedValueError.Str", Field, 0},
+		{"UnsupportedValueError.Value", Field, 0},
+		{"Valid", Func, 9},
+	},
+	"encoding/pem": {
+		{"Block", Type, 0},
+		{"Block.Bytes", Field, 0},
+		{"Block.Headers", Field, 0},
+		{"Block.Type", Field, 0},
+		{"Decode", Func, 0},
+		{"Encode", Func, 0},
+		{"EncodeToMemory", Func, 0},
+	},
+	"encoding/xml": {
+		{"(*Decoder).Decode", Method, 0},
+		{"(*Decoder).DecodeElement", Method, 0},
+		{"(*Decoder).InputOffset", Method, 4},
+		{"(*Decoder).InputPos", Method, 19},
+		{"(*Decoder).RawToken", Method, 0},
+		{"(*Decoder).Skip", Method, 0},
+		{"(*Decoder).Token", Method, 0},
+		{"(*Encoder).Close", Method, 20},
+		{"(*Encoder).Encode", Method, 0},
+		{"(*Encoder).EncodeElement", Method, 2},
+		{"(*Encoder).EncodeToken", Method, 2},
+		{"(*Encoder).Flush", Method, 2},
+		{"(*Encoder).Indent", Method, 1},
+		{"(*SyntaxError).Error", Method, 0},
+		{"(*TagPathError).Error", Method, 0},
+		{"(*UnsupportedTypeError).Error", Method, 0},
+		{"(CharData).Copy", Method, 0},
+		{"(Comment).Copy", Method, 0},
+		{"(Directive).Copy", Method, 0},
+		{"(ProcInst).Copy", Method, 0},
+		{"(StartElement).Copy", Method, 0},
+		{"(StartElement).End", Method, 2},
+		{"(UnmarshalError).Error", Method, 0},
+		{"Attr", Type, 0},
+		{"Attr.Name", Field, 0},
+		{"Attr.Value", Field, 0},
+		{"CharData", Type, 0},
+		{"Comment", Type, 0},
+		{"CopyToken", Func, 0},
+		{"Decoder", Type, 0},
+		{"Decoder.AutoClose", Field, 0},
+		{"Decoder.CharsetReader", Field, 0},
+		{"Decoder.DefaultSpace", Field, 1},
+		{"Decoder.Entity", Field, 0},
+		{"Decoder.Strict", Field, 0},
+		{"Directive", Type, 0},
+		{"Encoder", Type, 0},
+		{"EndElement", Type, 0},
+		{"EndElement.Name", Field, 0},
+		{"Escape", Func, 0},
+		{"EscapeText", Func, 1},
+		{"HTMLAutoClose", Var, 0},
+		{"HTMLEntity", Var, 0},
+		{"Header", Const, 0},
+		{"Marshal", Func, 0},
+		{"MarshalIndent", Func, 0},
+		{"Marshaler", Type, 2},
+		{"MarshalerAttr", Type, 2},
+		{"Name", Type, 0},
+		{"Name.Local", Field, 0},
+		{"Name.Space", Field, 0},
+		{"NewDecoder", Func, 0},
+		{"NewEncoder", Func, 0},
+		{"NewTokenDecoder", Func, 10},
+		{"ProcInst", Type, 0},
+		{"ProcInst.Inst", Field, 0},
+		{"ProcInst.Target", Field, 0},
+		{"StartElement", Type, 0},
+		{"StartElement.Attr", Field, 0},
+		{"StartElement.Name", Field, 0},
+		{"SyntaxError", Type, 0},
+		{"SyntaxError.Line", Field, 0},
+		{"SyntaxError.Msg", Field, 0},
+		{"TagPathError", Type, 0},
+		{"TagPathError.Field1", Field, 0},
+		{"TagPathError.Field2", Field, 0},
+		{"TagPathError.Struct", Field, 0},
+		{"TagPathError.Tag1", Field, 0},
+		{"TagPathError.Tag2", Field, 0},
+		{"Token", Type, 0},
+		{"TokenReader", Type, 10},
+		{"Unmarshal", Func, 0},
+		{"UnmarshalError", Type, 0},
+		{"Unmarshaler", Type, 2},
+		{"UnmarshalerAttr", Type, 2},
+		{"UnsupportedTypeError", Type, 0},
+		{"UnsupportedTypeError.Type", Field, 0},
+	},
+	"errors": {
+		{"As", Func, 13},
+		{"ErrUnsupported", Var, 21},
+		{"Is", Func, 13},
+		{"Join", Func, 20},
+		{"New", Func, 0},
+		{"Unwrap", Func, 13},
+	},
+	"expvar": {
+		{"(*Float).Add", Method, 0},
+		{"(*Float).Set", Method, 0},
+		{"(*Float).String", Method, 0},
+		{"(*Float).Value", Method, 8},
+		{"(*Int).Add", Method, 0},
+		{"(*Int).Set", Method, 0},
+		{"(*Int).String", Method, 0},
+		{"(*Int).Value", Method, 8},
+		{"(*Map).Add", Method, 0},
+		{"(*Map).AddFloat", Method, 0},
+		{"(*Map).Delete", Method, 12},
+		{"(*Map).Do", Method, 0},
+		{"(*Map).Get", Method, 0},
+		{"(*Map).Init", Method, 0},
+		{"(*Map).Set", Method, 0},
+		{"(*Map).String", Method, 0},
+		{"(*String).Set", Method, 0},
+		{"(*String).String", Method, 0},
+		{"(*String).Value", Method, 8},
+		{"(Func).String", Method, 0},
+		{"(Func).Value", Method, 8},
+		{"Do", Func, 0},
+		{"Float", Type, 0},
+		{"Func", Type, 0},
+		{"Get", Func, 0},
+		{"Handler", Func, 8},
+		{"Int", Type, 0},
+		{"KeyValue", Type, 0},
+		{"KeyValue.Key", Field, 0},
+		{"KeyValue.Value", Field, 0},
+		{"Map", Type, 0},
+		{"NewFloat", Func, 0},
+		{"NewInt", Func, 0},
+		{"NewMap", Func, 0},
+		{"NewString", Func, 0},
+		{"Publish", Func, 0},
+		{"String", Type, 0},
+		{"Var", Type, 0},
+	},
+	"flag": {
+		{"(*FlagSet).Arg", Method, 0},
+		{"(*FlagSet).Args", Method, 0},
+		{"(*FlagSet).Bool", Method, 0},
+		{"(*FlagSet).BoolFunc", Method, 21},
+		{"(*FlagSet).BoolVar", Method, 0},
+		{"(*FlagSet).Duration", Method, 0},
+		{"(*FlagSet).DurationVar", Method, 0},
+		{"(*FlagSet).ErrorHandling", Method, 10},
+		{"(*FlagSet).Float64", Method, 0},
+		{"(*FlagSet).Float64Var", Method, 0},
+		{"(*FlagSet).Func", Method, 16},
+		{"(*FlagSet).Init", Method, 0},
+		{"(*FlagSet).Int", Method, 0},
+		{"(*FlagSet).Int64", Method, 0},
+		{"(*FlagSet).Int64Var", Method, 0},
+		{"(*FlagSet).IntVar", Method, 0},
+		{"(*FlagSet).Lookup", Method, 0},
+		{"(*FlagSet).NArg", Method, 0},
+		{"(*FlagSet).NFlag", Method, 0},
+		{"(*FlagSet).Name", Method, 10},
+		{"(*FlagSet).Output", Method, 10},
+		{"(*FlagSet).Parse", Method, 0},
+		{"(*FlagSet).Parsed", Method, 0},
+		{"(*FlagSet).PrintDefaults", Method, 0},
+		{"(*FlagSet).Set", Method, 0},
+		{"(*FlagSet).SetOutput", Method, 0},
+		{"(*FlagSet).String", Method, 0},
+		{"(*FlagSet).StringVar", Method, 0},
+		{"(*FlagSet).TextVar", Method, 19},
+		{"(*FlagSet).Uint", Method, 0},
+		{"(*FlagSet).Uint64", Method, 0},
+		{"(*FlagSet).Uint64Var", Method, 0},
+		{"(*FlagSet).UintVar", Method, 0},
+		{"(*FlagSet).Var", Method, 0},
+		{"(*FlagSet).Visit", Method, 0},
+		{"(*FlagSet).VisitAll", Method, 0},
+		{"Arg", Func, 0},
+		{"Args", Func, 0},
+		{"Bool", Func, 0},
+		{"BoolFunc", Func, 21},
+		{"BoolVar", Func, 0},
+		{"CommandLine", Var, 2},
+		{"ContinueOnError", Const, 0},
+		{"Duration", Func, 0},
+		{"DurationVar", Func, 0},
+		{"ErrHelp", Var, 0},
+		{"ErrorHandling", Type, 0},
+		{"ExitOnError", Const, 0},
+		{"Flag", Type, 0},
+		{"Flag.DefValue", Field, 0},
+		{"Flag.Name", Field, 0},
+		{"Flag.Usage", Field, 0},
+		{"Flag.Value", Field, 0},
+		{"FlagSet", Type, 0},
+		{"FlagSet.Usage", Field, 0},
+		{"Float64", Func, 0},
+		{"Float64Var", Func, 0},
+		{"Func", Func, 16},
+		{"Getter", Type, 2},
+		{"Int", Func, 0},
+		{"Int64", Func, 0},
+		{"Int64Var", Func, 0},
+		{"IntVar", Func, 0},
+		{"Lookup", Func, 0},
+		{"NArg", Func, 0},
+		{"NFlag", Func, 0},
+		{"NewFlagSet", Func, 0},
+		{"PanicOnError", Const, 0},
+		{"Parse", Func, 0},
+		{"Parsed", Func, 0},
+		{"PrintDefaults", Func, 0},
+		{"Set", Func, 0},
+		{"String", Func, 0},
+		{"StringVar", Func, 0},
+		{"TextVar", Func, 19},
+		{"Uint", Func, 0},
+		{"Uint64", Func, 0},
+		{"Uint64Var", Func, 0},
+		{"UintVar", Func, 0},
+		{"UnquoteUsage", Func, 5},
+		{"Usage", Var, 0},
+		{"Value", Type, 0},
+		{"Var", Func, 0},
+		{"Visit", Func, 0},
+		{"VisitAll", Func, 0},
+	},
+	"fmt": {
+		{"Append", Func, 19},
+		{"Appendf", Func, 19},
+		{"Appendln", Func, 19},
+		{"Errorf", Func, 0},
+		{"FormatString", Func, 20},
+		{"Formatter", Type, 0},
+		{"Fprint", Func, 0},
+		{"Fprintf", Func, 0},
+		{"Fprintln", Func, 0},
+		{"Fscan", Func, 0},
+		{"Fscanf", Func, 0},
+		{"Fscanln", Func, 0},
+		{"GoStringer", Type, 0},
+		{"Print", Func, 0},
+		{"Printf", Func, 0},
+		{"Println", Func, 0},
+		{"Scan", Func, 0},
+		{"ScanState", Type, 0},
+		{"Scanf", Func, 0},
+		{"Scanln", Func, 0},
+		{"Scanner", Type, 0},
+		{"Sprint", Func, 0},
+		{"Sprintf", Func, 0},
+		{"Sprintln", Func, 0},
+		{"Sscan", Func, 0},
+		{"Sscanf", Func, 0},
+		{"Sscanln", Func, 0},
+		{"State", Type, 0},
+		{"Stringer", Type, 0},
+	},
+	"go/ast": {
+		{"(*ArrayType).End", Method, 0},
+		{"(*ArrayType).Pos", Method, 0},
+		{"(*AssignStmt).End", Method, 0},
+		{"(*AssignStmt).Pos", Method, 0},
+		{"(*BadDecl).End", Method, 0},
+		{"(*BadDecl).Pos", Method, 0},
+		{"(*BadExpr).End", Method, 0},
+		{"(*BadExpr).Pos", Method, 0},
+		{"(*BadStmt).End", Method, 0},
+		{"(*BadStmt).Pos", Method, 0},
+		{"(*BasicLit).End", Method, 0},
+		{"(*BasicLit).Pos", Method, 0},
+		{"(*BinaryExpr).End", Method, 0},
+		{"(*BinaryExpr).Pos", Method, 0},
+		{"(*BlockStmt).End", Method, 0},
+		{"(*BlockStmt).Pos", Method, 0},
+		{"(*BranchStmt).End", Method, 0},
+		{"(*BranchStmt).Pos", Method, 0},
+		{"(*CallExpr).End", Method, 0},
+		{"(*CallExpr).Pos", Method, 0},
+		{"(*CaseClause).End", Method, 0},
+		{"(*CaseClause).Pos", Method, 0},
+		{"(*ChanType).End", Method, 0},
+		{"(*ChanType).Pos", Method, 0},
+		{"(*CommClause).End", Method, 0},
+		{"(*CommClause).Pos", Method, 0},
+		{"(*Comment).End", Method, 0},
+		{"(*Comment).Pos", Method, 0},
+		{"(*CommentGroup).End", Method, 0},
+		{"(*CommentGroup).Pos", Method, 0},
+		{"(*CommentGroup).Text", Method, 0},
+		{"(*CompositeLit).End", Method, 0},
+		{"(*CompositeLit).Pos", Method, 0},
+		{"(*DeclStmt).End", Method, 0},
+		{"(*DeclStmt).Pos", Method, 0},
+		{"(*DeferStmt).End", Method, 0},
+		{"(*DeferStmt).Pos", Method, 0},
+		{"(*Ellipsis).End", Method, 0},
+		{"(*Ellipsis).Pos", Method, 0},
+		{"(*EmptyStmt).End", Method, 0},
+		{"(*EmptyStmt).Pos", Method, 0},
+		{"(*ExprStmt).End", Method, 0},
+		{"(*ExprStmt).Pos", Method, 0},
+		{"(*Field).End", Method, 0},
+		{"(*Field).Pos", Method, 0},
+		{"(*FieldList).End", Method, 0},
+		{"(*FieldList).NumFields", Method, 0},
+		{"(*FieldList).Pos", Method, 0},
+		{"(*File).End", Method, 0},
+		{"(*File).Pos", Method, 0},
+		{"(*ForStmt).End", Method, 0},
+		{"(*ForStmt).Pos", Method, 0},
+		{"(*FuncDecl).End", Method, 0},
+		{"(*FuncDecl).Pos", Method, 0},
+		{"(*FuncLit).End", Method, 0},
+		{"(*FuncLit).Pos", Method, 0},
+		{"(*FuncType).End", Method, 0},
+		{"(*FuncType).Pos", Method, 0},
+		{"(*GenDecl).End", Method, 0},
+		{"(*GenDecl).Pos", Method, 0},
+		{"(*GoStmt).End", Method, 0},
+		{"(*GoStmt).Pos", Method, 0},
+		{"(*Ident).End", Method, 0},
+		{"(*Ident).IsExported", Method, 0},
+		{"(*Ident).Pos", Method, 0},
+		{"(*Ident).String", Method, 0},
+		{"(*IfStmt).End", Method, 0},
+		{"(*IfStmt).Pos", Method, 0},
+		{"(*ImportSpec).End", Method, 0},
+		{"(*ImportSpec).Pos", Method, 0},
+		{"(*IncDecStmt).End", Method, 0},
+		{"(*IncDecStmt).Pos", Method, 0},
+		{"(*IndexExpr).End", Method, 0},
+		{"(*IndexExpr).Pos", Method, 0},
+		{"(*IndexListExpr).End", Method, 18},
+		{"(*IndexListExpr).Pos", Method, 18},
+		{"(*InterfaceType).End", Method, 0},
+		{"(*InterfaceType).Pos", Method, 0},
+		{"(*KeyValueExpr).End", Method, 0},
+		{"(*KeyValueExpr).Pos", Method, 0},
+		{"(*LabeledStmt).End", Method, 0},
+		{"(*LabeledStmt).Pos", Method, 0},
+		{"(*MapType).End", Method, 0},
+		{"(*MapType).Pos", Method, 0},
+		{"(*Object).Pos", Method, 0},
+		{"(*Package).End", Method, 0},
+		{"(*Package).Pos", Method, 0},
+		{"(*ParenExpr).End", Method, 0},
+		{"(*ParenExpr).Pos", Method, 0},
+		{"(*RangeStmt).End", Method, 0},
+		{"(*RangeStmt).Pos", Method, 0},
+		{"(*ReturnStmt).End", Method, 0},
+		{"(*ReturnStmt).Pos", Method, 0},
+		{"(*Scope).Insert", Method, 0},
+		{"(*Scope).Lookup", Method, 0},
+		{"(*Scope).String", Method, 0},
+		{"(*SelectStmt).End", Method, 0},
+		{"(*SelectStmt).Pos", Method, 0},
+		{"(*SelectorExpr).End", Method, 0},
+		{"(*SelectorExpr).Pos", Method, 0},
+		{"(*SendStmt).End", Method, 0},
+		{"(*SendStmt).Pos", Method, 0},
+		{"(*SliceExpr).End", Method, 0},
+		{"(*SliceExpr).Pos", Method, 0},
+		{"(*StarExpr).End", Method, 0},
+		{"(*StarExpr).Pos", Method, 0},
+		{"(*StructType).End", Method, 0},
+		{"(*StructType).Pos", Method, 0},
+		{"(*SwitchStmt).End", Method, 0},
+		{"(*SwitchStmt).Pos", Method, 0},
+		{"(*TypeAssertExpr).End", Method, 0},
+		{"(*TypeAssertExpr).Pos", Method, 0},
+		{"(*TypeSpec).End", Method, 0},
+		{"(*TypeSpec).Pos", Method, 0},
+		{"(*TypeSwitchStmt).End", Method, 0},
+		{"(*TypeSwitchStmt).Pos", Method, 0},
+		{"(*UnaryExpr).End", Method, 0},
+		{"(*UnaryExpr).Pos", Method, 0},
+		{"(*ValueSpec).End", Method, 0},
+		{"(*ValueSpec).Pos", Method, 0},
+		{"(CommentMap).Comments", Method, 1},
+		{"(CommentMap).Filter", Method, 1},
+		{"(CommentMap).String", Method, 1},
+		{"(CommentMap).Update", Method, 1},
+		{"(ObjKind).String", Method, 0},
+		{"ArrayType", Type, 0},
+		{"ArrayType.Elt", Field, 0},
+		{"ArrayType.Lbrack", Field, 0},
+		{"ArrayType.Len", Field, 0},
+		{"AssignStmt", Type, 0},
+		{"AssignStmt.Lhs", Field, 0},
+		{"AssignStmt.Rhs", Field, 0},
+		{"AssignStmt.Tok", Field, 0},
+		{"AssignStmt.TokPos", Field, 0},
+		{"Bad", Const, 0},
+		{"BadDecl", Type, 0},
+		{"BadDecl.From", Field, 0},
+		{"BadDecl.To", Field, 0},
+		{"BadExpr", Type, 0},
+		{"BadExpr.From", Field, 0},
+		{"BadExpr.To", Field, 0},
+		{"BadStmt", Type, 0},
+		{"BadStmt.From", Field, 0},
+		{"BadStmt.To", Field, 0},
+		{"BasicLit", Type, 0},
+		{"BasicLit.Kind", Field, 0},
+		{"BasicLit.Value", Field, 0},
+		{"BasicLit.ValuePos", Field, 0},
+		{"BinaryExpr", Type, 0},
+		{"BinaryExpr.Op", Field, 0},
+		{"BinaryExpr.OpPos", Field, 0},
+		{"BinaryExpr.X", Field, 0},
+		{"BinaryExpr.Y", Field, 0},
+		{"BlockStmt", Type, 0},
+		{"BlockStmt.Lbrace", Field, 0},
+		{"BlockStmt.List", Field, 0},
+		{"BlockStmt.Rbrace", Field, 0},
+		{"BranchStmt", Type, 0},
+		{"BranchStmt.Label", Field, 0},
+		{"BranchStmt.Tok", Field, 0},
+		{"BranchStmt.TokPos", Field, 0},
+		{"CallExpr", Type, 0},
+		{"CallExpr.Args", Field, 0},
+		{"CallExpr.Ellipsis", Field, 0},
+		{"CallExpr.Fun", Field, 0},
+		{"CallExpr.Lparen", Field, 0},
+		{"CallExpr.Rparen", Field, 0},
+		{"CaseClause", Type, 0},
+		{"CaseClause.Body", Field, 0},
+		{"CaseClause.Case", Field, 0},
+		{"CaseClause.Colon", Field, 0},
+		{"CaseClause.List", Field, 0},
+		{"ChanDir", Type, 0},
+		{"ChanType", Type, 0},
+		{"ChanType.Arrow", Field, 1},
+		{"ChanType.Begin", Field, 0},
+		{"ChanType.Dir", Field, 0},
+		{"ChanType.Value", Field, 0},
+		{"CommClause", Type, 0},
+		{"CommClause.Body", Field, 0},
+		{"CommClause.Case", Field, 0},
+		{"CommClause.Colon", Field, 0},
+		{"CommClause.Comm", Field, 0},
+		{"Comment", Type, 0},
+		{"Comment.Slash", Field, 0},
+		{"Comment.Text", Field, 0},
+		{"CommentGroup", Type, 0},
+		{"CommentGroup.List", Field, 0},
+		{"CommentMap", Type, 1},
+		{"CompositeLit", Type, 0},
+		{"CompositeLit.Elts", Field, 0},
+		{"CompositeLit.Incomplete", Field, 11},
+		{"CompositeLit.Lbrace", Field, 0},
+		{"CompositeLit.Rbrace", Field, 0},
+		{"CompositeLit.Type", Field, 0},
+		{"Con", Const, 0},
+		{"Decl", Type, 0},
+		{"DeclStmt", Type, 0},
+		{"DeclStmt.Decl", Field, 0},
+		{"DeferStmt", Type, 0},
+		{"DeferStmt.Call", Field, 0},
+		{"DeferStmt.Defer", Field, 0},
+		{"Ellipsis", Type, 0},
+		{"Ellipsis.Ellipsis", Field, 0},
+		{"Ellipsis.Elt", Field, 0},
+		{"EmptyStmt", Type, 0},
+		{"EmptyStmt.Implicit", Field, 5},
+		{"EmptyStmt.Semicolon", Field, 0},
+		{"Expr", Type, 0},
+		{"ExprStmt", Type, 0},
+		{"ExprStmt.X", Field, 0},
+		{"Field", Type, 0},
+		{"Field.Comment", Field, 0},
+		{"Field.Doc", Field, 0},
+		{"Field.Names", Field, 0},
+		{"Field.Tag", Field, 0},
+		{"Field.Type", Field, 0},
+		{"FieldFilter", Type, 0},
+		{"FieldList", Type, 0},
+		{"FieldList.Closing", Field, 0},
+		{"FieldList.List", Field, 0},
+		{"FieldList.Opening", Field, 0},
+		{"File", Type, 0},
+		{"File.Comments", Field, 0},
+		{"File.Decls", Field, 0},
+		{"File.Doc", Field, 0},
+		{"File.FileEnd", Field, 20},
+		{"File.FileStart", Field, 20},
+		{"File.GoVersion", Field, 21},
+		{"File.Imports", Field, 0},
+		{"File.Name", Field, 0},
+		{"File.Package", Field, 0},
+		{"File.Scope", Field, 0},
+		{"File.Unresolved", Field, 0},
+		{"FileExports", Func, 0},
+		{"Filter", Type, 0},
+		{"FilterDecl", Func, 0},
+		{"FilterFile", Func, 0},
+		{"FilterFuncDuplicates", Const, 0},
+		{"FilterImportDuplicates", Const, 0},
+		{"FilterPackage", Func, 0},
+		{"FilterUnassociatedComments", Const, 0},
+		{"ForStmt", Type, 0},
+		{"ForStmt.Body", Field, 0},
+		{"ForStmt.Cond", Field, 0},
+		{"ForStmt.For", Field, 0},
+		{"ForStmt.Init", Field, 0},
+		{"ForStmt.Post", Field, 0},
+		{"Fprint", Func, 0},
+		{"Fun", Const, 0},
+		{"FuncDecl", Type, 0},
+		{"FuncDecl.Body", Field, 0},
+		{"FuncDecl.Doc", Field, 0},
+		{"FuncDecl.Name", Field, 0},
+		{"FuncDecl.Recv", Field, 0},
+		{"FuncDecl.Type", Field, 0},
+		{"FuncLit", Type, 0},
+		{"FuncLit.Body", Field, 0},
+		{"FuncLit.Type", Field, 0},
+		{"FuncType", Type, 0},
+		{"FuncType.Func", Field, 0},
+		{"FuncType.Params", Field, 0},
+		{"FuncType.Results", Field, 0},
+		{"FuncType.TypeParams", Field, 18},
+		{"GenDecl", Type, 0},
+		{"GenDecl.Doc", Field, 0},
+		{"GenDecl.Lparen", Field, 0},
+		{"GenDecl.Rparen", Field, 0},
+		{"GenDecl.Specs", Field, 0},
+		{"GenDecl.Tok", Field, 0},
+		{"GenDecl.TokPos", Field, 0},
+		{"GoStmt", Type, 0},
+		{"GoStmt.Call", Field, 0},
+		{"GoStmt.Go", Field, 0},
+		{"Ident", Type, 0},
+		{"Ident.Name", Field, 0},
+		{"Ident.NamePos", Field, 0},
+		{"Ident.Obj", Field, 0},
+		{"IfStmt", Type, 0},
+		{"IfStmt.Body", Field, 0},
+		{"IfStmt.Cond", Field, 0},
+		{"IfStmt.Else", Field, 0},
+		{"IfStmt.If", Field, 0},
+		{"IfStmt.Init", Field, 0},
+		{"ImportSpec", Type, 0},
+		{"ImportSpec.Comment", Field, 0},
+		{"ImportSpec.Doc", Field, 0},
+		{"ImportSpec.EndPos", Field, 0},
+		{"ImportSpec.Name", Field, 0},
+		{"ImportSpec.Path", Field, 0},
+		{"Importer", Type, 0},
+		{"IncDecStmt", Type, 0},
+		{"IncDecStmt.Tok", Field, 0},
+		{"IncDecStmt.TokPos", Field, 0},
+		{"IncDecStmt.X", Field, 0},
+		{"IndexExpr", Type, 0},
+		{"IndexExpr.Index", Field, 0},
+		{"IndexExpr.Lbrack", Field, 0},
+		{"IndexExpr.Rbrack", Field, 0},
+		{"IndexExpr.X", Field, 0},
+		{"IndexListExpr", Type, 18},
+		{"IndexListExpr.Indices", Field, 18},
+		{"IndexListExpr.Lbrack", Field, 18},
+		{"IndexListExpr.Rbrack", Field, 18},
+		{"IndexListExpr.X", Field, 18},
+		{"Inspect", Func, 0},
+		{"InterfaceType", Type, 0},
+		{"InterfaceType.Incomplete", Field, 0},
+		{"InterfaceType.Interface", Field, 0},
+		{"InterfaceType.Methods", Field, 0},
+		{"IsExported", Func, 0},
+		{"IsGenerated", Func, 21},
+		{"KeyValueExpr", Type, 0},
+		{"KeyValueExpr.Colon", Field, 0},
+		{"KeyValueExpr.Key", Field, 0},
+		{"KeyValueExpr.Value", Field, 0},
+		{"LabeledStmt", Type, 0},
+		{"LabeledStmt.Colon", Field, 0},
+		{"LabeledStmt.Label", Field, 0},
+		{"LabeledStmt.Stmt", Field, 0},
+		{"Lbl", Const, 0},
+		{"MapType", Type, 0},
+		{"MapType.Key", Field, 0},
+		{"MapType.Map", Field, 0},
+		{"MapType.Value", Field, 0},
+		{"MergeMode", Type, 0},
+		{"MergePackageFiles", Func, 0},
+		{"NewCommentMap", Func, 1},
+		{"NewIdent", Func, 0},
+		{"NewObj", Func, 0},
+		{"NewPackage", Func, 0},
+		{"NewScope", Func, 0},
+		{"Node", Type, 0},
+		{"NotNilFilter", Func, 0},
+		{"ObjKind", Type, 0},
+		{"Object", Type, 0},
+		{"Object.Data", Field, 0},
+		{"Object.Decl", Field, 0},
+		{"Object.Kind", Field, 0},
+		{"Object.Name", Field, 0},
+		{"Object.Type", Field, 0},
+		{"Package", Type, 0},
+		{"Package.Files", Field, 0},
+		{"Package.Imports", Field, 0},
+		{"Package.Name", Field, 0},
+		{"Package.Scope", Field, 0},
+		{"PackageExports", Func, 0},
+		{"ParenExpr", Type, 0},
+		{"ParenExpr.Lparen", Field, 0},
+		{"ParenExpr.Rparen", Field, 0},
+		{"ParenExpr.X", Field, 0},
+		{"Pkg", Const, 0},
+		{"Preorder", Func, 23},
+		{"Print", Func, 0},
+		{"RECV", Const, 0},
+		{"RangeStmt", Type, 0},
+		{"RangeStmt.Body", Field, 0},
+		{"RangeStmt.For", Field, 0},
+		{"RangeStmt.Key", Field, 0},
+		{"RangeStmt.Range", Field, 20},
+		{"RangeStmt.Tok", Field, 0},
+		{"RangeStmt.TokPos", Field, 0},
+		{"RangeStmt.Value", Field, 0},
+		{"RangeStmt.X", Field, 0},
+		{"ReturnStmt", Type, 0},
+		{"ReturnStmt.Results", Field, 0},
+		{"ReturnStmt.Return", Field, 0},
+		{"SEND", Const, 0},
+		{"Scope", Type, 0},
+		{"Scope.Objects", Field, 0},
+		{"Scope.Outer", Field, 0},
+		{"SelectStmt", Type, 0},
+		{"SelectStmt.Body", Field, 0},
+		{"SelectStmt.Select", Field, 0},
+		{"SelectorExpr", Type, 0},
+		{"SelectorExpr.Sel", Field, 0},
+		{"SelectorExpr.X", Field, 0},
+		{"SendStmt", Type, 0},
+		{"SendStmt.Arrow", Field, 0},
+		{"SendStmt.Chan", Field, 0},
+		{"SendStmt.Value", Field, 0},
+		{"SliceExpr", Type, 0},
+		{"SliceExpr.High", Field, 0},
+		{"SliceExpr.Lbrack", Field, 0},
+		{"SliceExpr.Low", Field, 0},
+		{"SliceExpr.Max", Field, 2},
+		{"SliceExpr.Rbrack", Field, 0},
+		{"SliceExpr.Slice3", Field, 2},
+		{"SliceExpr.X", Field, 0},
+		{"SortImports", Func, 0},
+		{"Spec", Type, 0},
+		{"StarExpr", Type, 0},
+		{"StarExpr.Star", Field, 0},
+		{"StarExpr.X", Field, 0},
+		{"Stmt", Type, 0},
+		{"StructType", Type, 0},
+		{"StructType.Fields", Field, 0},
+		{"StructType.Incomplete", Field, 0},
+		{"StructType.Struct", Field, 0},
+		{"SwitchStmt", Type, 0},
+		{"SwitchStmt.Body", Field, 0},
+		{"SwitchStmt.Init", Field, 0},
+		{"SwitchStmt.Switch", Field, 0},
+		{"SwitchStmt.Tag", Field, 0},
+		{"Typ", Const, 0},
+		{"TypeAssertExpr", Type, 0},
+		{"TypeAssertExpr.Lparen", Field, 2},
+		{"TypeAssertExpr.Rparen", Field, 2},
+		{"TypeAssertExpr.Type", Field, 0},
+		{"TypeAssertExpr.X", Field, 0},
+		{"TypeSpec", Type, 0},
+		{"TypeSpec.Assign", Field, 9},
+		{"TypeSpec.Comment", Field, 0},
+		{"TypeSpec.Doc", Field, 0},
+		{"TypeSpec.Name", Field, 0},
+		{"TypeSpec.Type", Field, 0},
+		{"TypeSpec.TypeParams", Field, 18},
+		{"TypeSwitchStmt", Type, 0},
+		{"TypeSwitchStmt.Assign", Field, 0},
+		{"TypeSwitchStmt.Body", Field, 0},
+		{"TypeSwitchStmt.Init", Field, 0},
+		{"TypeSwitchStmt.Switch", Field, 0},
+		{"UnaryExpr", Type, 0},
+		{"UnaryExpr.Op", Field, 0},
+		{"UnaryExpr.OpPos", Field, 0},
+		{"UnaryExpr.X", Field, 0},
+		{"Unparen", Func, 22},
+		{"ValueSpec", Type, 0},
+		{"ValueSpec.Comment", Field, 0},
+		{"ValueSpec.Doc", Field, 0},
+		{"ValueSpec.Names", Field, 0},
+		{"ValueSpec.Type", Field, 0},
+		{"ValueSpec.Values", Field, 0},
+		{"Var", Const, 0},
+		{"Visitor", Type, 0},
+		{"Walk", Func, 0},
+	},
+	"go/build": {
+		{"(*Context).Import", Method, 0},
+		{"(*Context).ImportDir", Method, 0},
+		{"(*Context).MatchFile", Method, 2},
+		{"(*Context).SrcDirs", Method, 0},
+		{"(*MultiplePackageError).Error", Method, 4},
+		{"(*NoGoError).Error", Method, 0},
+		{"(*Package).IsCommand", Method, 0},
+		{"AllowBinary", Const, 0},
+		{"ArchChar", Func, 0},
+		{"Context", Type, 0},
+		{"Context.BuildTags", Field, 0},
+		{"Context.CgoEnabled", Field, 0},
+		{"Context.Compiler", Field, 0},
+		{"Context.Dir", Field, 14},
+		{"Context.GOARCH", Field, 0},
+		{"Context.GOOS", Field, 0},
+		{"Context.GOPATH", Field, 0},
+		{"Context.GOROOT", Field, 0},
+		{"Context.HasSubdir", Field, 0},
+		{"Context.InstallSuffix", Field, 1},
+		{"Context.IsAbsPath", Field, 0},
+		{"Context.IsDir", Field, 0},
+		{"Context.JoinPath", Field, 0},
+		{"Context.OpenFile", Field, 0},
+		{"Context.ReadDir", Field, 0},
+		{"Context.ReleaseTags", Field, 1},
+		{"Context.SplitPathList", Field, 0},
+		{"Context.ToolTags", Field, 17},
+		{"Context.UseAllFiles", Field, 0},
+		{"Default", Var, 0},
+		{"Directive", Type, 21},
+		{"Directive.Pos", Field, 21},
+		{"Directive.Text", Field, 21},
+		{"FindOnly", Const, 0},
+		{"IgnoreVendor", Const, 6},
+		{"Import", Func, 0},
+		{"ImportComment", Const, 4},
+		{"ImportDir", Func, 0},
+		{"ImportMode", Type, 0},
+		{"IsLocalImport", Func, 0},
+		{"MultiplePackageError", Type, 4},
+		{"MultiplePackageError.Dir", Field, 4},
+		{"MultiplePackageError.Files", Field, 4},
+		{"MultiplePackageError.Packages", Field, 4},
+		{"NoGoError", Type, 0},
+		{"NoGoError.Dir", Field, 0},
+		{"Package", Type, 0},
+		{"Package.AllTags", Field, 2},
+		{"Package.BinDir", Field, 0},
+		{"Package.BinaryOnly", Field, 7},
+		{"Package.CFiles", Field, 0},
+		{"Package.CXXFiles", Field, 2},
+		{"Package.CgoCFLAGS", Field, 0},
+		{"Package.CgoCPPFLAGS", Field, 2},
+		{"Package.CgoCXXFLAGS", Field, 2},
+		{"Package.CgoFFLAGS", Field, 7},
+		{"Package.CgoFiles", Field, 0},
+		{"Package.CgoLDFLAGS", Field, 0},
+		{"Package.CgoPkgConfig", Field, 0},
+		{"Package.ConflictDir", Field, 2},
+		{"Package.Dir", Field, 0},
+		{"Package.Directives", Field, 21},
+		{"Package.Doc", Field, 0},
+		{"Package.EmbedPatternPos", Field, 16},
+		{"Package.EmbedPatterns", Field, 16},
+		{"Package.FFiles", Field, 7},
+		{"Package.GoFiles", Field, 0},
+		{"Package.Goroot", Field, 0},
+		{"Package.HFiles", Field, 0},
+		{"Package.IgnoredGoFiles", Field, 1},
+		{"Package.IgnoredOtherFiles", Field, 16},
+		{"Package.ImportComment", Field, 4},
+		{"Package.ImportPath", Field, 0},
+		{"Package.ImportPos", Field, 0},
+		{"Package.Imports", Field, 0},
+		{"Package.InvalidGoFiles", Field, 6},
+		{"Package.MFiles", Field, 3},
+		{"Package.Name", Field, 0},
+		{"Package.PkgObj", Field, 0},
+		{"Package.PkgRoot", Field, 0},
+		{"Package.PkgTargetRoot", Field, 5},
+		{"Package.Root", Field, 0},
+		{"Package.SFiles", Field, 0},
+		{"Package.SrcRoot", Field, 0},
+		{"Package.SwigCXXFiles", Field, 1},
+		{"Package.SwigFiles", Field, 1},
+		{"Package.SysoFiles", Field, 0},
+		{"Package.TestDirectives", Field, 21},
+		{"Package.TestEmbedPatternPos", Field, 16},
+		{"Package.TestEmbedPatterns", Field, 16},
+		{"Package.TestGoFiles", Field, 0},
+		{"Package.TestImportPos", Field, 0},
+		{"Package.TestImports", Field, 0},
+		{"Package.XTestDirectives", Field, 21},
+		{"Package.XTestEmbedPatternPos", Field, 16},
+		{"Package.XTestEmbedPatterns", Field, 16},
+		{"Package.XTestGoFiles", Field, 0},
+		{"Package.XTestImportPos", Field, 0},
+		{"Package.XTestImports", Field, 0},
+		{"ToolDir", Var, 0},
+	},
+	"go/build/constraint": {
+		{"(*AndExpr).Eval", Method, 16},
+		{"(*AndExpr).String", Method, 16},
+		{"(*NotExpr).Eval", Method, 16},
+		{"(*NotExpr).String", Method, 16},
+		{"(*OrExpr).Eval", Method, 16},
+		{"(*OrExpr).String", Method, 16},
+		{"(*SyntaxError).Error", Method, 16},
+		{"(*TagExpr).Eval", Method, 16},
+		{"(*TagExpr).String", Method, 16},
+		{"AndExpr", Type, 16},
+		{"AndExpr.X", Field, 16},
+		{"AndExpr.Y", Field, 16},
+		{"Expr", Type, 16},
+		{"GoVersion", Func, 21},
+		{"IsGoBuild", Func, 16},
+		{"IsPlusBuild", Func, 16},
+		{"NotExpr", Type, 16},
+		{"NotExpr.X", Field, 16},
+		{"OrExpr", Type, 16},
+		{"OrExpr.X", Field, 16},
+		{"OrExpr.Y", Field, 16},
+		{"Parse", Func, 16},
+		{"PlusBuildLines", Func, 16},
+		{"SyntaxError", Type, 16},
+		{"SyntaxError.Err", Field, 16},
+		{"SyntaxError.Offset", Field, 16},
+		{"TagExpr", Type, 16},
+		{"TagExpr.Tag", Field, 16},
+	},
+	"go/constant": {
+		{"(Kind).String", Method, 18},
+		{"BinaryOp", Func, 5},
+		{"BitLen", Func, 5},
+		{"Bool", Const, 5},
+		{"BoolVal", Func, 5},
+		{"Bytes", Func, 5},
+		{"Compare", Func, 5},
+		{"Complex", Const, 5},
+		{"Denom", Func, 5},
+		{"Float", Const, 5},
+		{"Float32Val", Func, 5},
+		{"Float64Val", Func, 5},
+		{"Imag", Func, 5},
+		{"Int", Const, 5},
+		{"Int64Val", Func, 5},
+		{"Kind", Type, 5},
+		{"Make", Func, 13},
+		{"MakeBool", Func, 5},
+		{"MakeFloat64", Func, 5},
+		{"MakeFromBytes", Func, 5},
+		{"MakeFromLiteral", Func, 5},
+		{"MakeImag", Func, 5},
+		{"MakeInt64", Func, 5},
+		{"MakeString", Func, 5},
+		{"MakeUint64", Func, 5},
+		{"MakeUnknown", Func, 5},
+		{"Num", Func, 5},
+		{"Real", Func, 5},
+		{"Shift", Func, 5},
+		{"Sign", Func, 5},
+		{"String", Const, 5},
+		{"StringVal", Func, 5},
+		{"ToComplex", Func, 6},
+		{"ToFloat", Func, 6},
+		{"ToInt", Func, 6},
+		{"Uint64Val", Func, 5},
+		{"UnaryOp", Func, 5},
+		{"Unknown", Const, 5},
+		{"Val", Func, 13},
+		{"Value", Type, 5},
+	},
+	"go/doc": {
+		{"(*Package).Filter", Method, 0},
+		{"(*Package).HTML", Method, 19},
+		{"(*Package).Markdown", Method, 19},
+		{"(*Package).Parser", Method, 19},
+		{"(*Package).Printer", Method, 19},
+		{"(*Package).Synopsis", Method, 19},
+		{"(*Package).Text", Method, 19},
+		{"AllDecls", Const, 0},
+		{"AllMethods", Const, 0},
+		{"Example", Type, 0},
+		{"Example.Code", Field, 0},
+		{"Example.Comments", Field, 0},
+		{"Example.Doc", Field, 0},
+		{"Example.EmptyOutput", Field, 1},
+		{"Example.Name", Field, 0},
+		{"Example.Order", Field, 1},
+		{"Example.Output", Field, 0},
+		{"Example.Play", Field, 1},
+		{"Example.Suffix", Field, 14},
+		{"Example.Unordered", Field, 7},
+		{"Examples", Func, 0},
+		{"Filter", Type, 0},
+		{"Func", Type, 0},
+		{"Func.Decl", Field, 0},
+		{"Func.Doc", Field, 0},
+		{"Func.Examples", Field, 14},
+		{"Func.Level", Field, 0},
+		{"Func.Name", Field, 0},
+		{"Func.Orig", Field, 0},
+		{"Func.Recv", Field, 0},
+		{"IllegalPrefixes", Var, 1},
+		{"IsPredeclared", Func, 8},
+		{"Mode", Type, 0},
+		{"New", Func, 0},
+		{"NewFromFiles", Func, 14},
+		{"Note", Type, 1},
+		{"Note.Body", Field, 1},
+		{"Note.End", Field, 1},
+		{"Note.Pos", Field, 1},
+		{"Note.UID", Field, 1},
+		{"Package", Type, 0},
+		{"Package.Bugs", Field, 0},
+		{"Package.Consts", Field, 0},
+		{"Package.Doc", Field, 0},
+		{"Package.Examples", Field, 14},
+		{"Package.Filenames", Field, 0},
+		{"Package.Funcs", Field, 0},
+		{"Package.ImportPath", Field, 0},
+		{"Package.Imports", Field, 0},
+		{"Package.Name", Field, 0},
+		{"Package.Notes", Field, 1},
+		{"Package.Types", Field, 0},
+		{"Package.Vars", Field, 0},
+		{"PreserveAST", Const, 12},
+		{"Synopsis", Func, 0},
+		{"ToHTML", Func, 0},
+		{"ToText", Func, 0},
+		{"Type", Type, 0},
+		{"Type.Consts", Field, 0},
+		{"Type.Decl", Field, 0},
+		{"Type.Doc", Field, 0},
+		{"Type.Examples", Field, 14},
+		{"Type.Funcs", Field, 0},
+		{"Type.Methods", Field, 0},
+		{"Type.Name", Field, 0},
+		{"Type.Vars", Field, 0},
+		{"Value", Type, 0},
+		{"Value.Decl", Field, 0},
+		{"Value.Doc", Field, 0},
+		{"Value.Names", Field, 0},
+	},
+	"go/doc/comment": {
+		{"(*DocLink).DefaultURL", Method, 19},
+		{"(*Heading).DefaultID", Method, 19},
+		{"(*List).BlankBefore", Method, 19},
+		{"(*List).BlankBetween", Method, 19},
+		{"(*Parser).Parse", Method, 19},
+		{"(*Printer).Comment", Method, 19},
+		{"(*Printer).HTML", Method, 19},
+		{"(*Printer).Markdown", Method, 19},
+		{"(*Printer).Text", Method, 19},
+		{"Block", Type, 19},
+		{"Code", Type, 19},
+		{"Code.Text", Field, 19},
+		{"DefaultLookupPackage", Func, 19},
+		{"Doc", Type, 19},
+		{"Doc.Content", Field, 19},
+		{"Doc.Links", Field, 19},
+		{"DocLink", Type, 19},
+		{"DocLink.ImportPath", Field, 19},
+		{"DocLink.Name", Field, 19},
+		{"DocLink.Recv", Field, 19},
+		{"DocLink.Text", Field, 19},
+		{"Heading", Type, 19},
+		{"Heading.Text", Field, 19},
+		{"Italic", Type, 19},
+		{"Link", Type, 19},
+		{"Link.Auto", Field, 19},
+		{"Link.Text", Field, 19},
+		{"Link.URL", Field, 19},
+		{"LinkDef", Type, 19},
+		{"LinkDef.Text", Field, 19},
+		{"LinkDef.URL", Field, 19},
+		{"LinkDef.Used", Field, 19},
+		{"List", Type, 19},
+		{"List.ForceBlankBefore", Field, 19},
+		{"List.ForceBlankBetween", Field, 19},
+		{"List.Items", Field, 19},
+		{"ListItem", Type, 19},
+		{"ListItem.Content", Field, 19},
+		{"ListItem.Number", Field, 19},
+		{"Paragraph", Type, 19},
+		{"Paragraph.Text", Field, 19},
+		{"Parser", Type, 19},
+		{"Parser.LookupPackage", Field, 19},
+		{"Parser.LookupSym", Field, 19},
+		{"Parser.Words", Field, 19},
+		{"Plain", Type, 19},
+		{"Printer", Type, 19},
+		{"Printer.DocLinkBaseURL", Field, 19},
+		{"Printer.DocLinkURL", Field, 19},
+		{"Printer.HeadingID", Field, 19},
+		{"Printer.HeadingLevel", Field, 19},
+		{"Printer.TextCodePrefix", Field, 19},
+		{"Printer.TextPrefix", Field, 19},
+		{"Printer.TextWidth", Field, 19},
+		{"Text", Type, 19},
+	},
+	"go/format": {
+		{"Node", Func, 1},
+		{"Source", Func, 1},
+	},
+	"go/importer": {
+		{"Default", Func, 5},
+		{"For", Func, 5},
+		{"ForCompiler", Func, 12},
+		{"Lookup", Type, 5},
+	},
+	"go/parser": {
+		{"AllErrors", Const, 1},
+		{"DeclarationErrors", Const, 0},
+		{"ImportsOnly", Const, 0},
+		{"Mode", Type, 0},
+		{"PackageClauseOnly", Const, 0},
+		{"ParseComments", Const, 0},
+		{"ParseDir", Func, 0},
+		{"ParseExpr", Func, 0},
+		{"ParseExprFrom", Func, 5},
+		{"ParseFile", Func, 0},
+		{"SkipObjectResolution", Const, 17},
+		{"SpuriousErrors", Const, 0},
+		{"Trace", Const, 0},
+	},
+	"go/printer": {
+		{"(*Config).Fprint", Method, 0},
+		{"CommentedNode", Type, 0},
+		{"CommentedNode.Comments", Field, 0},
+		{"CommentedNode.Node", Field, 0},
+		{"Config", Type, 0},
+		{"Config.Indent", Field, 1},
+		{"Config.Mode", Field, 0},
+		{"Config.Tabwidth", Field, 0},
+		{"Fprint", Func, 0},
+		{"Mode", Type, 0},
+		{"RawFormat", Const, 0},
+		{"SourcePos", Const, 0},
+		{"TabIndent", Const, 0},
+		{"UseSpaces", Const, 0},
+	},
+	"go/scanner": {
+		{"(*ErrorList).Add", Method, 0},
+		{"(*ErrorList).RemoveMultiples", Method, 0},
+		{"(*ErrorList).Reset", Method, 0},
+		{"(*Scanner).Init", Method, 0},
+		{"(*Scanner).Scan", Method, 0},
+		{"(Error).Error", Method, 0},
+		{"(ErrorList).Err", Method, 0},
+		{"(ErrorList).Error", Method, 0},
+		{"(ErrorList).Len", Method, 0},
+		{"(ErrorList).Less", Method, 0},
+		{"(ErrorList).Sort", Method, 0},
+		{"(ErrorList).Swap", Method, 0},
+		{"Error", Type, 0},
+		{"Error.Msg", Field, 0},
+		{"Error.Pos", Field, 0},
+		{"ErrorHandler", Type, 0},
+		{"ErrorList", Type, 0},
+		{"Mode", Type, 0},
+		{"PrintError", Func, 0},
+		{"ScanComments", Const, 0},
+		{"Scanner", Type, 0},
+		{"Scanner.ErrorCount", Field, 0},
+	},
+	"go/token": {
+		{"(*File).AddLine", Method, 0},
+		{"(*File).AddLineColumnInfo", Method, 11},
+		{"(*File).AddLineInfo", Method, 0},
+		{"(*File).Base", Method, 0},
+		{"(*File).Line", Method, 0},
+		{"(*File).LineCount", Method, 0},
+		{"(*File).LineStart", Method, 12},
+		{"(*File).Lines", Method, 21},
+		{"(*File).MergeLine", Method, 2},
+		{"(*File).Name", Method, 0},
+		{"(*File).Offset", Method, 0},
+		{"(*File).Pos", Method, 0},
+		{"(*File).Position", Method, 0},
+		{"(*File).PositionFor", Method, 4},
+		{"(*File).SetLines", Method, 0},
+		{"(*File).SetLinesForContent", Method, 0},
+		{"(*File).Size", Method, 0},
+		{"(*FileSet).AddFile", Method, 0},
+		{"(*FileSet).Base", Method, 0},
+		{"(*FileSet).File", Method, 0},
+		{"(*FileSet).Iterate", Method, 0},
+		{"(*FileSet).Position", Method, 0},
+		{"(*FileSet).PositionFor", Method, 4},
+		{"(*FileSet).Read", Method, 0},
+		{"(*FileSet).RemoveFile", Method, 20},
+		{"(*FileSet).Write", Method, 0},
+		{"(*Position).IsValid", Method, 0},
+		{"(Pos).IsValid", Method, 0},
+		{"(Position).String", Method, 0},
+		{"(Token).IsKeyword", Method, 0},
+		{"(Token).IsLiteral", Method, 0},
+		{"(Token).IsOperator", Method, 0},
+		{"(Token).Precedence", Method, 0},
+		{"(Token).String", Method, 0},
+		{"ADD", Const, 0},
+		{"ADD_ASSIGN", Const, 0},
+		{"AND", Const, 0},
+		{"AND_ASSIGN", Const, 0},
+		{"AND_NOT", Const, 0},
+		{"AND_NOT_ASSIGN", Const, 0},
+		{"ARROW", Const, 0},
+		{"ASSIGN", Const, 0},
+		{"BREAK", Const, 0},
+		{"CASE", Const, 0},
+		{"CHAN", Const, 0},
+		{"CHAR", Const, 0},
+		{"COLON", Const, 0},
+		{"COMMA", Const, 0},
+		{"COMMENT", Const, 0},
+		{"CONST", Const, 0},
+		{"CONTINUE", Const, 0},
+		{"DEC", Const, 0},
+		{"DEFAULT", Const, 0},
+		{"DEFER", Const, 0},
+		{"DEFINE", Const, 0},
+		{"ELLIPSIS", Const, 0},
+		{"ELSE", Const, 0},
+		{"EOF", Const, 0},
+		{"EQL", Const, 0},
+		{"FALLTHROUGH", Const, 0},
+		{"FLOAT", Const, 0},
+		{"FOR", Const, 0},
+		{"FUNC", Const, 0},
+		{"File", Type, 0},
+		{"FileSet", Type, 0},
+		{"GEQ", Const, 0},
+		{"GO", Const, 0},
+		{"GOTO", Const, 0},
+		{"GTR", Const, 0},
+		{"HighestPrec", Const, 0},
+		{"IDENT", Const, 0},
+		{"IF", Const, 0},
+		{"ILLEGAL", Const, 0},
+		{"IMAG", Const, 0},
+		{"IMPORT", Const, 0},
+		{"INC", Const, 0},
+		{"INT", Const, 0},
+		{"INTERFACE", Const, 0},
+		{"IsExported", Func, 13},
+		{"IsIdentifier", Func, 13},
+		{"IsKeyword", Func, 13},
+		{"LAND", Const, 0},
+		{"LBRACE", Const, 0},
+		{"LBRACK", Const, 0},
+		{"LEQ", Const, 0},
+		{"LOR", Const, 0},
+		{"LPAREN", Const, 0},
+		{"LSS", Const, 0},
+		{"Lookup", Func, 0},
+		{"LowestPrec", Const, 0},
+		{"MAP", Const, 0},
+		{"MUL", Const, 0},
+		{"MUL_ASSIGN", Const, 0},
+		{"NEQ", Const, 0},
+		{"NOT", Const, 0},
+		{"NewFileSet", Func, 0},
+		{"NoPos", Const, 0},
+		{"OR", Const, 0},
+		{"OR_ASSIGN", Const, 0},
+		{"PACKAGE", Const, 0},
+		{"PERIOD", Const, 0},
+		{"Pos", Type, 0},
+		{"Position", Type, 0},
+		{"Position.Column", Field, 0},
+		{"Position.Filename", Field, 0},
+		{"Position.Line", Field, 0},
+		{"Position.Offset", Field, 0},
+		{"QUO", Const, 0},
+		{"QUO_ASSIGN", Const, 0},
+		{"RANGE", Const, 0},
+		{"RBRACE", Const, 0},
+		{"RBRACK", Const, 0},
+		{"REM", Const, 0},
+		{"REM_ASSIGN", Const, 0},
+		{"RETURN", Const, 0},
+		{"RPAREN", Const, 0},
+		{"SELECT", Const, 0},
+		{"SEMICOLON", Const, 0},
+		{"SHL", Const, 0},
+		{"SHL_ASSIGN", Const, 0},
+		{"SHR", Const, 0},
+		{"SHR_ASSIGN", Const, 0},
+		{"STRING", Const, 0},
+		{"STRUCT", Const, 0},
+		{"SUB", Const, 0},
+		{"SUB_ASSIGN", Const, 0},
+		{"SWITCH", Const, 0},
+		{"TILDE", Const, 18},
+		{"TYPE", Const, 0},
+		{"Token", Type, 0},
+		{"UnaryPrec", Const, 0},
+		{"VAR", Const, 0},
+		{"XOR", Const, 0},
+		{"XOR_ASSIGN", Const, 0},
+	},
+	"go/types": {
+		{"(*Alias).Obj", Method, 22},
+		{"(*Alias).Origin", Method, 23},
+		{"(*Alias).Rhs", Method, 23},
+		{"(*Alias).SetTypeParams", Method, 23},
+		{"(*Alias).String", Method, 22},
+		{"(*Alias).TypeArgs", Method, 23},
+		{"(*Alias).TypeParams", Method, 23},
+		{"(*Alias).Underlying", Method, 22},
+		{"(*ArgumentError).Error", Method, 18},
+		{"(*ArgumentError).Unwrap", Method, 18},
+		{"(*Array).Elem", Method, 5},
+		{"(*Array).Len", Method, 5},
+		{"(*Array).String", Method, 5},
+		{"(*Array).Underlying", Method, 5},
+		{"(*Basic).Info", Method, 5},
+		{"(*Basic).Kind", Method, 5},
+		{"(*Basic).Name", Method, 5},
+		{"(*Basic).String", Method, 5},
+		{"(*Basic).Underlying", Method, 5},
+		{"(*Builtin).Exported", Method, 5},
+		{"(*Builtin).Id", Method, 5},
+		{"(*Builtin).Name", Method, 5},
+		{"(*Builtin).Parent", Method, 5},
+		{"(*Builtin).Pkg", Method, 5},
+		{"(*Builtin).Pos", Method, 5},
+		{"(*Builtin).String", Method, 5},
+		{"(*Builtin).Type", Method, 5},
+		{"(*Chan).Dir", Method, 5},
+		{"(*Chan).Elem", Method, 5},
+		{"(*Chan).String", Method, 5},
+		{"(*Chan).Underlying", Method, 5},
+		{"(*Checker).Files", Method, 5},
+		{"(*Config).Check", Method, 5},
+		{"(*Const).Exported", Method, 5},
+		{"(*Const).Id", Method, 5},
+		{"(*Const).Name", Method, 5},
+		{"(*Const).Parent", Method, 5},
+		{"(*Const).Pkg", Method, 5},
+		{"(*Const).Pos", Method, 5},
+		{"(*Const).String", Method, 5},
+		{"(*Const).Type", Method, 5},
+		{"(*Const).Val", Method, 5},
+		{"(*Func).Exported", Method, 5},
+		{"(*Func).FullName", Method, 5},
+		{"(*Func).Id", Method, 5},
+		{"(*Func).Name", Method, 5},
+		{"(*Func).Origin", Method, 19},
+		{"(*Func).Parent", Method, 5},
+		{"(*Func).Pkg", Method, 5},
+		{"(*Func).Pos", Method, 5},
+		{"(*Func).Scope", Method, 5},
+		{"(*Func).Signature", Method, 23},
+		{"(*Func).String", Method, 5},
+		{"(*Func).Type", Method, 5},
+		{"(*Info).ObjectOf", Method, 5},
+		{"(*Info).PkgNameOf", Method, 22},
+		{"(*Info).TypeOf", Method, 5},
+		{"(*Initializer).String", Method, 5},
+		{"(*Interface).Complete", Method, 5},
+		{"(*Interface).Embedded", Method, 5},
+		{"(*Interface).EmbeddedType", Method, 11},
+		{"(*Interface).EmbeddedTypes", Method, 24},
+		{"(*Interface).Empty", Method, 5},
+		{"(*Interface).ExplicitMethod", Method, 5},
+		{"(*Interface).ExplicitMethods", Method, 24},
+		{"(*Interface).IsComparable", Method, 18},
+		{"(*Interface).IsImplicit", Method, 18},
+		{"(*Interface).IsMethodSet", Method, 18},
+		{"(*Interface).MarkImplicit", Method, 18},
+		{"(*Interface).Method", Method, 5},
+		{"(*Interface).Methods", Method, 24},
+		{"(*Interface).NumEmbeddeds", Method, 5},
+		{"(*Interface).NumExplicitMethods", Method, 5},
+		{"(*Interface).NumMethods", Method, 5},
+		{"(*Interface).String", Method, 5},
+		{"(*Interface).Underlying", Method, 5},
+		{"(*Label).Exported", Method, 5},
+		{"(*Label).Id", Method, 5},
+		{"(*Label).Name", Method, 5},
+		{"(*Label).Parent", Method, 5},
+		{"(*Label).Pkg", Method, 5},
+		{"(*Label).Pos", Method, 5},
+		{"(*Label).String", Method, 5},
+		{"(*Label).Type", Method, 5},
+		{"(*Map).Elem", Method, 5},
+		{"(*Map).Key", Method, 5},
+		{"(*Map).String", Method, 5},
+		{"(*Map).Underlying", Method, 5},
+		{"(*MethodSet).At", Method, 5},
+		{"(*MethodSet).Len", Method, 5},
+		{"(*MethodSet).Lookup", Method, 5},
+		{"(*MethodSet).Methods", Method, 24},
+		{"(*MethodSet).String", Method, 5},
+		{"(*Named).AddMethod", Method, 5},
+		{"(*Named).Method", Method, 5},
+		{"(*Named).Methods", Method, 24},
+		{"(*Named).NumMethods", Method, 5},
+		{"(*Named).Obj", Method, 5},
+		{"(*Named).Origin", Method, 18},
+		{"(*Named).SetTypeParams", Method, 18},
+		{"(*Named).SetUnderlying", Method, 5},
+		{"(*Named).String", Method, 5},
+		{"(*Named).TypeArgs", Method, 18},
+		{"(*Named).TypeParams", Method, 18},
+		{"(*Named).Underlying", Method, 5},
+		{"(*Nil).Exported", Method, 5},
+		{"(*Nil).Id", Method, 5},
+		{"(*Nil).Name", Method, 5},
+		{"(*Nil).Parent", Method, 5},
+		{"(*Nil).Pkg", Method, 5},
+		{"(*Nil).Pos", Method, 5},
+		{"(*Nil).String", Method, 5},
+		{"(*Nil).Type", Method, 5},
+		{"(*Package).Complete", Method, 5},
+		{"(*Package).GoVersion", Method, 21},
+		{"(*Package).Imports", Method, 5},
+		{"(*Package).MarkComplete", Method, 5},
+		{"(*Package).Name", Method, 5},
+		{"(*Package).Path", Method, 5},
+		{"(*Package).Scope", Method, 5},
+		{"(*Package).SetImports", Method, 5},
+		{"(*Package).SetName", Method, 6},
+		{"(*Package).String", Method, 5},
+		{"(*PkgName).Exported", Method, 5},
+		{"(*PkgName).Id", Method, 5},
+		{"(*PkgName).Imported", Method, 5},
+		{"(*PkgName).Name", Method, 5},
+		{"(*PkgName).Parent", Method, 5},
+		{"(*PkgName).Pkg", Method, 5},
+		{"(*PkgName).Pos", Method, 5},
+		{"(*PkgName).String", Method, 5},
+		{"(*PkgName).Type", Method, 5},
+		{"(*Pointer).Elem", Method, 5},
+		{"(*Pointer).String", Method, 5},
+		{"(*Pointer).Underlying", Method, 5},
+		{"(*Scope).Child", Method, 5},
+		{"(*Scope).Children", Method, 24},
+		{"(*Scope).Contains", Method, 5},
+		{"(*Scope).End", Method, 5},
+		{"(*Scope).Innermost", Method, 5},
+		{"(*Scope).Insert", Method, 5},
+		{"(*Scope).Len", Method, 5},
+		{"(*Scope).Lookup", Method, 5},
+		{"(*Scope).LookupParent", Method, 5},
+		{"(*Scope).Names", Method, 5},
+		{"(*Scope).NumChildren", Method, 5},
+		{"(*Scope).Parent", Method, 5},
+		{"(*Scope).Pos", Method, 5},
+		{"(*Scope).String", Method, 5},
+		{"(*Scope).WriteTo", Method, 5},
+		{"(*Selection).Index", Method, 5},
+		{"(*Selection).Indirect", Method, 5},
+		{"(*Selection).Kind", Method, 5},
+		{"(*Selection).Obj", Method, 5},
+		{"(*Selection).Recv", Method, 5},
+		{"(*Selection).String", Method, 5},
+		{"(*Selection).Type", Method, 5},
+		{"(*Signature).Params", Method, 5},
+		{"(*Signature).Recv", Method, 5},
+		{"(*Signature).RecvTypeParams", Method, 18},
+		{"(*Signature).Results", Method, 5},
+		{"(*Signature).String", Method, 5},
+		{"(*Signature).TypeParams", Method, 18},
+		{"(*Signature).Underlying", Method, 5},
+		{"(*Signature).Variadic", Method, 5},
+		{"(*Slice).Elem", Method, 5},
+		{"(*Slice).String", Method, 5},
+		{"(*Slice).Underlying", Method, 5},
+		{"(*StdSizes).Alignof", Method, 5},
+		{"(*StdSizes).Offsetsof", Method, 5},
+		{"(*StdSizes).Sizeof", Method, 5},
+		{"(*Struct).Field", Method, 5},
+		{"(*Struct).Fields", Method, 24},
+		{"(*Struct).NumFields", Method, 5},
+		{"(*Struct).String", Method, 5},
+		{"(*Struct).Tag", Method, 5},
+		{"(*Struct).Underlying", Method, 5},
+		{"(*Term).String", Method, 18},
+		{"(*Term).Tilde", Method, 18},
+		{"(*Term).Type", Method, 18},
+		{"(*Tuple).At", Method, 5},
+		{"(*Tuple).Len", Method, 5},
+		{"(*Tuple).String", Method, 5},
+		{"(*Tuple).Underlying", Method, 5},
+		{"(*Tuple).Variables", Method, 24},
+		{"(*TypeList).At", Method, 18},
+		{"(*TypeList).Len", Method, 18},
+		{"(*TypeList).Types", Method, 24},
+		{"(*TypeName).Exported", Method, 5},
+		{"(*TypeName).Id", Method, 5},
+		{"(*TypeName).IsAlias", Method, 9},
+		{"(*TypeName).Name", Method, 5},
+		{"(*TypeName).Parent", Method, 5},
+		{"(*TypeName).Pkg", Method, 5},
+		{"(*TypeName).Pos", Method, 5},
+		{"(*TypeName).String", Method, 5},
+		{"(*TypeName).Type", Method, 5},
+		{"(*TypeParam).Constraint", Method, 18},
+		{"(*TypeParam).Index", Method, 18},
+		{"(*TypeParam).Obj", Method, 18},
+		{"(*TypeParam).SetConstraint", Method, 18},
+		{"(*TypeParam).String", Method, 18},
+		{"(*TypeParam).Underlying", Method, 18},
+		{"(*TypeParamList).At", Method, 18},
+		{"(*TypeParamList).Len", Method, 18},
+		{"(*TypeParamList).TypeParams", Method, 24},
+		{"(*Union).Len", Method, 18},
+		{"(*Union).String", Method, 18},
+		{"(*Union).Term", Method, 18},
+		{"(*Union).Terms", Method, 24},
+		{"(*Union).Underlying", Method, 18},
+		{"(*Var).Anonymous", Method, 5},
+		{"(*Var).Embedded", Method, 11},
+		{"(*Var).Exported", Method, 5},
+		{"(*Var).Id", Method, 5},
+		{"(*Var).IsField", Method, 5},
+		{"(*Var).Name", Method, 5},
+		{"(*Var).Origin", Method, 19},
+		{"(*Var).Parent", Method, 5},
+		{"(*Var).Pkg", Method, 5},
+		{"(*Var).Pos", Method, 5},
+		{"(*Var).String", Method, 5},
+		{"(*Var).Type", Method, 5},
+		{"(Checker).ObjectOf", Method, 5},
+		{"(Checker).PkgNameOf", Method, 22},
+		{"(Checker).TypeOf", Method, 5},
+		{"(Error).Error", Method, 5},
+		{"(TypeAndValue).Addressable", Method, 5},
+		{"(TypeAndValue).Assignable", Method, 5},
+		{"(TypeAndValue).HasOk", Method, 5},
+		{"(TypeAndValue).IsBuiltin", Method, 5},
+		{"(TypeAndValue).IsNil", Method, 5},
+		{"(TypeAndValue).IsType", Method, 5},
+		{"(TypeAndValue).IsValue", Method, 5},
+		{"(TypeAndValue).IsVoid", Method, 5},
+		{"Alias", Type, 22},
+		{"ArgumentError", Type, 18},
+		{"ArgumentError.Err", Field, 18},
+		{"ArgumentError.Index", Field, 18},
+		{"Array", Type, 5},
+		{"AssertableTo", Func, 5},
+		{"AssignableTo", Func, 5},
+		{"Basic", Type, 5},
+		{"BasicInfo", Type, 5},
+		{"BasicKind", Type, 5},
+		{"Bool", Const, 5},
+		{"Builtin", Type, 5},
+		{"Byte", Const, 5},
+		{"Chan", Type, 5},
+		{"ChanDir", Type, 5},
+		{"CheckExpr", Func, 13},
+		{"Checker", Type, 5},
+		{"Checker.Info", Field, 5},
+		{"Comparable", Func, 5},
+		{"Complex128", Const, 5},
+		{"Complex64", Const, 5},
+		{"Config", Type, 5},
+		{"Config.Context", Field, 18},
+		{"Config.DisableUnusedImportCheck", Field, 5},
+		{"Config.Error", Field, 5},
+		{"Config.FakeImportC", Field, 5},
+		{"Config.GoVersion", Field, 18},
+		{"Config.IgnoreFuncBodies", Field, 5},
+		{"Config.Importer", Field, 5},
+		{"Config.Sizes", Field, 5},
+		{"Const", Type, 5},
+		{"Context", Type, 18},
+		{"ConvertibleTo", Func, 5},
+		{"DefPredeclaredTestFuncs", Func, 5},
+		{"Default", Func, 8},
+		{"Error", Type, 5},
+		{"Error.Fset", Field, 5},
+		{"Error.Msg", Field, 5},
+		{"Error.Pos", Field, 5},
+		{"Error.Soft", Field, 5},
+		{"Eval", Func, 5},
+		{"ExprString", Func, 5},
+		{"FieldVal", Const, 5},
+		{"Float32", Const, 5},
+		{"Float64", Const, 5},
+		{"Func", Type, 5},
+		{"Id", Func, 5},
+		{"Identical", Func, 5},
+		{"IdenticalIgnoreTags", Func, 8},
+		{"Implements", Func, 5},
+		{"ImportMode", Type, 6},
+		{"Importer", Type, 5},
+		{"ImporterFrom", Type, 6},
+		{"Info", Type, 5},
+		{"Info.Defs", Field, 5},
+		{"Info.FileVersions", Field, 22},
+		{"Info.Implicits", Field, 5},
+		{"Info.InitOrder", Field, 5},
+		{"Info.Instances", Field, 18},
+		{"Info.Scopes", Field, 5},
+		{"Info.Selections", Field, 5},
+		{"Info.Types", Field, 5},
+		{"Info.Uses", Field, 5},
+		{"Initializer", Type, 5},
+		{"Initializer.Lhs", Field, 5},
+		{"Initializer.Rhs", Field, 5},
+		{"Instance", Type, 18},
+		{"Instance.Type", Field, 18},
+		{"Instance.TypeArgs", Field, 18},
+		{"Instantiate", Func, 18},
+		{"Int", Const, 5},
+		{"Int16", Const, 5},
+		{"Int32", Const, 5},
+		{"Int64", Const, 5},
+		{"Int8", Const, 5},
+		{"Interface", Type, 5},
+		{"Invalid", Const, 5},
+		{"IsBoolean", Const, 5},
+		{"IsComplex", Const, 5},
+		{"IsConstType", Const, 5},
+		{"IsFloat", Const, 5},
+		{"IsInteger", Const, 5},
+		{"IsInterface", Func, 5},
+		{"IsNumeric", Const, 5},
+		{"IsOrdered", Const, 5},
+		{"IsString", Const, 5},
+		{"IsUnsigned", Const, 5},
+		{"IsUntyped", Const, 5},
+		{"Label", Type, 5},
+		{"LookupFieldOrMethod", Func, 5},
+		{"Map", Type, 5},
+		{"MethodExpr", Const, 5},
+		{"MethodSet", Type, 5},
+		{"MethodVal", Const, 5},
+		{"MissingMethod", Func, 5},
+		{"Named", Type, 5},
+		{"NewAlias", Func, 22},
+		{"NewArray", Func, 5},
+		{"NewChan", Func, 5},
+		{"NewChecker", Func, 5},
+		{"NewConst", Func, 5},
+		{"NewContext", Func, 18},
+		{"NewField", Func, 5},
+		{"NewFunc", Func, 5},
+		{"NewInterface", Func, 5},
+		{"NewInterfaceType", Func, 11},
+		{"NewLabel", Func, 5},
+		{"NewMap", Func, 5},
+		{"NewMethodSet", Func, 5},
+		{"NewNamed", Func, 5},
+		{"NewPackage", Func, 5},
+		{"NewParam", Func, 5},
+		{"NewPkgName", Func, 5},
+		{"NewPointer", Func, 5},
+		{"NewScope", Func, 5},
+		{"NewSignature", Func, 5},
+		{"NewSignatureType", Func, 18},
+		{"NewSlice", Func, 5},
+		{"NewStruct", Func, 5},
+		{"NewTerm", Func, 18},
+		{"NewTuple", Func, 5},
+		{"NewTypeName", Func, 5},
+		{"NewTypeParam", Func, 18},
+		{"NewUnion", Func, 18},
+		{"NewVar", Func, 5},
+		{"Nil", Type, 5},
+		{"Object", Type, 5},
+		{"ObjectString", Func, 5},
+		{"Package", Type, 5},
+		{"PkgName", Type, 5},
+		{"Pointer", Type, 5},
+		{"Qualifier", Type, 5},
+		{"RecvOnly", Const, 5},
+		{"RelativeTo", Func, 5},
+		{"Rune", Const, 5},
+		{"Satisfies", Func, 20},
+		{"Scope", Type, 5},
+		{"Selection", Type, 5},
+		{"SelectionKind", Type, 5},
+		{"SelectionString", Func, 5},
+		{"SendOnly", Const, 5},
+		{"SendRecv", Const, 5},
+		{"Signature", Type, 5},
+		{"Sizes", Type, 5},
+		{"SizesFor", Func, 9},
+		{"Slice", Type, 5},
+		{"StdSizes", Type, 5},
+		{"StdSizes.MaxAlign", Field, 5},
+		{"StdSizes.WordSize", Field, 5},
+		{"String", Const, 5},
+		{"Struct", Type, 5},
+		{"Term", Type, 18},
+		{"Tuple", Type, 5},
+		{"Typ", Var, 5},
+		{"Type", Type, 5},
+		{"TypeAndValue", Type, 5},
+		{"TypeAndValue.Type", Field, 5},
+		{"TypeAndValue.Value", Field, 5},
+		{"TypeList", Type, 18},
+		{"TypeName", Type, 5},
+		{"TypeParam", Type, 18},
+		{"TypeParamList", Type, 18},
+		{"TypeString", Func, 5},
+		{"Uint", Const, 5},
+		{"Uint16", Const, 5},
+		{"Uint32", Const, 5},
+		{"Uint64", Const, 5},
+		{"Uint8", Const, 5},
+		{"Uintptr", Const, 5},
+		{"Unalias", Func, 22},
+		{"Union", Type, 18},
+		{"Universe", Var, 5},
+		{"Unsafe", Var, 5},
+		{"UnsafePointer", Const, 5},
+		{"UntypedBool", Const, 5},
+		{"UntypedComplex", Const, 5},
+		{"UntypedFloat", Const, 5},
+		{"UntypedInt", Const, 5},
+		{"UntypedNil", Const, 5},
+		{"UntypedRune", Const, 5},
+		{"UntypedString", Const, 5},
+		{"Var", Type, 5},
+		{"WriteExpr", Func, 5},
+		{"WriteSignature", Func, 5},
+		{"WriteType", Func, 5},
+	},
+	"go/version": {
+		{"Compare", Func, 22},
+		{"IsValid", Func, 22},
+		{"Lang", Func, 22},
+	},
+	"hash": {
+		{"Hash", Type, 0},
+		{"Hash32", Type, 0},
+		{"Hash64", Type, 0},
+	},
+	"hash/adler32": {
+		{"Checksum", Func, 0},
+		{"New", Func, 0},
+		{"Size", Const, 0},
+	},
+	"hash/crc32": {
+		{"Castagnoli", Const, 0},
+		{"Checksum", Func, 0},
+		{"ChecksumIEEE", Func, 0},
+		{"IEEE", Const, 0},
+		{"IEEETable", Var, 0},
+		{"Koopman", Const, 0},
+		{"MakeTable", Func, 0},
+		{"New", Func, 0},
+		{"NewIEEE", Func, 0},
+		{"Size", Const, 0},
+		{"Table", Type, 0},
+		{"Update", Func, 0},
+	},
+	"hash/crc64": {
+		{"Checksum", Func, 0},
+		{"ECMA", Const, 0},
+		{"ISO", Const, 0},
+		{"MakeTable", Func, 0},
+		{"New", Func, 0},
+		{"Size", Const, 0},
+		{"Table", Type, 0},
+		{"Update", Func, 0},
+	},
+	"hash/fnv": {
+		{"New128", Func, 9},
+		{"New128a", Func, 9},
+		{"New32", Func, 0},
+		{"New32a", Func, 0},
+		{"New64", Func, 0},
+		{"New64a", Func, 0},
+	},
+	"hash/maphash": {
+		{"(*Hash).BlockSize", Method, 14},
+		{"(*Hash).Reset", Method, 14},
+		{"(*Hash).Seed", Method, 14},
+		{"(*Hash).SetSeed", Method, 14},
+		{"(*Hash).Size", Method, 14},
+		{"(*Hash).Sum", Method, 14},
+		{"(*Hash).Sum64", Method, 14},
+		{"(*Hash).Write", Method, 14},
+		{"(*Hash).WriteByte", Method, 14},
+		{"(*Hash).WriteString", Method, 14},
+		{"Bytes", Func, 19},
+		{"Comparable", Func, 24},
+		{"Hash", Type, 14},
+		{"MakeSeed", Func, 14},
+		{"Seed", Type, 14},
+		{"String", Func, 19},
+		{"WriteComparable", Func, 24},
+	},
+	"html": {
+		{"EscapeString", Func, 0},
+		{"UnescapeString", Func, 0},
+	},
+	"html/template": {
+		{"(*Error).Error", Method, 0},
+		{"(*Template).AddParseTree", Method, 0},
+		{"(*Template).Clone", Method, 0},
+		{"(*Template).DefinedTemplates", Method, 6},
+		{"(*Template).Delims", Method, 0},
+		{"(*Template).Execute", Method, 0},
+		{"(*Template).ExecuteTemplate", Method, 0},
+		{"(*Template).Funcs", Method, 0},
+		{"(*Template).Lookup", Method, 0},
+		{"(*Template).Name", Method, 0},
+		{"(*Template).New", Method, 0},
+		{"(*Template).Option", Method, 5},
+		{"(*Template).Parse", Method, 0},
+		{"(*Template).ParseFS", Method, 16},
+		{"(*Template).ParseFiles", Method, 0},
+		{"(*Template).ParseGlob", Method, 0},
+		{"(*Template).Templates", Method, 0},
+		{"CSS", Type, 0},
+		{"ErrAmbigContext", Const, 0},
+		{"ErrBadHTML", Const, 0},
+		{"ErrBranchEnd", Const, 0},
+		{"ErrEndContext", Const, 0},
+		{"ErrJSTemplate", Const, 21},
+		{"ErrNoSuchTemplate", Const, 0},
+		{"ErrOutputContext", Const, 0},
+		{"ErrPartialCharset", Const, 0},
+		{"ErrPartialEscape", Const, 0},
+		{"ErrPredefinedEscaper", Const, 9},
+		{"ErrRangeLoopReentry", Const, 0},
+		{"ErrSlashAmbig", Const, 0},
+		{"Error", Type, 0},
+		{"Error.Description", Field, 0},
+		{"Error.ErrorCode", Field, 0},
+		{"Error.Line", Field, 0},
+		{"Error.Name", Field, 0},
+		{"Error.Node", Field, 4},
+		{"ErrorCode", Type, 0},
+		{"FuncMap", Type, 0},
+		{"HTML", Type, 0},
+		{"HTMLAttr", Type, 0},
+		{"HTMLEscape", Func, 0},
+		{"HTMLEscapeString", Func, 0},
+		{"HTMLEscaper", Func, 0},
+		{"IsTrue", Func, 6},
+		{"JS", Type, 0},
+		{"JSEscape", Func, 0},
+		{"JSEscapeString", Func, 0},
+		{"JSEscaper", Func, 0},
+		{"JSStr", Type, 0},
+		{"Must", Func, 0},
+		{"New", Func, 0},
+		{"OK", Const, 0},
+		{"ParseFS", Func, 16},
+		{"ParseFiles", Func, 0},
+		{"ParseGlob", Func, 0},
+		{"Srcset", Type, 10},
+		{"Template", Type, 0},
+		{"Template.Tree", Field, 2},
+		{"URL", Type, 0},
+		{"URLQueryEscaper", Func, 0},
+	},
+	"image": {
+		{"(*Alpha).AlphaAt", Method, 4},
+		{"(*Alpha).At", Method, 0},
+		{"(*Alpha).Bounds", Method, 0},
+		{"(*Alpha).ColorModel", Method, 0},
+		{"(*Alpha).Opaque", Method, 0},
+		{"(*Alpha).PixOffset", Method, 0},
+		{"(*Alpha).RGBA64At", Method, 17},
+		{"(*Alpha).Set", Method, 0},
+		{"(*Alpha).SetAlpha", Method, 0},
+		{"(*Alpha).SetRGBA64", Method, 17},
+		{"(*Alpha).SubImage", Method, 0},
+		{"(*Alpha16).Alpha16At", Method, 4},
+		{"(*Alpha16).At", Method, 0},
+		{"(*Alpha16).Bounds", Method, 0},
+		{"(*Alpha16).ColorModel", Method, 0},
+		{"(*Alpha16).Opaque", Method, 0},
+		{"(*Alpha16).PixOffset", Method, 0},
+		{"(*Alpha16).RGBA64At", Method, 17},
+		{"(*Alpha16).Set", Method, 0},
+		{"(*Alpha16).SetAlpha16", Method, 0},
+		{"(*Alpha16).SetRGBA64", Method, 17},
+		{"(*Alpha16).SubImage", Method, 0},
+		{"(*CMYK).At", Method, 5},
+		{"(*CMYK).Bounds", Method, 5},
+		{"(*CMYK).CMYKAt", Method, 5},
+		{"(*CMYK).ColorModel", Method, 5},
+		{"(*CMYK).Opaque", Method, 5},
+		{"(*CMYK).PixOffset", Method, 5},
+		{"(*CMYK).RGBA64At", Method, 17},
+		{"(*CMYK).Set", Method, 5},
+		{"(*CMYK).SetCMYK", Method, 5},
+		{"(*CMYK).SetRGBA64", Method, 17},
+		{"(*CMYK).SubImage", Method, 5},
+		{"(*Gray).At", Method, 0},
+		{"(*Gray).Bounds", Method, 0},
+		{"(*Gray).ColorModel", Method, 0},
+		{"(*Gray).GrayAt", Method, 4},
+		{"(*Gray).Opaque", Method, 0},
+		{"(*Gray).PixOffset", Method, 0},
+		{"(*Gray).RGBA64At", Method, 17},
+		{"(*Gray).Set", Method, 0},
+		{"(*Gray).SetGray", Method, 0},
+		{"(*Gray).SetRGBA64", Method, 17},
+		{"(*Gray).SubImage", Method, 0},
+		{"(*Gray16).At", Method, 0},
+		{"(*Gray16).Bounds", Method, 0},
+		{"(*Gray16).ColorModel", Method, 0},
+		{"(*Gray16).Gray16At", Method, 4},
+		{"(*Gray16).Opaque", Method, 0},
+		{"(*Gray16).PixOffset", Method, 0},
+		{"(*Gray16).RGBA64At", Method, 17},
+		{"(*Gray16).Set", Method, 0},
+		{"(*Gray16).SetGray16", Method, 0},
+		{"(*Gray16).SetRGBA64", Method, 17},
+		{"(*Gray16).SubImage", Method, 0},
+		{"(*NRGBA).At", Method, 0},
+		{"(*NRGBA).Bounds", Method, 0},
+		{"(*NRGBA).ColorModel", Method, 0},
+		{"(*NRGBA).NRGBAAt", Method, 4},
+		{"(*NRGBA).Opaque", Method, 0},
+		{"(*NRGBA).PixOffset", Method, 0},
+		{"(*NRGBA).RGBA64At", Method, 17},
+		{"(*NRGBA).Set", Method, 0},
+		{"(*NRGBA).SetNRGBA", Method, 0},
+		{"(*NRGBA).SetRGBA64", Method, 17},
+		{"(*NRGBA).SubImage", Method, 0},
+		{"(*NRGBA64).At", Method, 0},
+		{"(*NRGBA64).Bounds", Method, 0},
+		{"(*NRGBA64).ColorModel", Method, 0},
+		{"(*NRGBA64).NRGBA64At", Method, 4},
+		{"(*NRGBA64).Opaque", Method, 0},
+		{"(*NRGBA64).PixOffset", Method, 0},
+		{"(*NRGBA64).RGBA64At", Method, 17},
+		{"(*NRGBA64).Set", Method, 0},
+		{"(*NRGBA64).SetNRGBA64", Method, 0},
+		{"(*NRGBA64).SetRGBA64", Method, 17},
+		{"(*NRGBA64).SubImage", Method, 0},
+		{"(*NYCbCrA).AOffset", Method, 6},
+		{"(*NYCbCrA).At", Method, 6},
+		{"(*NYCbCrA).Bounds", Method, 6},
+		{"(*NYCbCrA).COffset", Method, 6},
+		{"(*NYCbCrA).ColorModel", Method, 6},
+		{"(*NYCbCrA).NYCbCrAAt", Method, 6},
+		{"(*NYCbCrA).Opaque", Method, 6},
+		{"(*NYCbCrA).RGBA64At", Method, 17},
+		{"(*NYCbCrA).SubImage", Method, 6},
+		{"(*NYCbCrA).YCbCrAt", Method, 6},
+		{"(*NYCbCrA).YOffset", Method, 6},
+		{"(*Paletted).At", Method, 0},
+		{"(*Paletted).Bounds", Method, 0},
+		{"(*Paletted).ColorIndexAt", Method, 0},
+		{"(*Paletted).ColorModel", Method, 0},
+		{"(*Paletted).Opaque", Method, 0},
+		{"(*Paletted).PixOffset", Method, 0},
+		{"(*Paletted).RGBA64At", Method, 17},
+		{"(*Paletted).Set", Method, 0},
+		{"(*Paletted).SetColorIndex", Method, 0},
+		{"(*Paletted).SetRGBA64", Method, 17},
+		{"(*Paletted).SubImage", Method, 0},
+		{"(*RGBA).At", Method, 0},
+		{"(*RGBA).Bounds", Method, 0},
+		{"(*RGBA).ColorModel", Method, 0},
+		{"(*RGBA).Opaque", Method, 0},
+		{"(*RGBA).PixOffset", Method, 0},
+		{"(*RGBA).RGBA64At", Method, 17},
+		{"(*RGBA).RGBAAt", Method, 4},
+		{"(*RGBA).Set", Method, 0},
+		{"(*RGBA).SetRGBA", Method, 0},
+		{"(*RGBA).SetRGBA64", Method, 17},
+		{"(*RGBA).SubImage", Method, 0},
+		{"(*RGBA64).At", Method, 0},
+		{"(*RGBA64).Bounds", Method, 0},
+		{"(*RGBA64).ColorModel", Method, 0},
+		{"(*RGBA64).Opaque", Method, 0},
+		{"(*RGBA64).PixOffset", Method, 0},
+		{"(*RGBA64).RGBA64At", Method, 4},
+		{"(*RGBA64).Set", Method, 0},
+		{"(*RGBA64).SetRGBA64", Method, 0},
+		{"(*RGBA64).SubImage", Method, 0},
+		{"(*Uniform).At", Method, 0},
+		{"(*Uniform).Bounds", Method, 0},
+		{"(*Uniform).ColorModel", Method, 0},
+		{"(*Uniform).Convert", Method, 0},
+		{"(*Uniform).Opaque", Method, 0},
+		{"(*Uniform).RGBA", Method, 0},
+		{"(*Uniform).RGBA64At", Method, 17},
+		{"(*YCbCr).At", Method, 0},
+		{"(*YCbCr).Bounds", Method, 0},
+		{"(*YCbCr).COffset", Method, 0},
+		{"(*YCbCr).ColorModel", Method, 0},
+		{"(*YCbCr).Opaque", Method, 0},
+		{"(*YCbCr).RGBA64At", Method, 17},
+		{"(*YCbCr).SubImage", Method, 0},
+		{"(*YCbCr).YCbCrAt", Method, 4},
+		{"(*YCbCr).YOffset", Method, 0},
+		{"(Point).Add", Method, 0},
+		{"(Point).Div", Method, 0},
+		{"(Point).Eq", Method, 0},
+		{"(Point).In", Method, 0},
+		{"(Point).Mod", Method, 0},
+		{"(Point).Mul", Method, 0},
+		{"(Point).String", Method, 0},
+		{"(Point).Sub", Method, 0},
+		{"(Rectangle).Add", Method, 0},
+		{"(Rectangle).At", Method, 5},
+		{"(Rectangle).Bounds", Method, 5},
+		{"(Rectangle).Canon", Method, 0},
+		{"(Rectangle).ColorModel", Method, 5},
+		{"(Rectangle).Dx", Method, 0},
+		{"(Rectangle).Dy", Method, 0},
+		{"(Rectangle).Empty", Method, 0},
+		{"(Rectangle).Eq", Method, 0},
+		{"(Rectangle).In", Method, 0},
+		{"(Rectangle).Inset", Method, 0},
+		{"(Rectangle).Intersect", Method, 0},
+		{"(Rectangle).Overlaps", Method, 0},
+		{"(Rectangle).RGBA64At", Method, 17},
+		{"(Rectangle).Size", Method, 0},
+		{"(Rectangle).String", Method, 0},
+		{"(Rectangle).Sub", Method, 0},
+		{"(Rectangle).Union", Method, 0},
+		{"(YCbCrSubsampleRatio).String", Method, 0},
+		{"Alpha", Type, 0},
+		{"Alpha.Pix", Field, 0},
+		{"Alpha.Rect", Field, 0},
+		{"Alpha.Stride", Field, 0},
+		{"Alpha16", Type, 0},
+		{"Alpha16.Pix", Field, 0},
+		{"Alpha16.Rect", Field, 0},
+		{"Alpha16.Stride", Field, 0},
+		{"Black", Var, 0},
+		{"CMYK", Type, 5},
+		{"CMYK.Pix", Field, 5},
+		{"CMYK.Rect", Field, 5},
+		{"CMYK.Stride", Field, 5},
+		{"Config", Type, 0},
+		{"Config.ColorModel", Field, 0},
+		{"Config.Height", Field, 0},
+		{"Config.Width", Field, 0},
+		{"Decode", Func, 0},
+		{"DecodeConfig", Func, 0},
+		{"ErrFormat", Var, 0},
+		{"Gray", Type, 0},
+		{"Gray.Pix", Field, 0},
+		{"Gray.Rect", Field, 0},
+		{"Gray.Stride", Field, 0},
+		{"Gray16", Type, 0},
+		{"Gray16.Pix", Field, 0},
+		{"Gray16.Rect", Field, 0},
+		{"Gray16.Stride", Field, 0},
+		{"Image", Type, 0},
+		{"NRGBA", Type, 0},
+		{"NRGBA.Pix", Field, 0},
+		{"NRGBA.Rect", Field, 0},
+		{"NRGBA.Stride", Field, 0},
+		{"NRGBA64", Type, 0},
+		{"NRGBA64.Pix", Field, 0},
+		{"NRGBA64.Rect", Field, 0},
+		{"NRGBA64.Stride", Field, 0},
+		{"NYCbCrA", Type, 6},
+		{"NYCbCrA.A", Field, 6},
+		{"NYCbCrA.AStride", Field, 6},
+		{"NYCbCrA.YCbCr", Field, 6},
+		{"NewAlpha", Func, 0},
+		{"NewAlpha16", Func, 0},
+		{"NewCMYK", Func, 5},
+		{"NewGray", Func, 0},
+		{"NewGray16", Func, 0},
+		{"NewNRGBA", Func, 0},
+		{"NewNRGBA64", Func, 0},
+		{"NewNYCbCrA", Func, 6},
+		{"NewPaletted", Func, 0},
+		{"NewRGBA", Func, 0},
+		{"NewRGBA64", Func, 0},
+		{"NewUniform", Func, 0},
+		{"NewYCbCr", Func, 0},
+		{"Opaque", Var, 0},
+		{"Paletted", Type, 0},
+		{"Paletted.Palette", Field, 0},
+		{"Paletted.Pix", Field, 0},
+		{"Paletted.Rect", Field, 0},
+		{"Paletted.Stride", Field, 0},
+		{"PalettedImage", Type, 0},
+		{"Point", Type, 0},
+		{"Point.X", Field, 0},
+		{"Point.Y", Field, 0},
+		{"Pt", Func, 0},
+		{"RGBA", Type, 0},
+		{"RGBA.Pix", Field, 0},
+		{"RGBA.Rect", Field, 0},
+		{"RGBA.Stride", Field, 0},
+		{"RGBA64", Type, 0},
+		{"RGBA64.Pix", Field, 0},
+		{"RGBA64.Rect", Field, 0},
+		{"RGBA64.Stride", Field, 0},
+		{"RGBA64Image", Type, 17},
+		{"Rect", Func, 0},
+		{"Rectangle", Type, 0},
+		{"Rectangle.Max", Field, 0},
+		{"Rectangle.Min", Field, 0},
+		{"RegisterFormat", Func, 0},
+		{"Transparent", Var, 0},
+		{"Uniform", Type, 0},
+		{"Uniform.C", Field, 0},
+		{"White", Var, 0},
+		{"YCbCr", Type, 0},
+		{"YCbCr.CStride", Field, 0},
+		{"YCbCr.Cb", Field, 0},
+		{"YCbCr.Cr", Field, 0},
+		{"YCbCr.Rect", Field, 0},
+		{"YCbCr.SubsampleRatio", Field, 0},
+		{"YCbCr.Y", Field, 0},
+		{"YCbCr.YStride", Field, 0},
+		{"YCbCrSubsampleRatio", Type, 0},
+		{"YCbCrSubsampleRatio410", Const, 5},
+		{"YCbCrSubsampleRatio411", Const, 5},
+		{"YCbCrSubsampleRatio420", Const, 0},
+		{"YCbCrSubsampleRatio422", Const, 0},
+		{"YCbCrSubsampleRatio440", Const, 1},
+		{"YCbCrSubsampleRatio444", Const, 0},
+		{"ZP", Var, 0},
+		{"ZR", Var, 0},
+	},
+	"image/color": {
+		{"(Alpha).RGBA", Method, 0},
+		{"(Alpha16).RGBA", Method, 0},
+		{"(CMYK).RGBA", Method, 5},
+		{"(Gray).RGBA", Method, 0},
+		{"(Gray16).RGBA", Method, 0},
+		{"(NRGBA).RGBA", Method, 0},
+		{"(NRGBA64).RGBA", Method, 0},
+		{"(NYCbCrA).RGBA", Method, 6},
+		{"(Palette).Convert", Method, 0},
+		{"(Palette).Index", Method, 0},
+		{"(RGBA).RGBA", Method, 0},
+		{"(RGBA64).RGBA", Method, 0},
+		{"(YCbCr).RGBA", Method, 0},
+		{"Alpha", Type, 0},
+		{"Alpha.A", Field, 0},
+		{"Alpha16", Type, 0},
+		{"Alpha16.A", Field, 0},
+		{"Alpha16Model", Var, 0},
+		{"AlphaModel", Var, 0},
+		{"Black", Var, 0},
+		{"CMYK", Type, 5},
+		{"CMYK.C", Field, 5},
+		{"CMYK.K", Field, 5},
+		{"CMYK.M", Field, 5},
+		{"CMYK.Y", Field, 5},
+		{"CMYKModel", Var, 5},
+		{"CMYKToRGB", Func, 5},
+		{"Color", Type, 0},
+		{"Gray", Type, 0},
+		{"Gray.Y", Field, 0},
+		{"Gray16", Type, 0},
+		{"Gray16.Y", Field, 0},
+		{"Gray16Model", Var, 0},
+		{"GrayModel", Var, 0},
+		{"Model", Type, 0},
+		{"ModelFunc", Func, 0},
+		{"NRGBA", Type, 0},
+		{"NRGBA.A", Field, 0},
+		{"NRGBA.B", Field, 0},
+		{"NRGBA.G", Field, 0},
+		{"NRGBA.R", Field, 0},
+		{"NRGBA64", Type, 0},
+		{"NRGBA64.A", Field, 0},
+		{"NRGBA64.B", Field, 0},
+		{"NRGBA64.G", Field, 0},
+		{"NRGBA64.R", Field, 0},
+		{"NRGBA64Model", Var, 0},
+		{"NRGBAModel", Var, 0},
+		{"NYCbCrA", Type, 6},
+		{"NYCbCrA.A", Field, 6},
+		{"NYCbCrA.YCbCr", Field, 6},
+		{"NYCbCrAModel", Var, 6},
+		{"Opaque", Var, 0},
+		{"Palette", Type, 0},
+		{"RGBA", Type, 0},
+		{"RGBA.A", Field, 0},
+		{"RGBA.B", Field, 0},
+		{"RGBA.G", Field, 0},
+		{"RGBA.R", Field, 0},
+		{"RGBA64", Type, 0},
+		{"RGBA64.A", Field, 0},
+		{"RGBA64.B", Field, 0},
+		{"RGBA64.G", Field, 0},
+		{"RGBA64.R", Field, 0},
+		{"RGBA64Model", Var, 0},
+		{"RGBAModel", Var, 0},
+		{"RGBToCMYK", Func, 5},
+		{"RGBToYCbCr", Func, 0},
+		{"Transparent", Var, 0},
+		{"White", Var, 0},
+		{"YCbCr", Type, 0},
+		{"YCbCr.Cb", Field, 0},
+		{"YCbCr.Cr", Field, 0},
+		{"YCbCr.Y", Field, 0},
+		{"YCbCrModel", Var, 0},
+		{"YCbCrToRGB", Func, 0},
+	},
+	"image/color/palette": {
+		{"Plan9", Var, 2},
+		{"WebSafe", Var, 2},
+	},
+	"image/draw": {
+		{"(Op).Draw", Method, 2},
+		{"Draw", Func, 0},
+		{"DrawMask", Func, 0},
+		{"Drawer", Type, 2},
+		{"FloydSteinberg", Var, 2},
+		{"Image", Type, 0},
+		{"Op", Type, 0},
+		{"Over", Const, 0},
+		{"Quantizer", Type, 2},
+		{"RGBA64Image", Type, 17},
+		{"Src", Const, 0},
+	},
+	"image/gif": {
+		{"Decode", Func, 0},
+		{"DecodeAll", Func, 0},
+		{"DecodeConfig", Func, 0},
+		{"DisposalBackground", Const, 5},
+		{"DisposalNone", Const, 5},
+		{"DisposalPrevious", Const, 5},
+		{"Encode", Func, 2},
+		{"EncodeAll", Func, 2},
+		{"GIF", Type, 0},
+		{"GIF.BackgroundIndex", Field, 5},
+		{"GIF.Config", Field, 5},
+		{"GIF.Delay", Field, 0},
+		{"GIF.Disposal", Field, 5},
+		{"GIF.Image", Field, 0},
+		{"GIF.LoopCount", Field, 0},
+		{"Options", Type, 2},
+		{"Options.Drawer", Field, 2},
+		{"Options.NumColors", Field, 2},
+		{"Options.Quantizer", Field, 2},
+	},
+	"image/jpeg": {
+		{"(FormatError).Error", Method, 0},
+		{"(UnsupportedError).Error", Method, 0},
+		{"Decode", Func, 0},
+		{"DecodeConfig", Func, 0},
+		{"DefaultQuality", Const, 0},
+		{"Encode", Func, 0},
+		{"FormatError", Type, 0},
+		{"Options", Type, 0},
+		{"Options.Quality", Field, 0},
+		{"Reader", Type, 0},
+		{"UnsupportedError", Type, 0},
+	},
+	"image/png": {
+		{"(*Encoder).Encode", Method, 4},
+		{"(FormatError).Error", Method, 0},
+		{"(UnsupportedError).Error", Method, 0},
+		{"BestCompression", Const, 4},
+		{"BestSpeed", Const, 4},
+		{"CompressionLevel", Type, 4},
+		{"Decode", Func, 0},
+		{"DecodeConfig", Func, 0},
+		{"DefaultCompression", Const, 4},
+		{"Encode", Func, 0},
+		{"Encoder", Type, 4},
+		{"Encoder.BufferPool", Field, 9},
+		{"Encoder.CompressionLevel", Field, 4},
+		{"EncoderBuffer", Type, 9},
+		{"EncoderBufferPool", Type, 9},
+		{"FormatError", Type, 0},
+		{"NoCompression", Const, 4},
+		{"UnsupportedError", Type, 0},
+	},
+	"index/suffixarray": {
+		{"(*Index).Bytes", Method, 0},
+		{"(*Index).FindAllIndex", Method, 0},
+		{"(*Index).Lookup", Method, 0},
+		{"(*Index).Read", Method, 0},
+		{"(*Index).Write", Method, 0},
+		{"Index", Type, 0},
+		{"New", Func, 0},
+	},
+	"io": {
+		{"(*LimitedReader).Read", Method, 0},
+		{"(*OffsetWriter).Seek", Method, 20},
+		{"(*OffsetWriter).Write", Method, 20},
+		{"(*OffsetWriter).WriteAt", Method, 20},
+		{"(*PipeReader).Close", Method, 0},
+		{"(*PipeReader).CloseWithError", Method, 0},
+		{"(*PipeReader).Read", Method, 0},
+		{"(*PipeWriter).Close", Method, 0},
+		{"(*PipeWriter).CloseWithError", Method, 0},
+		{"(*PipeWriter).Write", Method, 0},
+		{"(*SectionReader).Outer", Method, 22},
+		{"(*SectionReader).Read", Method, 0},
+		{"(*SectionReader).ReadAt", Method, 0},
+		{"(*SectionReader).Seek", Method, 0},
+		{"(*SectionReader).Size", Method, 0},
+		{"ByteReader", Type, 0},
+		{"ByteScanner", Type, 0},
+		{"ByteWriter", Type, 1},
+		{"Closer", Type, 0},
+		{"Copy", Func, 0},
+		{"CopyBuffer", Func, 5},
+		{"CopyN", Func, 0},
+		{"Discard", Var, 16},
+		{"EOF", Var, 0},
+		{"ErrClosedPipe", Var, 0},
+		{"ErrNoProgress", Var, 1},
+		{"ErrShortBuffer", Var, 0},
+		{"ErrShortWrite", Var, 0},
+		{"ErrUnexpectedEOF", Var, 0},
+		{"LimitReader", Func, 0},
+		{"LimitedReader", Type, 0},
+		{"LimitedReader.N", Field, 0},
+		{"LimitedReader.R", Field, 0},
+		{"MultiReader", Func, 0},
+		{"MultiWriter", Func, 0},
+		{"NewOffsetWriter", Func, 20},
+		{"NewSectionReader", Func, 0},
+		{"NopCloser", Func, 16},
+		{"OffsetWriter", Type, 20},
+		{"Pipe", Func, 0},
+		{"PipeReader", Type, 0},
+		{"PipeWriter", Type, 0},
+		{"ReadAll", Func, 16},
+		{"ReadAtLeast", Func, 0},
+		{"ReadCloser", Type, 0},
+		{"ReadFull", Func, 0},
+		{"ReadSeekCloser", Type, 16},
+		{"ReadSeeker", Type, 0},
+		{"ReadWriteCloser", Type, 0},
+		{"ReadWriteSeeker", Type, 0},
+		{"ReadWriter", Type, 0},
+		{"Reader", Type, 0},
+		{"ReaderAt", Type, 0},
+		{"ReaderFrom", Type, 0},
+		{"RuneReader", Type, 0},
+		{"RuneScanner", Type, 0},
+		{"SectionReader", Type, 0},
+		{"SeekCurrent", Const, 7},
+		{"SeekEnd", Const, 7},
+		{"SeekStart", Const, 7},
+		{"Seeker", Type, 0},
+		{"StringWriter", Type, 12},
+		{"TeeReader", Func, 0},
+		{"WriteCloser", Type, 0},
+		{"WriteSeeker", Type, 0},
+		{"WriteString", Func, 0},
+		{"Writer", Type, 0},
+		{"WriterAt", Type, 0},
+		{"WriterTo", Type, 0},
+	},
+	"io/fs": {
+		{"(*PathError).Error", Method, 16},
+		{"(*PathError).Timeout", Method, 16},
+		{"(*PathError).Unwrap", Method, 16},
+		{"(FileMode).IsDir", Method, 16},
+		{"(FileMode).IsRegular", Method, 16},
+		{"(FileMode).Perm", Method, 16},
+		{"(FileMode).String", Method, 16},
+		{"(FileMode).Type", Method, 16},
+		{"DirEntry", Type, 16},
+		{"ErrClosed", Var, 16},
+		{"ErrExist", Var, 16},
+		{"ErrInvalid", Var, 16},
+		{"ErrNotExist", Var, 16},
+		{"ErrPermission", Var, 16},
+		{"FS", Type, 16},
+		{"File", Type, 16},
+		{"FileInfo", Type, 16},
+		{"FileInfoToDirEntry", Func, 17},
+		{"FileMode", Type, 16},
+		{"FormatDirEntry", Func, 21},
+		{"FormatFileInfo", Func, 21},
+		{"Glob", Func, 16},
+		{"GlobFS", Type, 16},
+		{"ModeAppend", Const, 16},
+		{"ModeCharDevice", Const, 16},
+		{"ModeDevice", Const, 16},
+		{"ModeDir", Const, 16},
+		{"ModeExclusive", Const, 16},
+		{"ModeIrregular", Const, 16},
+		{"ModeNamedPipe", Const, 16},
+		{"ModePerm", Const, 16},
+		{"ModeSetgid", Const, 16},
+		{"ModeSetuid", Const, 16},
+		{"ModeSocket", Const, 16},
+		{"ModeSticky", Const, 16},
+		{"ModeSymlink", Const, 16},
+		{"ModeTemporary", Const, 16},
+		{"ModeType", Const, 16},
+		{"PathError", Type, 16},
+		{"PathError.Err", Field, 16},
+		{"PathError.Op", Field, 16},
+		{"PathError.Path", Field, 16},
+		{"ReadDir", Func, 16},
+		{"ReadDirFS", Type, 16},
+		{"ReadDirFile", Type, 16},
+		{"ReadFile", Func, 16},
+		{"ReadFileFS", Type, 16},
+		{"SkipAll", Var, 20},
+		{"SkipDir", Var, 16},
+		{"Stat", Func, 16},
+		{"StatFS", Type, 16},
+		{"Sub", Func, 16},
+		{"SubFS", Type, 16},
+		{"ValidPath", Func, 16},
+		{"WalkDir", Func, 16},
+		{"WalkDirFunc", Type, 16},
+	},
+	"io/ioutil": {
+		{"Discard", Var, 0},
+		{"NopCloser", Func, 0},
+		{"ReadAll", Func, 0},
+		{"ReadDir", Func, 0},
+		{"ReadFile", Func, 0},
+		{"TempDir", Func, 0},
+		{"TempFile", Func, 0},
+		{"WriteFile", Func, 0},
+	},
+	"iter": {
+		{"Pull", Func, 23},
+		{"Pull2", Func, 23},
+		{"Seq", Type, 23},
+		{"Seq2", Type, 23},
+	},
+	"log": {
+		{"(*Logger).Fatal", Method, 0},
+		{"(*Logger).Fatalf", Method, 0},
+		{"(*Logger).Fatalln", Method, 0},
+		{"(*Logger).Flags", Method, 0},
+		{"(*Logger).Output", Method, 0},
+		{"(*Logger).Panic", Method, 0},
+		{"(*Logger).Panicf", Method, 0},
+		{"(*Logger).Panicln", Method, 0},
+		{"(*Logger).Prefix", Method, 0},
+		{"(*Logger).Print", Method, 0},
+		{"(*Logger).Printf", Method, 0},
+		{"(*Logger).Println", Method, 0},
+		{"(*Logger).SetFlags", Method, 0},
+		{"(*Logger).SetOutput", Method, 5},
+		{"(*Logger).SetPrefix", Method, 0},
+		{"(*Logger).Writer", Method, 12},
+		{"Default", Func, 16},
+		{"Fatal", Func, 0},
+		{"Fatalf", Func, 0},
+		{"Fatalln", Func, 0},
+		{"Flags", Func, 0},
+		{"LUTC", Const, 5},
+		{"Ldate", Const, 0},
+		{"Llongfile", Const, 0},
+		{"Lmicroseconds", Const, 0},
+		{"Lmsgprefix", Const, 14},
+		{"Logger", Type, 0},
+		{"Lshortfile", Const, 0},
+		{"LstdFlags", Const, 0},
+		{"Ltime", Const, 0},
+		{"New", Func, 0},
+		{"Output", Func, 5},
+		{"Panic", Func, 0},
+		{"Panicf", Func, 0},
+		{"Panicln", Func, 0},
+		{"Prefix", Func, 0},
+		{"Print", Func, 0},
+		{"Printf", Func, 0},
+		{"Println", Func, 0},
+		{"SetFlags", Func, 0},
+		{"SetOutput", Func, 0},
+		{"SetPrefix", Func, 0},
+		{"Writer", Func, 13},
+	},
+	"log/slog": {
+		{"(*JSONHandler).Enabled", Method, 21},
+		{"(*JSONHandler).Handle", Method, 21},
+		{"(*JSONHandler).WithAttrs", Method, 21},
+		{"(*JSONHandler).WithGroup", Method, 21},
+		{"(*Level).UnmarshalJSON", Method, 21},
+		{"(*Level).UnmarshalText", Method, 21},
+		{"(*LevelVar).AppendText", Method, 24},
+		{"(*LevelVar).Level", Method, 21},
+		{"(*LevelVar).MarshalText", Method, 21},
+		{"(*LevelVar).Set", Method, 21},
+		{"(*LevelVar).String", Method, 21},
+		{"(*LevelVar).UnmarshalText", Method, 21},
+		{"(*Logger).Debug", Method, 21},
+		{"(*Logger).DebugContext", Method, 21},
+		{"(*Logger).Enabled", Method, 21},
+		{"(*Logger).Error", Method, 21},
+		{"(*Logger).ErrorContext", Method, 21},
+		{"(*Logger).Handler", Method, 21},
+		{"(*Logger).Info", Method, 21},
+		{"(*Logger).InfoContext", Method, 21},
+		{"(*Logger).Log", Method, 21},
+		{"(*Logger).LogAttrs", Method, 21},
+		{"(*Logger).Warn", Method, 21},
+		{"(*Logger).WarnContext", Method, 21},
+		{"(*Logger).With", Method, 21},
+		{"(*Logger).WithGroup", Method, 21},
+		{"(*Record).Add", Method, 21},
+		{"(*Record).AddAttrs", Method, 21},
+		{"(*TextHandler).Enabled", Method, 21},
+		{"(*TextHandler).Handle", Method, 21},
+		{"(*TextHandler).WithAttrs", Method, 21},
+		{"(*TextHandler).WithGroup", Method, 21},
+		{"(Attr).Equal", Method, 21},
+		{"(Attr).String", Method, 21},
+		{"(Kind).String", Method, 21},
+		{"(Level).AppendText", Method, 24},
+		{"(Level).Level", Method, 21},
+		{"(Level).MarshalJSON", Method, 21},
+		{"(Level).MarshalText", Method, 21},
+		{"(Level).String", Method, 21},
+		{"(Record).Attrs", Method, 21},
+		{"(Record).Clone", Method, 21},
+		{"(Record).NumAttrs", Method, 21},
+		{"(Value).Any", Method, 21},
+		{"(Value).Bool", Method, 21},
+		{"(Value).Duration", Method, 21},
+		{"(Value).Equal", Method, 21},
+		{"(Value).Float64", Method, 21},
+		{"(Value).Group", Method, 21},
+		{"(Value).Int64", Method, 21},
+		{"(Value).Kind", Method, 21},
+		{"(Value).LogValuer", Method, 21},
+		{"(Value).Resolve", Method, 21},
+		{"(Value).String", Method, 21},
+		{"(Value).Time", Method, 21},
+		{"(Value).Uint64", Method, 21},
+		{"Any", Func, 21},
+		{"AnyValue", Func, 21},
+		{"Attr", Type, 21},
+		{"Attr.Key", Field, 21},
+		{"Attr.Value", Field, 21},
+		{"Bool", Func, 21},
+		{"BoolValue", Func, 21},
+		{"Debug", Func, 21},
+		{"DebugContext", Func, 21},
+		{"Default", Func, 21},
+		{"DiscardHandler", Var, 24},
+		{"Duration", Func, 21},
+		{"DurationValue", Func, 21},
+		{"Error", Func, 21},
+		{"ErrorContext", Func, 21},
+		{"Float64", Func, 21},
+		{"Float64Value", Func, 21},
+		{"Group", Func, 21},
+		{"GroupValue", Func, 21},
+		{"Handler", Type, 21},
+		{"HandlerOptions", Type, 21},
+		{"HandlerOptions.AddSource", Field, 21},
+		{"HandlerOptions.Level", Field, 21},
+		{"HandlerOptions.ReplaceAttr", Field, 21},
+		{"Info", Func, 21},
+		{"InfoContext", Func, 21},
+		{"Int", Func, 21},
+		{"Int64", Func, 21},
+		{"Int64Value", Func, 21},
+		{"IntValue", Func, 21},
+		{"JSONHandler", Type, 21},
+		{"Kind", Type, 21},
+		{"KindAny", Const, 21},
+		{"KindBool", Const, 21},
+		{"KindDuration", Const, 21},
+		{"KindFloat64", Const, 21},
+		{"KindGroup", Const, 21},
+		{"KindInt64", Const, 21},
+		{"KindLogValuer", Const, 21},
+		{"KindString", Const, 21},
+		{"KindTime", Const, 21},
+		{"KindUint64", Const, 21},
+		{"Level", Type, 21},
+		{"LevelDebug", Const, 21},
+		{"LevelError", Const, 21},
+		{"LevelInfo", Const, 21},
+		{"LevelKey", Const, 21},
+		{"LevelVar", Type, 21},
+		{"LevelWarn", Const, 21},
+		{"Leveler", Type, 21},
+		{"Log", Func, 21},
+		{"LogAttrs", Func, 21},
+		{"LogValuer", Type, 21},
+		{"Logger", Type, 21},
+		{"MessageKey", Const, 21},
+		{"New", Func, 21},
+		{"NewJSONHandler", Func, 21},
+		{"NewLogLogger", Func, 21},
+		{"NewRecord", Func, 21},
+		{"NewTextHandler", Func, 21},
+		{"Record", Type, 21},
+		{"Record.Level", Field, 21},
+		{"Record.Message", Field, 21},
+		{"Record.PC", Field, 21},
+		{"Record.Time", Field, 21},
+		{"SetDefault", Func, 21},
+		{"SetLogLoggerLevel", Func, 22},
+		{"Source", Type, 21},
+		{"Source.File", Field, 21},
+		{"Source.Function", Field, 21},
+		{"Source.Line", Field, 21},
+		{"SourceKey", Const, 21},
+		{"String", Func, 21},
+		{"StringValue", Func, 21},
+		{"TextHandler", Type, 21},
+		{"Time", Func, 21},
+		{"TimeKey", Const, 21},
+		{"TimeValue", Func, 21},
+		{"Uint64", Func, 21},
+		{"Uint64Value", Func, 21},
+		{"Value", Type, 21},
+		{"Warn", Func, 21},
+		{"WarnContext", Func, 21},
+		{"With", Func, 21},
+	},
+	"log/syslog": {
+		{"(*Writer).Alert", Method, 0},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).Crit", Method, 0},
+		{"(*Writer).Debug", Method, 0},
+		{"(*Writer).Emerg", Method, 0},
+		{"(*Writer).Err", Method, 0},
+		{"(*Writer).Info", Method, 0},
+		{"(*Writer).Notice", Method, 0},
+		{"(*Writer).Warning", Method, 0},
+		{"(*Writer).Write", Method, 0},
+		{"Dial", Func, 0},
+		{"LOG_ALERT", Const, 0},
+		{"LOG_AUTH", Const, 1},
+		{"LOG_AUTHPRIV", Const, 1},
+		{"LOG_CRIT", Const, 0},
+		{"LOG_CRON", Const, 1},
+		{"LOG_DAEMON", Const, 1},
+		{"LOG_DEBUG", Const, 0},
+		{"LOG_EMERG", Const, 0},
+		{"LOG_ERR", Const, 0},
+		{"LOG_FTP", Const, 1},
+		{"LOG_INFO", Const, 0},
+		{"LOG_KERN", Const, 1},
+		{"LOG_LOCAL0", Const, 1},
+		{"LOG_LOCAL1", Const, 1},
+		{"LOG_LOCAL2", Const, 1},
+		{"LOG_LOCAL3", Const, 1},
+		{"LOG_LOCAL4", Const, 1},
+		{"LOG_LOCAL5", Const, 1},
+		{"LOG_LOCAL6", Const, 1},
+		{"LOG_LOCAL7", Const, 1},
+		{"LOG_LPR", Const, 1},
+		{"LOG_MAIL", Const, 1},
+		{"LOG_NEWS", Const, 1},
+		{"LOG_NOTICE", Const, 0},
+		{"LOG_SYSLOG", Const, 1},
+		{"LOG_USER", Const, 1},
+		{"LOG_UUCP", Const, 1},
+		{"LOG_WARNING", Const, 0},
+		{"New", Func, 0},
+		{"NewLogger", Func, 0},
+		{"Priority", Type, 0},
+		{"Writer", Type, 0},
+	},
+	"maps": {
+		{"All", Func, 23},
+		{"Clone", Func, 21},
+		{"Collect", Func, 23},
+		{"Copy", Func, 21},
+		{"DeleteFunc", Func, 21},
+		{"Equal", Func, 21},
+		{"EqualFunc", Func, 21},
+		{"Insert", Func, 23},
+		{"Keys", Func, 23},
+		{"Values", Func, 23},
+	},
+	"math": {
+		{"Abs", Func, 0},
+		{"Acos", Func, 0},
+		{"Acosh", Func, 0},
+		{"Asin", Func, 0},
+		{"Asinh", Func, 0},
+		{"Atan", Func, 0},
+		{"Atan2", Func, 0},
+		{"Atanh", Func, 0},
+		{"Cbrt", Func, 0},
+		{"Ceil", Func, 0},
+		{"Copysign", Func, 0},
+		{"Cos", Func, 0},
+		{"Cosh", Func, 0},
+		{"Dim", Func, 0},
+		{"E", Const, 0},
+		{"Erf", Func, 0},
+		{"Erfc", Func, 0},
+		{"Erfcinv", Func, 10},
+		{"Erfinv", Func, 10},
+		{"Exp", Func, 0},
+		{"Exp2", Func, 0},
+		{"Expm1", Func, 0},
+		{"FMA", Func, 14},
+		{"Float32bits", Func, 0},
+		{"Float32frombits", Func, 0},
+		{"Float64bits", Func, 0},
+		{"Float64frombits", Func, 0},
+		{"Floor", Func, 0},
+		{"Frexp", Func, 0},
+		{"Gamma", Func, 0},
+		{"Hypot", Func, 0},
+		{"Ilogb", Func, 0},
+		{"Inf", Func, 0},
+		{"IsInf", Func, 0},
+		{"IsNaN", Func, 0},
+		{"J0", Func, 0},
+		{"J1", Func, 0},
+		{"Jn", Func, 0},
+		{"Ldexp", Func, 0},
+		{"Lgamma", Func, 0},
+		{"Ln10", Const, 0},
+		{"Ln2", Const, 0},
+		{"Log", Func, 0},
+		{"Log10", Func, 0},
+		{"Log10E", Const, 0},
+		{"Log1p", Func, 0},
+		{"Log2", Func, 0},
+		{"Log2E", Const, 0},
+		{"Logb", Func, 0},
+		{"Max", Func, 0},
+		{"MaxFloat32", Const, 0},
+		{"MaxFloat64", Const, 0},
+		{"MaxInt", Const, 17},
+		{"MaxInt16", Const, 0},
+		{"MaxInt32", Const, 0},
+		{"MaxInt64", Const, 0},
+		{"MaxInt8", Const, 0},
+		{"MaxUint", Const, 17},
+		{"MaxUint16", Const, 0},
+		{"MaxUint32", Const, 0},
+		{"MaxUint64", Const, 0},
+		{"MaxUint8", Const, 0},
+		{"Min", Func, 0},
+		{"MinInt", Const, 17},
+		{"MinInt16", Const, 0},
+		{"MinInt32", Const, 0},
+		{"MinInt64", Const, 0},
+		{"MinInt8", Const, 0},
+		{"Mod", Func, 0},
+		{"Modf", Func, 0},
+		{"NaN", Func, 0},
+		{"Nextafter", Func, 0},
+		{"Nextafter32", Func, 4},
+		{"Phi", Const, 0},
+		{"Pi", Const, 0},
+		{"Pow", Func, 0},
+		{"Pow10", Func, 0},
+		{"Remainder", Func, 0},
+		{"Round", Func, 10},
+		{"RoundToEven", Func, 10},
+		{"Signbit", Func, 0},
+		{"Sin", Func, 0},
+		{"Sincos", Func, 0},
+		{"Sinh", Func, 0},
+		{"SmallestNonzeroFloat32", Const, 0},
+		{"SmallestNonzeroFloat64", Const, 0},
+		{"Sqrt", Func, 0},
+		{"Sqrt2", Const, 0},
+		{"SqrtE", Const, 0},
+		{"SqrtPhi", Const, 0},
+		{"SqrtPi", Const, 0},
+		{"Tan", Func, 0},
+		{"Tanh", Func, 0},
+		{"Trunc", Func, 0},
+		{"Y0", Func, 0},
+		{"Y1", Func, 0},
+		{"Yn", Func, 0},
+	},
+	"math/big": {
+		{"(*Float).Abs", Method, 5},
+		{"(*Float).Acc", Method, 5},
+		{"(*Float).Add", Method, 5},
+		{"(*Float).Append", Method, 5},
+		{"(*Float).AppendText", Method, 24},
+		{"(*Float).Cmp", Method, 5},
+		{"(*Float).Copy", Method, 5},
+		{"(*Float).Float32", Method, 5},
+		{"(*Float).Float64", Method, 5},
+		{"(*Float).Format", Method, 5},
+		{"(*Float).GobDecode", Method, 7},
+		{"(*Float).GobEncode", Method, 7},
+		{"(*Float).Int", Method, 5},
+		{"(*Float).Int64", Method, 5},
+		{"(*Float).IsInf", Method, 5},
+		{"(*Float).IsInt", Method, 5},
+		{"(*Float).MantExp", Method, 5},
+		{"(*Float).MarshalText", Method, 6},
+		{"(*Float).MinPrec", Method, 5},
+		{"(*Float).Mode", Method, 5},
+		{"(*Float).Mul", Method, 5},
+		{"(*Float).Neg", Method, 5},
+		{"(*Float).Parse", Method, 5},
+		{"(*Float).Prec", Method, 5},
+		{"(*Float).Quo", Method, 5},
+		{"(*Float).Rat", Method, 5},
+		{"(*Float).Scan", Method, 8},
+		{"(*Float).Set", Method, 5},
+		{"(*Float).SetFloat64", Method, 5},
+		{"(*Float).SetInf", Method, 5},
+		{"(*Float).SetInt", Method, 5},
+		{"(*Float).SetInt64", Method, 5},
+		{"(*Float).SetMantExp", Method, 5},
+		{"(*Float).SetMode", Method, 5},
+		{"(*Float).SetPrec", Method, 5},
+		{"(*Float).SetRat", Method, 5},
+		{"(*Float).SetString", Method, 5},
+		{"(*Float).SetUint64", Method, 5},
+		{"(*Float).Sign", Method, 5},
+		{"(*Float).Signbit", Method, 5},
+		{"(*Float).Sqrt", Method, 10},
+		{"(*Float).String", Method, 5},
+		{"(*Float).Sub", Method, 5},
+		{"(*Float).Text", Method, 5},
+		{"(*Float).Uint64", Method, 5},
+		{"(*Float).UnmarshalText", Method, 6},
+		{"(*Int).Abs", Method, 0},
+		{"(*Int).Add", Method, 0},
+		{"(*Int).And", Method, 0},
+		{"(*Int).AndNot", Method, 0},
+		{"(*Int).Append", Method, 6},
+		{"(*Int).AppendText", Method, 24},
+		{"(*Int).Binomial", Method, 0},
+		{"(*Int).Bit", Method, 0},
+		{"(*Int).BitLen", Method, 0},
+		{"(*Int).Bits", Method, 0},
+		{"(*Int).Bytes", Method, 0},
+		{"(*Int).Cmp", Method, 0},
+		{"(*Int).CmpAbs", Method, 10},
+		{"(*Int).Div", Method, 0},
+		{"(*Int).DivMod", Method, 0},
+		{"(*Int).Exp", Method, 0},
+		{"(*Int).FillBytes", Method, 15},
+		{"(*Int).Float64", Method, 21},
+		{"(*Int).Format", Method, 0},
+		{"(*Int).GCD", Method, 0},
+		{"(*Int).GobDecode", Method, 0},
+		{"(*Int).GobEncode", Method, 0},
+		{"(*Int).Int64", Method, 0},
+		{"(*Int).IsInt64", Method, 9},
+		{"(*Int).IsUint64", Method, 9},
+		{"(*Int).Lsh", Method, 0},
+		{"(*Int).MarshalJSON", Method, 1},
+		{"(*Int).MarshalText", Method, 3},
+		{"(*Int).Mod", Method, 0},
+		{"(*Int).ModInverse", Method, 0},
+		{"(*Int).ModSqrt", Method, 5},
+		{"(*Int).Mul", Method, 0},
+		{"(*Int).MulRange", Method, 0},
+		{"(*Int).Neg", Method, 0},
+		{"(*Int).Not", Method, 0},
+		{"(*Int).Or", Method, 0},
+		{"(*Int).ProbablyPrime", Method, 0},
+		{"(*Int).Quo", Method, 0},
+		{"(*Int).QuoRem", Method, 0},
+		{"(*Int).Rand", Method, 0},
+		{"(*Int).Rem", Method, 0},
+		{"(*Int).Rsh", Method, 0},
+		{"(*Int).Scan", Method, 0},
+		{"(*Int).Set", Method, 0},
+		{"(*Int).SetBit", Method, 0},
+		{"(*Int).SetBits", Method, 0},
+		{"(*Int).SetBytes", Method, 0},
+		{"(*Int).SetInt64", Method, 0},
+		{"(*Int).SetString", Method, 0},
+		{"(*Int).SetUint64", Method, 1},
+		{"(*Int).Sign", Method, 0},
+		{"(*Int).Sqrt", Method, 8},
+		{"(*Int).String", Method, 0},
+		{"(*Int).Sub", Method, 0},
+		{"(*Int).Text", Method, 6},
+		{"(*Int).TrailingZeroBits", Method, 13},
+		{"(*Int).Uint64", Method, 1},
+		{"(*Int).UnmarshalJSON", Method, 1},
+		{"(*Int).UnmarshalText", Method, 3},
+		{"(*Int).Xor", Method, 0},
+		{"(*Rat).Abs", Method, 0},
+		{"(*Rat).Add", Method, 0},
+		{"(*Rat).AppendText", Method, 24},
+		{"(*Rat).Cmp", Method, 0},
+		{"(*Rat).Denom", Method, 0},
+		{"(*Rat).Float32", Method, 4},
+		{"(*Rat).Float64", Method, 1},
+		{"(*Rat).FloatPrec", Method, 22},
+		{"(*Rat).FloatString", Method, 0},
+		{"(*Rat).GobDecode", Method, 0},
+		{"(*Rat).GobEncode", Method, 0},
+		{"(*Rat).Inv", Method, 0},
+		{"(*Rat).IsInt", Method, 0},
+		{"(*Rat).MarshalText", Method, 3},
+		{"(*Rat).Mul", Method, 0},
+		{"(*Rat).Neg", Method, 0},
+		{"(*Rat).Num", Method, 0},
+		{"(*Rat).Quo", Method, 0},
+		{"(*Rat).RatString", Method, 0},
+		{"(*Rat).Scan", Method, 0},
+		{"(*Rat).Set", Method, 0},
+		{"(*Rat).SetFloat64", Method, 1},
+		{"(*Rat).SetFrac", Method, 0},
+		{"(*Rat).SetFrac64", Method, 0},
+		{"(*Rat).SetInt", Method, 0},
+		{"(*Rat).SetInt64", Method, 0},
+		{"(*Rat).SetString", Method, 0},
+		{"(*Rat).SetUint64", Method, 13},
+		{"(*Rat).Sign", Method, 0},
+		{"(*Rat).String", Method, 0},
+		{"(*Rat).Sub", Method, 0},
+		{"(*Rat).UnmarshalText", Method, 3},
+		{"(Accuracy).String", Method, 5},
+		{"(ErrNaN).Error", Method, 5},
+		{"(RoundingMode).String", Method, 5},
+		{"Above", Const, 5},
+		{"Accuracy", Type, 5},
+		{"AwayFromZero", Const, 5},
+		{"Below", Const, 5},
+		{"ErrNaN", Type, 5},
+		{"Exact", Const, 5},
+		{"Float", Type, 5},
+		{"Int", Type, 0},
+		{"Jacobi", Func, 5},
+		{"MaxBase", Const, 0},
+		{"MaxExp", Const, 5},
+		{"MaxPrec", Const, 5},
+		{"MinExp", Const, 5},
+		{"NewFloat", Func, 5},
+		{"NewInt", Func, 0},
+		{"NewRat", Func, 0},
+		{"ParseFloat", Func, 5},
+		{"Rat", Type, 0},
+		{"RoundingMode", Type, 5},
+		{"ToNearestAway", Const, 5},
+		{"ToNearestEven", Const, 5},
+		{"ToNegativeInf", Const, 5},
+		{"ToPositiveInf", Const, 5},
+		{"ToZero", Const, 5},
+		{"Word", Type, 0},
+	},
+	"math/bits": {
+		{"Add", Func, 12},
+		{"Add32", Func, 12},
+		{"Add64", Func, 12},
+		{"Div", Func, 12},
+		{"Div32", Func, 12},
+		{"Div64", Func, 12},
+		{"LeadingZeros", Func, 9},
+		{"LeadingZeros16", Func, 9},
+		{"LeadingZeros32", Func, 9},
+		{"LeadingZeros64", Func, 9},
+		{"LeadingZeros8", Func, 9},
+		{"Len", Func, 9},
+		{"Len16", Func, 9},
+		{"Len32", Func, 9},
+		{"Len64", Func, 9},
+		{"Len8", Func, 9},
+		{"Mul", Func, 12},
+		{"Mul32", Func, 12},
+		{"Mul64", Func, 12},
+		{"OnesCount", Func, 9},
+		{"OnesCount16", Func, 9},
+		{"OnesCount32", Func, 9},
+		{"OnesCount64", Func, 9},
+		{"OnesCount8", Func, 9},
+		{"Rem", Func, 14},
+		{"Rem32", Func, 14},
+		{"Rem64", Func, 14},
+		{"Reverse", Func, 9},
+		{"Reverse16", Func, 9},
+		{"Reverse32", Func, 9},
+		{"Reverse64", Func, 9},
+		{"Reverse8", Func, 9},
+		{"ReverseBytes", Func, 9},
+		{"ReverseBytes16", Func, 9},
+		{"ReverseBytes32", Func, 9},
+		{"ReverseBytes64", Func, 9},
+		{"RotateLeft", Func, 9},
+		{"RotateLeft16", Func, 9},
+		{"RotateLeft32", Func, 9},
+		{"RotateLeft64", Func, 9},
+		{"RotateLeft8", Func, 9},
+		{"Sub", Func, 12},
+		{"Sub32", Func, 12},
+		{"Sub64", Func, 12},
+		{"TrailingZeros", Func, 9},
+		{"TrailingZeros16", Func, 9},
+		{"TrailingZeros32", Func, 9},
+		{"TrailingZeros64", Func, 9},
+		{"TrailingZeros8", Func, 9},
+		{"UintSize", Const, 9},
+	},
+	"math/cmplx": {
+		{"Abs", Func, 0},
+		{"Acos", Func, 0},
+		{"Acosh", Func, 0},
+		{"Asin", Func, 0},
+		{"Asinh", Func, 0},
+		{"Atan", Func, 0},
+		{"Atanh", Func, 0},
+		{"Conj", Func, 0},
+		{"Cos", Func, 0},
+		{"Cosh", Func, 0},
+		{"Cot", Func, 0},
+		{"Exp", Func, 0},
+		{"Inf", Func, 0},
+		{"IsInf", Func, 0},
+		{"IsNaN", Func, 0},
+		{"Log", Func, 0},
+		{"Log10", Func, 0},
+		{"NaN", Func, 0},
+		{"Phase", Func, 0},
+		{"Polar", Func, 0},
+		{"Pow", Func, 0},
+		{"Rect", Func, 0},
+		{"Sin", Func, 0},
+		{"Sinh", Func, 0},
+		{"Sqrt", Func, 0},
+		{"Tan", Func, 0},
+		{"Tanh", Func, 0},
+	},
+	"math/rand": {
+		{"(*Rand).ExpFloat64", Method, 0},
+		{"(*Rand).Float32", Method, 0},
+		{"(*Rand).Float64", Method, 0},
+		{"(*Rand).Int", Method, 0},
+		{"(*Rand).Int31", Method, 0},
+		{"(*Rand).Int31n", Method, 0},
+		{"(*Rand).Int63", Method, 0},
+		{"(*Rand).Int63n", Method, 0},
+		{"(*Rand).Intn", Method, 0},
+		{"(*Rand).NormFloat64", Method, 0},
+		{"(*Rand).Perm", Method, 0},
+		{"(*Rand).Read", Method, 6},
+		{"(*Rand).Seed", Method, 0},
+		{"(*Rand).Shuffle", Method, 10},
+		{"(*Rand).Uint32", Method, 0},
+		{"(*Rand).Uint64", Method, 8},
+		{"(*Zipf).Uint64", Method, 0},
+		{"ExpFloat64", Func, 0},
+		{"Float32", Func, 0},
+		{"Float64", Func, 0},
+		{"Int", Func, 0},
+		{"Int31", Func, 0},
+		{"Int31n", Func, 0},
+		{"Int63", Func, 0},
+		{"Int63n", Func, 0},
+		{"Intn", Func, 0},
+		{"New", Func, 0},
+		{"NewSource", Func, 0},
+		{"NewZipf", Func, 0},
+		{"NormFloat64", Func, 0},
+		{"Perm", Func, 0},
+		{"Rand", Type, 0},
+		{"Read", Func, 6},
+		{"Seed", Func, 0},
+		{"Shuffle", Func, 10},
+		{"Source", Type, 0},
+		{"Source64", Type, 8},
+		{"Uint32", Func, 0},
+		{"Uint64", Func, 8},
+		{"Zipf", Type, 0},
+	},
+	"math/rand/v2": {
+		{"(*ChaCha8).AppendBinary", Method, 24},
+		{"(*ChaCha8).MarshalBinary", Method, 22},
+		{"(*ChaCha8).Read", Method, 23},
+		{"(*ChaCha8).Seed", Method, 22},
+		{"(*ChaCha8).Uint64", Method, 22},
+		{"(*ChaCha8).UnmarshalBinary", Method, 22},
+		{"(*PCG).AppendBinary", Method, 24},
+		{"(*PCG).MarshalBinary", Method, 22},
+		{"(*PCG).Seed", Method, 22},
+		{"(*PCG).Uint64", Method, 22},
+		{"(*PCG).UnmarshalBinary", Method, 22},
+		{"(*Rand).ExpFloat64", Method, 22},
+		{"(*Rand).Float32", Method, 22},
+		{"(*Rand).Float64", Method, 22},
+		{"(*Rand).Int", Method, 22},
+		{"(*Rand).Int32", Method, 22},
+		{"(*Rand).Int32N", Method, 22},
+		{"(*Rand).Int64", Method, 22},
+		{"(*Rand).Int64N", Method, 22},
+		{"(*Rand).IntN", Method, 22},
+		{"(*Rand).NormFloat64", Method, 22},
+		{"(*Rand).Perm", Method, 22},
+		{"(*Rand).Shuffle", Method, 22},
+		{"(*Rand).Uint", Method, 23},
+		{"(*Rand).Uint32", Method, 22},
+		{"(*Rand).Uint32N", Method, 22},
+		{"(*Rand).Uint64", Method, 22},
+		{"(*Rand).Uint64N", Method, 22},
+		{"(*Rand).UintN", Method, 22},
+		{"(*Zipf).Uint64", Method, 22},
+		{"ChaCha8", Type, 22},
+		{"ExpFloat64", Func, 22},
+		{"Float32", Func, 22},
+		{"Float64", Func, 22},
+		{"Int", Func, 22},
+		{"Int32", Func, 22},
+		{"Int32N", Func, 22},
+		{"Int64", Func, 22},
+		{"Int64N", Func, 22},
+		{"IntN", Func, 22},
+		{"N", Func, 22},
+		{"New", Func, 22},
+		{"NewChaCha8", Func, 22},
+		{"NewPCG", Func, 22},
+		{"NewZipf", Func, 22},
+		{"NormFloat64", Func, 22},
+		{"PCG", Type, 22},
+		{"Perm", Func, 22},
+		{"Rand", Type, 22},
+		{"Shuffle", Func, 22},
+		{"Source", Type, 22},
+		{"Uint", Func, 23},
+		{"Uint32", Func, 22},
+		{"Uint32N", Func, 22},
+		{"Uint64", Func, 22},
+		{"Uint64N", Func, 22},
+		{"UintN", Func, 22},
+		{"Zipf", Type, 22},
+	},
+	"mime": {
+		{"(*WordDecoder).Decode", Method, 5},
+		{"(*WordDecoder).DecodeHeader", Method, 5},
+		{"(WordEncoder).Encode", Method, 5},
+		{"AddExtensionType", Func, 0},
+		{"BEncoding", Const, 5},
+		{"ErrInvalidMediaParameter", Var, 9},
+		{"ExtensionsByType", Func, 5},
+		{"FormatMediaType", Func, 0},
+		{"ParseMediaType", Func, 0},
+		{"QEncoding", Const, 5},
+		{"TypeByExtension", Func, 0},
+		{"WordDecoder", Type, 5},
+		{"WordDecoder.CharsetReader", Field, 5},
+		{"WordEncoder", Type, 5},
+	},
+	"mime/multipart": {
+		{"(*FileHeader).Open", Method, 0},
+		{"(*Form).RemoveAll", Method, 0},
+		{"(*Part).Close", Method, 0},
+		{"(*Part).FileName", Method, 0},
+		{"(*Part).FormName", Method, 0},
+		{"(*Part).Read", Method, 0},
+		{"(*Reader).NextPart", Method, 0},
+		{"(*Reader).NextRawPart", Method, 14},
+		{"(*Reader).ReadForm", Method, 0},
+		{"(*Writer).Boundary", Method, 0},
+		{"(*Writer).Close", Method, 0},
+		{"(*Writer).CreateFormField", Method, 0},
+		{"(*Writer).CreateFormFile", Method, 0},
+		{"(*Writer).CreatePart", Method, 0},
+		{"(*Writer).FormDataContentType", Method, 0},
+		{"(*Writer).SetBoundary", Method, 1},
+		{"(*Writer).WriteField", Method, 0},
+		{"ErrMessageTooLarge", Var, 9},
+		{"File", Type, 0},
+		{"FileHeader", Type, 0},
+		{"FileHeader.Filename", Field, 0},
+		{"FileHeader.Header", Field, 0},
+		{"FileHeader.Size", Field, 9},
+		{"Form", Type, 0},
+		{"Form.File", Field, 0},
+		{"Form.Value", Field, 0},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"Part", Type, 0},
+		{"Part.Header", Field, 0},
+		{"Reader", Type, 0},
+		{"Writer", Type, 0},
+	},
+	"mime/quotedprintable": {
+		{"(*Reader).Read", Method, 5},
+		{"(*Writer).Close", Method, 5},
+		{"(*Writer).Write", Method, 5},
+		{"NewReader", Func, 5},
+		{"NewWriter", Func, 5},
+		{"Reader", Type, 5},
+		{"Writer", Type, 5},
+		{"Writer.Binary", Field, 5},
+	},
+	"net": {
+		{"(*AddrError).Error", Method, 0},
+		{"(*AddrError).Temporary", Method, 0},
+		{"(*AddrError).Timeout", Method, 0},
+		{"(*Buffers).Read", Method, 8},
+		{"(*Buffers).WriteTo", Method, 8},
+		{"(*DNSConfigError).Error", Method, 0},
+		{"(*DNSConfigError).Temporary", Method, 0},
+		{"(*DNSConfigError).Timeout", Method, 0},
+		{"(*DNSConfigError).Unwrap", Method, 13},
+		{"(*DNSError).Error", Method, 0},
+		{"(*DNSError).Temporary", Method, 0},
+		{"(*DNSError).Timeout", Method, 0},
+		{"(*DNSError).Unwrap", Method, 23},
+		{"(*Dialer).Dial", Method, 1},
+		{"(*Dialer).DialContext", Method, 7},
+		{"(*Dialer).MultipathTCP", Method, 21},
+		{"(*Dialer).SetMultipathTCP", Method, 21},
+		{"(*IP).UnmarshalText", Method, 2},
+		{"(*IPAddr).Network", Method, 0},
+		{"(*IPAddr).String", Method, 0},
+		{"(*IPConn).Close", Method, 0},
+		{"(*IPConn).File", Method, 0},
+		{"(*IPConn).LocalAddr", Method, 0},
+		{"(*IPConn).Read", Method, 0},
+		{"(*IPConn).ReadFrom", Method, 0},
+		{"(*IPConn).ReadFromIP", Method, 0},
+		{"(*IPConn).ReadMsgIP", Method, 1},
+		{"(*IPConn).RemoteAddr", Method, 0},
+		{"(*IPConn).SetDeadline", Method, 0},
+		{"(*IPConn).SetReadBuffer", Method, 0},
+		{"(*IPConn).SetReadDeadline", Method, 0},
+		{"(*IPConn).SetWriteBuffer", Method, 0},
+		{"(*IPConn).SetWriteDeadline", Method, 0},
+		{"(*IPConn).SyscallConn", Method, 9},
+		{"(*IPConn).Write", Method, 0},
+		{"(*IPConn).WriteMsgIP", Method, 1},
+		{"(*IPConn).WriteTo", Method, 0},
+		{"(*IPConn).WriteToIP", Method, 0},
+		{"(*IPNet).Contains", Method, 0},
+		{"(*IPNet).Network", Method, 0},
+		{"(*IPNet).String", Method, 0},
+		{"(*Interface).Addrs", Method, 0},
+		{"(*Interface).MulticastAddrs", Method, 0},
+		{"(*ListenConfig).Listen", Method, 11},
+		{"(*ListenConfig).ListenPacket", Method, 11},
+		{"(*ListenConfig).MultipathTCP", Method, 21},
+		{"(*ListenConfig).SetMultipathTCP", Method, 21},
+		{"(*OpError).Error", Method, 0},
+		{"(*OpError).Temporary", Method, 0},
+		{"(*OpError).Timeout", Method, 0},
+		{"(*OpError).Unwrap", Method, 13},
+		{"(*ParseError).Error", Method, 0},
+		{"(*ParseError).Temporary", Method, 17},
+		{"(*ParseError).Timeout", Method, 17},
+		{"(*Resolver).LookupAddr", Method, 8},
+		{"(*Resolver).LookupCNAME", Method, 8},
+		{"(*Resolver).LookupHost", Method, 8},
+		{"(*Resolver).LookupIP", Method, 15},
+		{"(*Resolver).LookupIPAddr", Method, 8},
+		{"(*Resolver).LookupMX", Method, 8},
+		{"(*Resolver).LookupNS", Method, 8},
+		{"(*Resolver).LookupNetIP", Method, 18},
+		{"(*Resolver).LookupPort", Method, 8},
+		{"(*Resolver).LookupSRV", Method, 8},
+		{"(*Resolver).LookupTXT", Method, 8},
+		{"(*TCPAddr).AddrPort", Method, 18},
+		{"(*TCPAddr).Network", Method, 0},
+		{"(*TCPAddr).String", Method, 0},
+		{"(*TCPConn).Close", Method, 0},
+		{"(*TCPConn).CloseRead", Method, 0},
+		{"(*TCPConn).CloseWrite", Method, 0},
+		{"(*TCPConn).File", Method, 0},
+		{"(*TCPConn).LocalAddr", Method, 0},
+		{"(*TCPConn).MultipathTCP", Method, 21},
+		{"(*TCPConn).Read", Method, 0},
+		{"(*TCPConn).ReadFrom", Method, 0},
+		{"(*TCPConn).RemoteAddr", Method, 0},
+		{"(*TCPConn).SetDeadline", Method, 0},
+		{"(*TCPConn).SetKeepAlive", Method, 0},
+		{"(*TCPConn).SetKeepAliveConfig", Method, 23},
+		{"(*TCPConn).SetKeepAlivePeriod", Method, 2},
+		{"(*TCPConn).SetLinger", Method, 0},
+		{"(*TCPConn).SetNoDelay", Method, 0},
+		{"(*TCPConn).SetReadBuffer", Method, 0},
+		{"(*TCPConn).SetReadDeadline", Method, 0},
+		{"(*TCPConn).SetWriteBuffer", Method, 0},
+		{"(*TCPConn).SetWriteDeadline", Method, 0},
+		{"(*TCPConn).SyscallConn", Method, 9},
+		{"(*TCPConn).Write", Method, 0},
+		{"(*TCPConn).WriteTo", Method, 22},
+		{"(*TCPListener).Accept", Method, 0},
+		{"(*TCPListener).AcceptTCP", Method, 0},
+		{"(*TCPListener).Addr", Method, 0},
+		{"(*TCPListener).Close", Method, 0},
+		{"(*TCPListener).File", Method, 0},
+		{"(*TCPListener).SetDeadline", Method, 0},
+		{"(*TCPListener).SyscallConn", Method, 10},
+		{"(*UDPAddr).AddrPort", Method, 18},
+		{"(*UDPAddr).Network", Method, 0},
+		{"(*UDPAddr).String", Method, 0},
+		{"(*UDPConn).Close", Method, 0},
+		{"(*UDPConn).File", Method, 0},
+		{"(*UDPConn).LocalAddr", Method, 0},
+		{"(*UDPConn).Read", Method, 0},
+		{"(*UDPConn).ReadFrom", Method, 0},
+		{"(*UDPConn).ReadFromUDP", Method, 0},
+		{"(*UDPConn).ReadFromUDPAddrPort", Method, 18},
+		{"(*UDPConn).ReadMsgUDP", Method, 1},
+		{"(*UDPConn).ReadMsgUDPAddrPort", Method, 18},
+		{"(*UDPConn).RemoteAddr", Method, 0},
+		{"(*UDPConn).SetDeadline", Method, 0},
+		{"(*UDPConn).SetReadBuffer", Method, 0},
+		{"(*UDPConn).SetReadDeadline", Method, 0},
+		{"(*UDPConn).SetWriteBuffer", Method, 0},
+		{"(*UDPConn).SetWriteDeadline", Method, 0},
+		{"(*UDPConn).SyscallConn", Method, 9},
+		{"(*UDPConn).Write", Method, 0},
+		{"(*UDPConn).WriteMsgUDP", Method, 1},
+		{"(*UDPConn).WriteMsgUDPAddrPort", Method, 18},
+		{"(*UDPConn).WriteTo", Method, 0},
+		{"(*UDPConn).WriteToUDP", Method, 0},
+		{"(*UDPConn).WriteToUDPAddrPort", Method, 18},
+		{"(*UnixAddr).Network", Method, 0},
+		{"(*UnixAddr).String", Method, 0},
+		{"(*UnixConn).Close", Method, 0},
+		{"(*UnixConn).CloseRead", Method, 1},
+		{"(*UnixConn).CloseWrite", Method, 1},
+		{"(*UnixConn).File", Method, 0},
+		{"(*UnixConn).LocalAddr", Method, 0},
+		{"(*UnixConn).Read", Method, 0},
+		{"(*UnixConn).ReadFrom", Method, 0},
+		{"(*UnixConn).ReadFromUnix", Method, 0},
+		{"(*UnixConn).ReadMsgUnix", Method, 0},
+		{"(*UnixConn).RemoteAddr", Method, 0},
+		{"(*UnixConn).SetDeadline", Method, 0},
+		{"(*UnixConn).SetReadBuffer", Method, 0},
+		{"(*UnixConn).SetReadDeadline", Method, 0},
+		{"(*UnixConn).SetWriteBuffer", Method, 0},
+		{"(*UnixConn).SetWriteDeadline", Method, 0},
+		{"(*UnixConn).SyscallConn", Method, 9},
+		{"(*UnixConn).Write", Method, 0},
+		{"(*UnixConn).WriteMsgUnix", Method, 0},
+		{"(*UnixConn).WriteTo", Method, 0},
+		{"(*UnixConn).WriteToUnix", Method, 0},
+		{"(*UnixListener).Accept", Method, 0},
+		{"(*UnixListener).AcceptUnix", Method, 0},
+		{"(*UnixListener).Addr", Method, 0},
+		{"(*UnixListener).Close", Method, 0},
+		{"(*UnixListener).File", Method, 0},
+		{"(*UnixListener).SetDeadline", Method, 0},
+		{"(*UnixListener).SetUnlinkOnClose", Method, 8},
+		{"(*UnixListener).SyscallConn", Method, 10},
+		{"(Flags).String", Method, 0},
+		{"(HardwareAddr).String", Method, 0},
+		{"(IP).AppendText", Method, 24},
+		{"(IP).DefaultMask", Method, 0},
+		{"(IP).Equal", Method, 0},
+		{"(IP).IsGlobalUnicast", Method, 0},
+		{"(IP).IsInterfaceLocalMulticast", Method, 0},
+		{"(IP).IsLinkLocalMulticast", Method, 0},
+		{"(IP).IsLinkLocalUnicast", Method, 0},
+		{"(IP).IsLoopback", Method, 0},
+		{"(IP).IsMulticast", Method, 0},
+		{"(IP).IsPrivate", Method, 17},
+		{"(IP).IsUnspecified", Method, 0},
+		{"(IP).MarshalText", Method, 2},
+		{"(IP).Mask", Method, 0},
+		{"(IP).String", Method, 0},
+		{"(IP).To16", Method, 0},
+		{"(IP).To4", Method, 0},
+		{"(IPMask).Size", Method, 0},
+		{"(IPMask).String", Method, 0},
+		{"(InvalidAddrError).Error", Method, 0},
+		{"(InvalidAddrError).Temporary", Method, 0},
+		{"(InvalidAddrError).Timeout", Method, 0},
+		{"(UnknownNetworkError).Error", Method, 0},
+		{"(UnknownNetworkError).Temporary", Method, 0},
+		{"(UnknownNetworkError).Timeout", Method, 0},
+		{"Addr", Type, 0},
+		{"AddrError", Type, 0},
+		{"AddrError.Addr", Field, 0},
+		{"AddrError.Err", Field, 0},
+		{"Buffers", Type, 8},
+		{"CIDRMask", Func, 0},
+		{"Conn", Type, 0},
+		{"DNSConfigError", Type, 0},
+		{"DNSConfigError.Err", Field, 0},
+		{"DNSError", Type, 0},
+		{"DNSError.Err", Field, 0},
+		{"DNSError.IsNotFound", Field, 13},
+		{"DNSError.IsTemporary", Field, 6},
+		{"DNSError.IsTimeout", Field, 0},
+		{"DNSError.Name", Field, 0},
+		{"DNSError.Server", Field, 0},
+		{"DNSError.UnwrapErr", Field, 23},
+		{"DefaultResolver", Var, 8},
+		{"Dial", Func, 0},
+		{"DialIP", Func, 0},
+		{"DialTCP", Func, 0},
+		{"DialTimeout", Func, 0},
+		{"DialUDP", Func, 0},
+		{"DialUnix", Func, 0},
+		{"Dialer", Type, 1},
+		{"Dialer.Cancel", Field, 6},
+		{"Dialer.Control", Field, 11},
+		{"Dialer.ControlContext", Field, 20},
+		{"Dialer.Deadline", Field, 1},
+		{"Dialer.DualStack", Field, 2},
+		{"Dialer.FallbackDelay", Field, 5},
+		{"Dialer.KeepAlive", Field, 3},
+		{"Dialer.KeepAliveConfig", Field, 23},
+		{"Dialer.LocalAddr", Field, 1},
+		{"Dialer.Resolver", Field, 8},
+		{"Dialer.Timeout", Field, 1},
+		{"ErrClosed", Var, 16},
+		{"ErrWriteToConnected", Var, 0},
+		{"Error", Type, 0},
+		{"FileConn", Func, 0},
+		{"FileListener", Func, 0},
+		{"FilePacketConn", Func, 0},
+		{"FlagBroadcast", Const, 0},
+		{"FlagLoopback", Const, 0},
+		{"FlagMulticast", Const, 0},
+		{"FlagPointToPoint", Const, 0},
+		{"FlagRunning", Const, 20},
+		{"FlagUp", Const, 0},
+		{"Flags", Type, 0},
+		{"HardwareAddr", Type, 0},
+		{"IP", Type, 0},
+		{"IPAddr", Type, 0},
+		{"IPAddr.IP", Field, 0},
+		{"IPAddr.Zone", Field, 1},
+		{"IPConn", Type, 0},
+		{"IPMask", Type, 0},
+		{"IPNet", Type, 0},
+		{"IPNet.IP", Field, 0},
+		{"IPNet.Mask", Field, 0},
+		{"IPv4", Func, 0},
+		{"IPv4Mask", Func, 0},
+		{"IPv4allrouter", Var, 0},
+		{"IPv4allsys", Var, 0},
+		{"IPv4bcast", Var, 0},
+		{"IPv4len", Const, 0},
+		{"IPv4zero", Var, 0},
+		{"IPv6interfacelocalallnodes", Var, 0},
+		{"IPv6len", Const, 0},
+		{"IPv6linklocalallnodes", Var, 0},
+		{"IPv6linklocalallrouters", Var, 0},
+		{"IPv6loopback", Var, 0},
+		{"IPv6unspecified", Var, 0},
+		{"IPv6zero", Var, 0},
+		{"Interface", Type, 0},
+		{"Interface.Flags", Field, 0},
+		{"Interface.HardwareAddr", Field, 0},
+		{"Interface.Index", Field, 0},
+		{"Interface.MTU", Field, 0},
+		{"Interface.Name", Field, 0},
+		{"InterfaceAddrs", Func, 0},
+		{"InterfaceByIndex", Func, 0},
+		{"InterfaceByName", Func, 0},
+		{"Interfaces", Func, 0},
+		{"InvalidAddrError", Type, 0},
+		{"JoinHostPort", Func, 0},
+		{"KeepAliveConfig", Type, 23},
+		{"KeepAliveConfig.Count", Field, 23},
+		{"KeepAliveConfig.Enable", Field, 23},
+		{"KeepAliveConfig.Idle", Field, 23},
+		{"KeepAliveConfig.Interval", Field, 23},
+		{"Listen", Func, 0},
+		{"ListenConfig", Type, 11},
+		{"ListenConfig.Control", Field, 11},
+		{"ListenConfig.KeepAlive", Field, 13},
+		{"ListenConfig.KeepAliveConfig", Field, 23},
+		{"ListenIP", Func, 0},
+		{"ListenMulticastUDP", Func, 0},
+		{"ListenPacket", Func, 0},
+		{"ListenTCP", Func, 0},
+		{"ListenUDP", Func, 0},
+		{"ListenUnix", Func, 0},
+		{"ListenUnixgram", Func, 0},
+		{"Listener", Type, 0},
+		{"LookupAddr", Func, 0},
+		{"LookupCNAME", Func, 0},
+		{"LookupHost", Func, 0},
+		{"LookupIP", Func, 0},
+		{"LookupMX", Func, 0},
+		{"LookupNS", Func, 1},
+		{"LookupPort", Func, 0},
+		{"LookupSRV", Func, 0},
+		{"LookupTXT", Func, 0},
+		{"MX", Type, 0},
+		{"MX.Host", Field, 0},
+		{"MX.Pref", Field, 0},
+		{"NS", Type, 1},
+		{"NS.Host", Field, 1},
+		{"OpError", Type, 0},
+		{"OpError.Addr", Field, 0},
+		{"OpError.Err", Field, 0},
+		{"OpError.Net", Field, 0},
+		{"OpError.Op", Field, 0},
+		{"OpError.Source", Field, 5},
+		{"PacketConn", Type, 0},
+		{"ParseCIDR", Func, 0},
+		{"ParseError", Type, 0},
+		{"ParseError.Text", Field, 0},
+		{"ParseError.Type", Field, 0},
+		{"ParseIP", Func, 0},
+		{"ParseMAC", Func, 0},
+		{"Pipe", Func, 0},
+		{"ResolveIPAddr", Func, 0},
+		{"ResolveTCPAddr", Func, 0},
+		{"ResolveUDPAddr", Func, 0},
+		{"ResolveUnixAddr", Func, 0},
+		{"Resolver", Type, 8},
+		{"Resolver.Dial", Field, 9},
+		{"Resolver.PreferGo", Field, 8},
+		{"Resolver.StrictErrors", Field, 9},
+		{"SRV", Type, 0},
+		{"SRV.Port", Field, 0},
+		{"SRV.Priority", Field, 0},
+		{"SRV.Target", Field, 0},
+		{"SRV.Weight", Field, 0},
+		{"SplitHostPort", Func, 0},
+		{"TCPAddr", Type, 0},
+		{"TCPAddr.IP", Field, 0},
+		{"TCPAddr.Port", Field, 0},
+		{"TCPAddr.Zone", Field, 1},
+		{"TCPAddrFromAddrPort", Func, 18},
+		{"TCPConn", Type, 0},
+		{"TCPListener", Type, 0},
+		{"UDPAddr", Type, 0},
+		{"UDPAddr.IP", Field, 0},
+		{"UDPAddr.Port", Field, 0},
+		{"UDPAddr.Zone", Field, 1},
+		{"UDPAddrFromAddrPort", Func, 18},
+		{"UDPConn", Type, 0},
+		{"UnixAddr", Type, 0},
+		{"UnixAddr.Name", Field, 0},
+		{"UnixAddr.Net", Field, 0},
+		{"UnixConn", Type, 0},
+		{"UnixListener", Type, 0},
+		{"UnknownNetworkError", Type, 0},
+	},
+	"net/http": {
+		{"(*Client).CloseIdleConnections", Method, 12},
+		{"(*Client).Do", Method, 0},
+		{"(*Client).Get", Method, 0},
+		{"(*Client).Head", Method, 0},
+		{"(*Client).Post", Method, 0},
+		{"(*Client).PostForm", Method, 0},
+		{"(*Cookie).String", Method, 0},
+		{"(*Cookie).Valid", Method, 18},
+		{"(*MaxBytesError).Error", Method, 19},
+		{"(*ProtocolError).Error", Method, 0},
+		{"(*ProtocolError).Is", Method, 21},
+		{"(*Protocols).SetHTTP1", Method, 24},
+		{"(*Protocols).SetHTTP2", Method, 24},
+		{"(*Protocols).SetUnencryptedHTTP2", Method, 24},
+		{"(*Request).AddCookie", Method, 0},
+		{"(*Request).BasicAuth", Method, 4},
+		{"(*Request).Clone", Method, 13},
+		{"(*Request).Context", Method, 7},
+		{"(*Request).Cookie", Method, 0},
+		{"(*Request).Cookies", Method, 0},
+		{"(*Request).CookiesNamed", Method, 23},
+		{"(*Request).FormFile", Method, 0},
+		{"(*Request).FormValue", Method, 0},
+		{"(*Request).MultipartReader", Method, 0},
+		{"(*Request).ParseForm", Method, 0},
+		{"(*Request).ParseMultipartForm", Method, 0},
+		{"(*Request).PathValue", Method, 22},
+		{"(*Request).PostFormValue", Method, 1},
+		{"(*Request).ProtoAtLeast", Method, 0},
+		{"(*Request).Referer", Method, 0},
+		{"(*Request).SetBasicAuth", Method, 0},
+		{"(*Request).SetPathValue", Method, 22},
+		{"(*Request).UserAgent", Method, 0},
+		{"(*Request).WithContext", Method, 7},
+		{"(*Request).Write", Method, 0},
+		{"(*Request).WriteProxy", Method, 0},
+		{"(*Response).Cookies", Method, 0},
+		{"(*Response).Location", Method, 0},
+		{"(*Response).ProtoAtLeast", Method, 0},
+		{"(*Response).Write", Method, 0},
+		{"(*ResponseController).EnableFullDuplex", Method, 21},
+		{"(*ResponseController).Flush", Method, 20},
+		{"(*ResponseController).Hijack", Method, 20},
+		{"(*ResponseController).SetReadDeadline", Method, 20},
+		{"(*ResponseController).SetWriteDeadline", Method, 20},
+		{"(*ServeMux).Handle", Method, 0},
+		{"(*ServeMux).HandleFunc", Method, 0},
+		{"(*ServeMux).Handler", Method, 1},
+		{"(*ServeMux).ServeHTTP", Method, 0},
+		{"(*Server).Close", Method, 8},
+		{"(*Server).ListenAndServe", Method, 0},
+		{"(*Server).ListenAndServeTLS", Method, 0},
+		{"(*Server).RegisterOnShutdown", Method, 9},
+		{"(*Server).Serve", Method, 0},
+		{"(*Server).ServeTLS", Method, 9},
+		{"(*Server).SetKeepAlivesEnabled", Method, 3},
+		{"(*Server).Shutdown", Method, 8},
+		{"(*Transport).CancelRequest", Method, 1},
+		{"(*Transport).Clone", Method, 13},
+		{"(*Transport).CloseIdleConnections", Method, 0},
+		{"(*Transport).RegisterProtocol", Method, 0},
+		{"(*Transport).RoundTrip", Method, 0},
+		{"(ConnState).String", Method, 3},
+		{"(Dir).Open", Method, 0},
+		{"(HandlerFunc).ServeHTTP", Method, 0},
+		{"(Header).Add", Method, 0},
+		{"(Header).Clone", Method, 13},
+		{"(Header).Del", Method, 0},
+		{"(Header).Get", Method, 0},
+		{"(Header).Set", Method, 0},
+		{"(Header).Values", Method, 14},
+		{"(Header).Write", Method, 0},
+		{"(Header).WriteSubset", Method, 0},
+		{"(Protocols).HTTP1", Method, 24},
+		{"(Protocols).HTTP2", Method, 24},
+		{"(Protocols).String", Method, 24},
+		{"(Protocols).UnencryptedHTTP2", Method, 24},
+		{"AllowQuerySemicolons", Func, 17},
+		{"CanonicalHeaderKey", Func, 0},
+		{"Client", Type, 0},
+		{"Client.CheckRedirect", Field, 0},
+		{"Client.Jar", Field, 0},
+		{"Client.Timeout", Field, 3},
+		{"Client.Transport", Field, 0},
+		{"CloseNotifier", Type, 1},
+		{"ConnState", Type, 3},
+		{"Cookie", Type, 0},
+		{"Cookie.Domain", Field, 0},
+		{"Cookie.Expires", Field, 0},
+		{"Cookie.HttpOnly", Field, 0},
+		{"Cookie.MaxAge", Field, 0},
+		{"Cookie.Name", Field, 0},
+		{"Cookie.Partitioned", Field, 23},
+		{"Cookie.Path", Field, 0},
+		{"Cookie.Quoted", Field, 23},
+		{"Cookie.Raw", Field, 0},
+		{"Cookie.RawExpires", Field, 0},
+		{"Cookie.SameSite", Field, 11},
+		{"Cookie.Secure", Field, 0},
+		{"Cookie.Unparsed", Field, 0},
+		{"Cookie.Value", Field, 0},
+		{"CookieJar", Type, 0},
+		{"DefaultClient", Var, 0},
+		{"DefaultMaxHeaderBytes", Const, 0},
+		{"DefaultMaxIdleConnsPerHost", Const, 0},
+		{"DefaultServeMux", Var, 0},
+		{"DefaultTransport", Var, 0},
+		{"DetectContentType", Func, 0},
+		{"Dir", Type, 0},
+		{"ErrAbortHandler", Var, 8},
+		{"ErrBodyNotAllowed", Var, 0},
+		{"ErrBodyReadAfterClose", Var, 0},
+		{"ErrContentLength", Var, 0},
+		{"ErrHandlerTimeout", Var, 0},
+		{"ErrHeaderTooLong", Var, 0},
+		{"ErrHijacked", Var, 0},
+		{"ErrLineTooLong", Var, 0},
+		{"ErrMissingBoundary", Var, 0},
+		{"ErrMissingContentLength", Var, 0},
+		{"ErrMissingFile", Var, 0},
+		{"ErrNoCookie", Var, 0},
+		{"ErrNoLocation", Var, 0},
+		{"ErrNotMultipart", Var, 0},
+		{"ErrNotSupported", Var, 0},
+		{"ErrSchemeMismatch", Var, 21},
+		{"ErrServerClosed", Var, 8},
+		{"ErrShortBody", Var, 0},
+		{"ErrSkipAltProtocol", Var, 6},
+		{"ErrUnexpectedTrailer", Var, 0},
+		{"ErrUseLastResponse", Var, 7},
+		{"ErrWriteAfterFlush", Var, 0},
+		{"Error", Func, 0},
+		{"FS", Func, 16},
+		{"File", Type, 0},
+		{"FileServer", Func, 0},
+		{"FileServerFS", Func, 22},
+		{"FileSystem", Type, 0},
+		{"Flusher", Type, 0},
+		{"Get", Func, 0},
+		{"HTTP2Config", Type, 24},
+		{"HTTP2Config.CountError", Field, 24},
+		{"HTTP2Config.MaxConcurrentStreams", Field, 24},
+		{"HTTP2Config.MaxDecoderHeaderTableSize", Field, 24},
+		{"HTTP2Config.MaxEncoderHeaderTableSize", Field, 24},
+		{"HTTP2Config.MaxReadFrameSize", Field, 24},
+		{"HTTP2Config.MaxReceiveBufferPerConnection", Field, 24},
+		{"HTTP2Config.MaxReceiveBufferPerStream", Field, 24},
+		{"HTTP2Config.PermitProhibitedCipherSuites", Field, 24},
+		{"HTTP2Config.PingTimeout", Field, 24},
+		{"HTTP2Config.SendPingTimeout", Field, 24},
+		{"HTTP2Config.WriteByteTimeout", Field, 24},
+		{"Handle", Func, 0},
+		{"HandleFunc", Func, 0},
+		{"Handler", Type, 0},
+		{"HandlerFunc", Type, 0},
+		{"Head", Func, 0},
+		{"Header", Type, 0},
+		{"Hijacker", Type, 0},
+		{"ListenAndServe", Func, 0},
+		{"ListenAndServeTLS", Func, 0},
+		{"LocalAddrContextKey", Var, 7},
+		{"MaxBytesError", Type, 19},
+		{"MaxBytesError.Limit", Field, 19},
+		{"MaxBytesHandler", Func, 18},
+		{"MaxBytesReader", Func, 0},
+		{"MethodConnect", Const, 6},
+		{"MethodDelete", Const, 6},
+		{"MethodGet", Const, 6},
+		{"MethodHead", Const, 6},
+		{"MethodOptions", Const, 6},
+		{"MethodPatch", Const, 6},
+		{"MethodPost", Const, 6},
+		{"MethodPut", Const, 6},
+		{"MethodTrace", Const, 6},
+		{"NewFileTransport", Func, 0},
+		{"NewFileTransportFS", Func, 22},
+		{"NewRequest", Func, 0},
+		{"NewRequestWithContext", Func, 13},
+		{"NewResponseController", Func, 20},
+		{"NewServeMux", Func, 0},
+		{"NoBody", Var, 8},
+		{"NotFound", Func, 0},
+		{"NotFoundHandler", Func, 0},
+		{"ParseCookie", Func, 23},
+		{"ParseHTTPVersion", Func, 0},
+		{"ParseSetCookie", Func, 23},
+		{"ParseTime", Func, 1},
+		{"Post", Func, 0},
+		{"PostForm", Func, 0},
+		{"ProtocolError", Type, 0},
+		{"ProtocolError.ErrorString", Field, 0},
+		{"Protocols", Type, 24},
+		{"ProxyFromEnvironment", Func, 0},
+		{"ProxyURL", Func, 0},
+		{"PushOptions", Type, 8},
+		{"PushOptions.Header", Field, 8},
+		{"PushOptions.Method", Field, 8},
+		{"Pusher", Type, 8},
+		{"ReadRequest", Func, 0},
+		{"ReadResponse", Func, 0},
+		{"Redirect", Func, 0},
+		{"RedirectHandler", Func, 0},
+		{"Request", Type, 0},
+		{"Request.Body", Field, 0},
+		{"Request.Cancel", Field, 5},
+		{"Request.Close", Field, 0},
+		{"Request.ContentLength", Field, 0},
+		{"Request.Form", Field, 0},
+		{"Request.GetBody", Field, 8},
+		{"Request.Header", Field, 0},
+		{"Request.Host", Field, 0},
+		{"Request.Method", Field, 0},
+		{"Request.MultipartForm", Field, 0},
+		{"Request.Pattern", Field, 23},
+		{"Request.PostForm", Field, 1},
+		{"Request.Proto", Field, 0},
+		{"Request.ProtoMajor", Field, 0},
+		{"Request.ProtoMinor", Field, 0},
+		{"Request.RemoteAddr", Field, 0},
+		{"Request.RequestURI", Field, 0},
+		{"Request.Response", Field, 7},
+		{"Request.TLS", Field, 0},
+		{"Request.Trailer", Field, 0},
+		{"Request.TransferEncoding", Field, 0},
+		{"Request.URL", Field, 0},
+		{"Response", Type, 0},
+		{"Response.Body", Field, 0},
+		{"Response.Close", Field, 0},
+		{"Response.ContentLength", Field, 0},
+		{"Response.Header", Field, 0},
+		{"Response.Proto", Field, 0},
+		{"Response.ProtoMajor", Field, 0},
+		{"Response.ProtoMinor", Field, 0},
+		{"Response.Request", Field, 0},
+		{"Response.Status", Field, 0},
+		{"Response.StatusCode", Field, 0},
+		{"Response.TLS", Field, 3},
+		{"Response.Trailer", Field, 0},
+		{"Response.TransferEncoding", Field, 0},
+		{"Response.Uncompressed", Field, 7},
+		{"ResponseController", Type, 20},
+		{"ResponseWriter", Type, 0},
+		{"RoundTripper", Type, 0},
+		{"SameSite", Type, 11},
+		{"SameSiteDefaultMode", Const, 11},
+		{"SameSiteLaxMode", Const, 11},
+		{"SameSiteNoneMode", Const, 13},
+		{"SameSiteStrictMode", Const, 11},
+		{"Serve", Func, 0},
+		{"ServeContent", Func, 0},
+		{"ServeFile", Func, 0},
+		{"ServeFileFS", Func, 22},
+		{"ServeMux", Type, 0},
+		{"ServeTLS", Func, 9},
+		{"Server", Type, 0},
+		{"Server.Addr", Field, 0},
+		{"Server.BaseContext", Field, 13},
+		{"Server.ConnContext", Field, 13},
+		{"Server.ConnState", Field, 3},
+		{"Server.DisableGeneralOptionsHandler", Field, 20},
+		{"Server.ErrorLog", Field, 3},
+		{"Server.HTTP2", Field, 24},
+		{"Server.Handler", Field, 0},
+		{"Server.IdleTimeout", Field, 8},
+		{"Server.MaxHeaderBytes", Field, 0},
+		{"Server.Protocols", Field, 24},
+		{"Server.ReadHeaderTimeout", Field, 8},
+		{"Server.ReadTimeout", Field, 0},
+		{"Server.TLSConfig", Field, 0},
+		{"Server.TLSNextProto", Field, 1},
+		{"Server.WriteTimeout", Field, 0},
+		{"ServerContextKey", Var, 7},
+		{"SetCookie", Func, 0},
+		{"StateActive", Const, 3},
+		{"StateClosed", Const, 3},
+		{"StateHijacked", Const, 3},
+		{"StateIdle", Const, 3},
+		{"StateNew", Const, 3},
+		{"StatusAccepted", Const, 0},
+		{"StatusAlreadyReported", Const, 7},
+		{"StatusBadGateway", Const, 0},
+		{"StatusBadRequest", Const, 0},
+		{"StatusConflict", Const, 0},
+		{"StatusContinue", Const, 0},
+		{"StatusCreated", Const, 0},
+		{"StatusEarlyHints", Const, 13},
+		{"StatusExpectationFailed", Const, 0},
+		{"StatusFailedDependency", Const, 7},
+		{"StatusForbidden", Const, 0},
+		{"StatusFound", Const, 0},
+		{"StatusGatewayTimeout", Const, 0},
+		{"StatusGone", Const, 0},
+		{"StatusHTTPVersionNotSupported", Const, 0},
+		{"StatusIMUsed", Const, 7},
+		{"StatusInsufficientStorage", Const, 7},
+		{"StatusInternalServerError", Const, 0},
+		{"StatusLengthRequired", Const, 0},
+		{"StatusLocked", Const, 7},
+		{"StatusLoopDetected", Const, 7},
+		{"StatusMethodNotAllowed", Const, 0},
+		{"StatusMisdirectedRequest", Const, 11},
+		{"StatusMovedPermanently", Const, 0},
+		{"StatusMultiStatus", Const, 7},
+		{"StatusMultipleChoices", Const, 0},
+		{"StatusNetworkAuthenticationRequired", Const, 6},
+		{"StatusNoContent", Const, 0},
+		{"StatusNonAuthoritativeInfo", Const, 0},
+		{"StatusNotAcceptable", Const, 0},
+		{"StatusNotExtended", Const, 7},
+		{"StatusNotFound", Const, 0},
+		{"StatusNotImplemented", Const, 0},
+		{"StatusNotModified", Const, 0},
+		{"StatusOK", Const, 0},
+		{"StatusPartialContent", Const, 0},
+		{"StatusPaymentRequired", Const, 0},
+		{"StatusPermanentRedirect", Const, 7},
+		{"StatusPreconditionFailed", Const, 0},
+		{"StatusPreconditionRequired", Const, 6},
+		{"StatusProcessing", Const, 7},
+		{"StatusProxyAuthRequired", Const, 0},
+		{"StatusRequestEntityTooLarge", Const, 0},
+		{"StatusRequestHeaderFieldsTooLarge", Const, 6},
+		{"StatusRequestTimeout", Const, 0},
+		{"StatusRequestURITooLong", Const, 0},
+		{"StatusRequestedRangeNotSatisfiable", Const, 0},
+		{"StatusResetContent", Const, 0},
+		{"StatusSeeOther", Const, 0},
+		{"StatusServiceUnavailable", Const, 0},
+		{"StatusSwitchingProtocols", Const, 0},
+		{"StatusTeapot", Const, 0},
+		{"StatusTemporaryRedirect", Const, 0},
+		{"StatusText", Func, 0},
+		{"StatusTooEarly", Const, 12},
+		{"StatusTooManyRequests", Const, 6},
+		{"StatusUnauthorized", Const, 0},
+		{"StatusUnavailableForLegalReasons", Const, 6},
+		{"StatusUnprocessableEntity", Const, 7},
+		{"StatusUnsupportedMediaType", Const, 0},
+		{"StatusUpgradeRequired", Const, 7},
+		{"StatusUseProxy", Const, 0},
+		{"StatusVariantAlsoNegotiates", Const, 7},
+		{"StripPrefix", Func, 0},
+		{"TimeFormat", Const, 0},
+		{"TimeoutHandler", Func, 0},
+		{"TrailerPrefix", Const, 8},
+		{"Transport", Type, 0},
+		{"Transport.Dial", Field, 0},
+		{"Transport.DialContext", Field, 7},
+		{"Transport.DialTLS", Field, 4},
+		{"Transport.DialTLSContext", Field, 14},
+		{"Transport.DisableCompression", Field, 0},
+		{"Transport.DisableKeepAlives", Field, 0},
+		{"Transport.ExpectContinueTimeout", Field, 6},
+		{"Transport.ForceAttemptHTTP2", Field, 13},
+		{"Transport.GetProxyConnectHeader", Field, 16},
+		{"Transport.HTTP2", Field, 24},
+		{"Transport.IdleConnTimeout", Field, 7},
+		{"Transport.MaxConnsPerHost", Field, 11},
+		{"Transport.MaxIdleConns", Field, 7},
+		{"Transport.MaxIdleConnsPerHost", Field, 0},
+		{"Transport.MaxResponseHeaderBytes", Field, 7},
+		{"Transport.OnProxyConnectResponse", Field, 20},
+		{"Transport.Protocols", Field, 24},
+		{"Transport.Proxy", Field, 0},
+		{"Transport.ProxyConnectHeader", Field, 8},
+		{"Transport.ReadBufferSize", Field, 13},
+		{"Transport.ResponseHeaderTimeout", Field, 1},
+		{"Transport.TLSClientConfig", Field, 0},
+		{"Transport.TLSHandshakeTimeout", Field, 3},
+		{"Transport.TLSNextProto", Field, 6},
+		{"Transport.WriteBufferSize", Field, 13},
+	},
+	"net/http/cgi": {
+		{"(*Handler).ServeHTTP", Method, 0},
+		{"Handler", Type, 0},
+		{"Handler.Args", Field, 0},
+		{"Handler.Dir", Field, 0},
+		{"Handler.Env", Field, 0},
+		{"Handler.InheritEnv", Field, 0},
+		{"Handler.Logger", Field, 0},
+		{"Handler.Path", Field, 0},
+		{"Handler.PathLocationHandler", Field, 0},
+		{"Handler.Root", Field, 0},
+		{"Handler.Stderr", Field, 7},
+		{"Request", Func, 0},
+		{"RequestFromMap", Func, 0},
+		{"Serve", Func, 0},
+	},
+	"net/http/cookiejar": {
+		{"(*Jar).Cookies", Method, 1},
+		{"(*Jar).SetCookies", Method, 1},
+		{"Jar", Type, 1},
+		{"New", Func, 1},
+		{"Options", Type, 1},
+		{"Options.PublicSuffixList", Field, 1},
+		{"PublicSuffixList", Type, 1},
+	},
+	"net/http/fcgi": {
+		{"ErrConnClosed", Var, 5},
+		{"ErrRequestAborted", Var, 5},
+		{"ProcessEnv", Func, 9},
+		{"Serve", Func, 0},
+	},
+	"net/http/httptest": {
+		{"(*ResponseRecorder).Flush", Method, 0},
+		{"(*ResponseRecorder).Header", Method, 0},
+		{"(*ResponseRecorder).Result", Method, 7},
+		{"(*ResponseRecorder).Write", Method, 0},
+		{"(*ResponseRecorder).WriteHeader", Method, 0},
+		{"(*ResponseRecorder).WriteString", Method, 6},
+		{"(*Server).Certificate", Method, 9},
+		{"(*Server).Client", Method, 9},
+		{"(*Server).Close", Method, 0},
+		{"(*Server).CloseClientConnections", Method, 0},
+		{"(*Server).Start", Method, 0},
+		{"(*Server).StartTLS", Method, 0},
+		{"DefaultRemoteAddr", Const, 0},
+		{"NewRecorder", Func, 0},
+		{"NewRequest", Func, 7},
+		{"NewRequestWithContext", Func, 23},
+		{"NewServer", Func, 0},
+		{"NewTLSServer", Func, 0},
+		{"NewUnstartedServer", Func, 0},
+		{"ResponseRecorder", Type, 0},
+		{"ResponseRecorder.Body", Field, 0},
+		{"ResponseRecorder.Code", Field, 0},
+		{"ResponseRecorder.Flushed", Field, 0},
+		{"ResponseRecorder.HeaderMap", Field, 0},
+		{"Server", Type, 0},
+		{"Server.Config", Field, 0},
+		{"Server.EnableHTTP2", Field, 14},
+		{"Server.Listener", Field, 0},
+		{"Server.TLS", Field, 0},
+		{"Server.URL", Field, 0},
+	},
+	"net/http/httptrace": {
+		{"ClientTrace", Type, 7},
+		{"ClientTrace.ConnectDone", Field, 7},
+		{"ClientTrace.ConnectStart", Field, 7},
+		{"ClientTrace.DNSDone", Field, 7},
+		{"ClientTrace.DNSStart", Field, 7},
+		{"ClientTrace.GetConn", Field, 7},
+		{"ClientTrace.Got100Continue", Field, 7},
+		{"ClientTrace.Got1xxResponse", Field, 11},
+		{"ClientTrace.GotConn", Field, 7},
+		{"ClientTrace.GotFirstResponseByte", Field, 7},
+		{"ClientTrace.PutIdleConn", Field, 7},
+		{"ClientTrace.TLSHandshakeDone", Field, 8},
+		{"ClientTrace.TLSHandshakeStart", Field, 8},
+		{"ClientTrace.Wait100Continue", Field, 7},
+		{"ClientTrace.WroteHeaderField", Field, 11},
+		{"ClientTrace.WroteHeaders", Field, 7},
+		{"ClientTrace.WroteRequest", Field, 7},
+		{"ContextClientTrace", Func, 7},
+		{"DNSDoneInfo", Type, 7},
+		{"DNSDoneInfo.Addrs", Field, 7},
+		{"DNSDoneInfo.Coalesced", Field, 7},
+		{"DNSDoneInfo.Err", Field, 7},
+		{"DNSStartInfo", Type, 7},
+		{"DNSStartInfo.Host", Field, 7},
+		{"GotConnInfo", Type, 7},
+		{"GotConnInfo.Conn", Field, 7},
+		{"GotConnInfo.IdleTime", Field, 7},
+		{"GotConnInfo.Reused", Field, 7},
+		{"GotConnInfo.WasIdle", Field, 7},
+		{"WithClientTrace", Func, 7},
+		{"WroteRequestInfo", Type, 7},
+		{"WroteRequestInfo.Err", Field, 7},
+	},
+	"net/http/httputil": {
+		{"(*ClientConn).Close", Method, 0},
+		{"(*ClientConn).Do", Method, 0},
+		{"(*ClientConn).Hijack", Method, 0},
+		{"(*ClientConn).Pending", Method, 0},
+		{"(*ClientConn).Read", Method, 0},
+		{"(*ClientConn).Write", Method, 0},
+		{"(*ProxyRequest).SetURL", Method, 20},
+		{"(*ProxyRequest).SetXForwarded", Method, 20},
+		{"(*ReverseProxy).ServeHTTP", Method, 0},
+		{"(*ServerConn).Close", Method, 0},
+		{"(*ServerConn).Hijack", Method, 0},
+		{"(*ServerConn).Pending", Method, 0},
+		{"(*ServerConn).Read", Method, 0},
+		{"(*ServerConn).Write", Method, 0},
+		{"BufferPool", Type, 6},
+		{"ClientConn", Type, 0},
+		{"DumpRequest", Func, 0},
+		{"DumpRequestOut", Func, 0},
+		{"DumpResponse", Func, 0},
+		{"ErrClosed", Var, 0},
+		{"ErrLineTooLong", Var, 0},
+		{"ErrPersistEOF", Var, 0},
+		{"ErrPipeline", Var, 0},
+		{"NewChunkedReader", Func, 0},
+		{"NewChunkedWriter", Func, 0},
+		{"NewClientConn", Func, 0},
+		{"NewProxyClientConn", Func, 0},
+		{"NewServerConn", Func, 0},
+		{"NewSingleHostReverseProxy", Func, 0},
+		{"ProxyRequest", Type, 20},
+		{"ProxyRequest.In", Field, 20},
+		{"ProxyRequest.Out", Field, 20},
+		{"ReverseProxy", Type, 0},
+		{"ReverseProxy.BufferPool", Field, 6},
+		{"ReverseProxy.Director", Field, 0},
+		{"ReverseProxy.ErrorHandler", Field, 11},
+		{"ReverseProxy.ErrorLog", Field, 4},
+		{"ReverseProxy.FlushInterval", Field, 0},
+		{"ReverseProxy.ModifyResponse", Field, 8},
+		{"ReverseProxy.Rewrite", Field, 20},
+		{"ReverseProxy.Transport", Field, 0},
+		{"ServerConn", Type, 0},
+	},
+	"net/http/pprof": {
+		{"Cmdline", Func, 0},
+		{"Handler", Func, 0},
+		{"Index", Func, 0},
+		{"Profile", Func, 0},
+		{"Symbol", Func, 0},
+		{"Trace", Func, 5},
+	},
+	"net/mail": {
+		{"(*Address).String", Method, 0},
+		{"(*AddressParser).Parse", Method, 5},
+		{"(*AddressParser).ParseList", Method, 5},
+		{"(Header).AddressList", Method, 0},
+		{"(Header).Date", Method, 0},
+		{"(Header).Get", Method, 0},
+		{"Address", Type, 0},
+		{"Address.Address", Field, 0},
+		{"Address.Name", Field, 0},
+		{"AddressParser", Type, 5},
+		{"AddressParser.WordDecoder", Field, 5},
+		{"ErrHeaderNotPresent", Var, 0},
+		{"Header", Type, 0},
+		{"Message", Type, 0},
+		{"Message.Body", Field, 0},
+		{"Message.Header", Field, 0},
+		{"ParseAddress", Func, 1},
+		{"ParseAddressList", Func, 1},
+		{"ParseDate", Func, 8},
+		{"ReadMessage", Func, 0},
+	},
+	"net/netip": {
+		{"(*Addr).UnmarshalBinary", Method, 18},
+		{"(*Addr).UnmarshalText", Method, 18},
+		{"(*AddrPort).UnmarshalBinary", Method, 18},
+		{"(*AddrPort).UnmarshalText", Method, 18},
+		{"(*Prefix).UnmarshalBinary", Method, 18},
+		{"(*Prefix).UnmarshalText", Method, 18},
+		{"(Addr).AppendBinary", Method, 24},
+		{"(Addr).AppendText", Method, 24},
+		{"(Addr).AppendTo", Method, 18},
+		{"(Addr).As16", Method, 18},
+		{"(Addr).As4", Method, 18},
+		{"(Addr).AsSlice", Method, 18},
+		{"(Addr).BitLen", Method, 18},
+		{"(Addr).Compare", Method, 18},
+		{"(Addr).Is4", Method, 18},
+		{"(Addr).Is4In6", Method, 18},
+		{"(Addr).Is6", Method, 18},
+		{"(Addr).IsGlobalUnicast", Method, 18},
+		{"(Addr).IsInterfaceLocalMulticast", Method, 18},
+		{"(Addr).IsLinkLocalMulticast", Method, 18},
+		{"(Addr).IsLinkLocalUnicast", Method, 18},
+		{"(Addr).IsLoopback", Method, 18},
+		{"(Addr).IsMulticast", Method, 18},
+		{"(Addr).IsPrivate", Method, 18},
+		{"(Addr).IsUnspecified", Method, 18},
+		{"(Addr).IsValid", Method, 18},
+		{"(Addr).Less", Method, 18},
+		{"(Addr).MarshalBinary", Method, 18},
+		{"(Addr).MarshalText", Method, 18},
+		{"(Addr).Next", Method, 18},
+		{"(Addr).Prefix", Method, 18},
+		{"(Addr).Prev", Method, 18},
+		{"(Addr).String", Method, 18},
+		{"(Addr).StringExpanded", Method, 18},
+		{"(Addr).Unmap", Method, 18},
+		{"(Addr).WithZone", Method, 18},
+		{"(Addr).Zone", Method, 18},
+		{"(AddrPort).Addr", Method, 18},
+		{"(AddrPort).AppendBinary", Method, 24},
+		{"(AddrPort).AppendText", Method, 24},
+		{"(AddrPort).AppendTo", Method, 18},
+		{"(AddrPort).Compare", Method, 22},
+		{"(AddrPort).IsValid", Method, 18},
+		{"(AddrPort).MarshalBinary", Method, 18},
+		{"(AddrPort).MarshalText", Method, 18},
+		{"(AddrPort).Port", Method, 18},
+		{"(AddrPort).String", Method, 18},
+		{"(Prefix).Addr", Method, 18},
+		{"(Prefix).AppendBinary", Method, 24},
+		{"(Prefix).AppendText", Method, 24},
+		{"(Prefix).AppendTo", Method, 18},
+		{"(Prefix).Bits", Method, 18},
+		{"(Prefix).Contains", Method, 18},
+		{"(Prefix).IsSingleIP", Method, 18},
+		{"(Prefix).IsValid", Method, 18},
+		{"(Prefix).MarshalBinary", Method, 18},
+		{"(Prefix).MarshalText", Method, 18},
+		{"(Prefix).Masked", Method, 18},
+		{"(Prefix).Overlaps", Method, 18},
+		{"(Prefix).String", Method, 18},
+		{"Addr", Type, 18},
+		{"AddrFrom16", Func, 18},
+		{"AddrFrom4", Func, 18},
+		{"AddrFromSlice", Func, 18},
+		{"AddrPort", Type, 18},
+		{"AddrPortFrom", Func, 18},
+		{"IPv4Unspecified", Func, 18},
+		{"IPv6LinkLocalAllNodes", Func, 18},
+		{"IPv6LinkLocalAllRouters", Func, 20},
+		{"IPv6Loopback", Func, 20},
+		{"IPv6Unspecified", Func, 18},
+		{"MustParseAddr", Func, 18},
+		{"MustParseAddrPort", Func, 18},
+		{"MustParsePrefix", Func, 18},
+		{"ParseAddr", Func, 18},
+		{"ParseAddrPort", Func, 18},
+		{"ParsePrefix", Func, 18},
+		{"Prefix", Type, 18},
+		{"PrefixFrom", Func, 18},
+	},
+	"net/rpc": {
+		{"(*Client).Call", Method, 0},
+		{"(*Client).Close", Method, 0},
+		{"(*Client).Go", Method, 0},
+		{"(*Server).Accept", Method, 0},
+		{"(*Server).HandleHTTP", Method, 0},
+		{"(*Server).Register", Method, 0},
+		{"(*Server).RegisterName", Method, 0},
+		{"(*Server).ServeCodec", Method, 0},
+		{"(*Server).ServeConn", Method, 0},
+		{"(*Server).ServeHTTP", Method, 0},
+		{"(*Server).ServeRequest", Method, 0},
+		{"(ServerError).Error", Method, 0},
+		{"Accept", Func, 0},
+		{"Call", Type, 0},
+		{"Call.Args", Field, 0},
+		{"Call.Done", Field, 0},
+		{"Call.Error", Field, 0},
+		{"Call.Reply", Field, 0},
+		{"Call.ServiceMethod", Field, 0},
+		{"Client", Type, 0},
+		{"ClientCodec", Type, 0},
+		{"DefaultDebugPath", Const, 0},
+		{"DefaultRPCPath", Const, 0},
+		{"DefaultServer", Var, 0},
+		{"Dial", Func, 0},
+		{"DialHTTP", Func, 0},
+		{"DialHTTPPath", Func, 0},
+		{"ErrShutdown", Var, 0},
+		{"HandleHTTP", Func, 0},
+		{"NewClient", Func, 0},
+		{"NewClientWithCodec", Func, 0},
+		{"NewServer", Func, 0},
+		{"Register", Func, 0},
+		{"RegisterName", Func, 0},
+		{"Request", Type, 0},
+		{"Request.Seq", Field, 0},
+		{"Request.ServiceMethod", Field, 0},
+		{"Response", Type, 0},
+		{"Response.Error", Field, 0},
+		{"Response.Seq", Field, 0},
+		{"Response.ServiceMethod", Field, 0},
+		{"ServeCodec", Func, 0},
+		{"ServeConn", Func, 0},
+		{"ServeRequest", Func, 0},
+		{"Server", Type, 0},
+		{"ServerCodec", Type, 0},
+		{"ServerError", Type, 0},
+	},
+	"net/rpc/jsonrpc": {
+		{"Dial", Func, 0},
+		{"NewClient", Func, 0},
+		{"NewClientCodec", Func, 0},
+		{"NewServerCodec", Func, 0},
+		{"ServeConn", Func, 0},
+	},
+	"net/smtp": {
+		{"(*Client).Auth", Method, 0},
+		{"(*Client).Close", Method, 2},
+		{"(*Client).Data", Method, 0},
+		{"(*Client).Extension", Method, 0},
+		{"(*Client).Hello", Method, 1},
+		{"(*Client).Mail", Method, 0},
+		{"(*Client).Noop", Method, 10},
+		{"(*Client).Quit", Method, 0},
+		{"(*Client).Rcpt", Method, 0},
+		{"(*Client).Reset", Method, 0},
+		{"(*Client).StartTLS", Method, 0},
+		{"(*Client).TLSConnectionState", Method, 5},
+		{"(*Client).Verify", Method, 0},
+		{"Auth", Type, 0},
+		{"CRAMMD5Auth", Func, 0},
+		{"Client", Type, 0},
+		{"Client.Text", Field, 0},
+		{"Dial", Func, 0},
+		{"NewClient", Func, 0},
+		{"PlainAuth", Func, 0},
+		{"SendMail", Func, 0},
+		{"ServerInfo", Type, 0},
+		{"ServerInfo.Auth", Field, 0},
+		{"ServerInfo.Name", Field, 0},
+		{"ServerInfo.TLS", Field, 0},
+	},
+	"net/textproto": {
+		{"(*Conn).Close", Method, 0},
+		{"(*Conn).Cmd", Method, 0},
+		{"(*Conn).DotReader", Method, 0},
+		{"(*Conn).DotWriter", Method, 0},
+		{"(*Conn).EndRequest", Method, 0},
+		{"(*Conn).EndResponse", Method, 0},
+		{"(*Conn).Next", Method, 0},
+		{"(*Conn).PrintfLine", Method, 0},
+		{"(*Conn).ReadCodeLine", Method, 0},
+		{"(*Conn).ReadContinuedLine", Method, 0},
+		{"(*Conn).ReadContinuedLineBytes", Method, 0},
+		{"(*Conn).ReadDotBytes", Method, 0},
+		{"(*Conn).ReadDotLines", Method, 0},
+		{"(*Conn).ReadLine", Method, 0},
+		{"(*Conn).ReadLineBytes", Method, 0},
+		{"(*Conn).ReadMIMEHeader", Method, 0},
+		{"(*Conn).ReadResponse", Method, 0},
+		{"(*Conn).StartRequest", Method, 0},
+		{"(*Conn).StartResponse", Method, 0},
+		{"(*Error).Error", Method, 0},
+		{"(*Pipeline).EndRequest", Method, 0},
+		{"(*Pipeline).EndResponse", Method, 0},
+		{"(*Pipeline).Next", Method, 0},
+		{"(*Pipeline).StartRequest", Method, 0},
+		{"(*Pipeline).StartResponse", Method, 0},
+		{"(*Reader).DotReader", Method, 0},
+		{"(*Reader).ReadCodeLine", Method, 0},
+		{"(*Reader).ReadContinuedLine", Method, 0},
+		{"(*Reader).ReadContinuedLineBytes", Method, 0},
+		{"(*Reader).ReadDotBytes", Method, 0},
+		{"(*Reader).ReadDotLines", Method, 0},
+		{"(*Reader).ReadLine", Method, 0},
+		{"(*Reader).ReadLineBytes", Method, 0},
+		{"(*Reader).ReadMIMEHeader", Method, 0},
+		{"(*Reader).ReadResponse", Method, 0},
+		{"(*Writer).DotWriter", Method, 0},
+		{"(*Writer).PrintfLine", Method, 0},
+		{"(MIMEHeader).Add", Method, 0},
+		{"(MIMEHeader).Del", Method, 0},
+		{"(MIMEHeader).Get", Method, 0},
+		{"(MIMEHeader).Set", Method, 0},
+		{"(MIMEHeader).Values", Method, 14},
+		{"(ProtocolError).Error", Method, 0},
+		{"CanonicalMIMEHeaderKey", Func, 0},
+		{"Conn", Type, 0},
+		{"Conn.Pipeline", Field, 0},
+		{"Conn.Reader", Field, 0},
+		{"Conn.Writer", Field, 0},
+		{"Dial", Func, 0},
+		{"Error", Type, 0},
+		{"Error.Code", Field, 0},
+		{"Error.Msg", Field, 0},
+		{"MIMEHeader", Type, 0},
+		{"NewConn", Func, 0},
+		{"NewReader", Func, 0},
+		{"NewWriter", Func, 0},
+		{"Pipeline", Type, 0},
+		{"ProtocolError", Type, 0},
+		{"Reader", Type, 0},
+		{"Reader.R", Field, 0},
+		{"TrimBytes", Func, 1},
+		{"TrimString", Func, 1},
+		{"Writer", Type, 0},
+		{"Writer.W", Field, 0},
+	},
+	"net/url": {
+		{"(*Error).Error", Method, 0},
+		{"(*Error).Temporary", Method, 6},
+		{"(*Error).Timeout", Method, 6},
+		{"(*Error).Unwrap", Method, 13},
+		{"(*URL).AppendBinary", Method, 24},
+		{"(*URL).EscapedFragment", Method, 15},
+		{"(*URL).EscapedPath", Method, 5},
+		{"(*URL).Hostname", Method, 8},
+		{"(*URL).IsAbs", Method, 0},
+		{"(*URL).JoinPath", Method, 19},
+		{"(*URL).MarshalBinary", Method, 8},
+		{"(*URL).Parse", Method, 0},
+		{"(*URL).Port", Method, 8},
+		{"(*URL).Query", Method, 0},
+		{"(*URL).Redacted", Method, 15},
+		{"(*URL).RequestURI", Method, 0},
+		{"(*URL).ResolveReference", Method, 0},
+		{"(*URL).String", Method, 0},
+		{"(*URL).UnmarshalBinary", Method, 8},
+		{"(*Userinfo).Password", Method, 0},
+		{"(*Userinfo).String", Method, 0},
+		{"(*Userinfo).Username", Method, 0},
+		{"(EscapeError).Error", Method, 0},
+		{"(InvalidHostError).Error", Method, 6},
+		{"(Values).Add", Method, 0},
+		{"(Values).Del", Method, 0},
+		{"(Values).Encode", Method, 0},
+		{"(Values).Get", Method, 0},
+		{"(Values).Has", Method, 17},
+		{"(Values).Set", Method, 0},
+		{"Error", Type, 0},
+		{"Error.Err", Field, 0},
+		{"Error.Op", Field, 0},
+		{"Error.URL", Field, 0},
+		{"EscapeError", Type, 0},
+		{"InvalidHostError", Type, 6},
+		{"JoinPath", Func, 19},
+		{"Parse", Func, 0},
+		{"ParseQuery", Func, 0},
+		{"ParseRequestURI", Func, 0},
+		{"PathEscape", Func, 8},
+		{"PathUnescape", Func, 8},
+		{"QueryEscape", Func, 0},
+		{"QueryUnescape", Func, 0},
+		{"URL", Type, 0},
+		{"URL.ForceQuery", Field, 7},
+		{"URL.Fragment", Field, 0},
+		{"URL.Host", Field, 0},
+		{"URL.OmitHost", Field, 19},
+		{"URL.Opaque", Field, 0},
+		{"URL.Path", Field, 0},
+		{"URL.RawFragment", Field, 15},
+		{"URL.RawPath", Field, 5},
+		{"URL.RawQuery", Field, 0},
+		{"URL.Scheme", Field, 0},
+		{"URL.User", Field, 0},
+		{"User", Func, 0},
+		{"UserPassword", Func, 0},
+		{"Userinfo", Type, 0},
+		{"Values", Type, 0},
+	},
+	"os": {
+		{"(*File).Chdir", Method, 0},
+		{"(*File).Chmod", Method, 0},
+		{"(*File).Chown", Method, 0},
+		{"(*File).Close", Method, 0},
+		{"(*File).Fd", Method, 0},
+		{"(*File).Name", Method, 0},
+		{"(*File).Read", Method, 0},
+		{"(*File).ReadAt", Method, 0},
+		{"(*File).ReadDir", Method, 16},
+		{"(*File).ReadFrom", Method, 15},
+		{"(*File).Readdir", Method, 0},
+		{"(*File).Readdirnames", Method, 0},
+		{"(*File).Seek", Method, 0},
+		{"(*File).SetDeadline", Method, 10},
+		{"(*File).SetReadDeadline", Method, 10},
+		{"(*File).SetWriteDeadline", Method, 10},
+		{"(*File).Stat", Method, 0},
+		{"(*File).Sync", Method, 0},
+		{"(*File).SyscallConn", Method, 12},
+		{"(*File).Truncate", Method, 0},
+		{"(*File).Write", Method, 0},
+		{"(*File).WriteAt", Method, 0},
+		{"(*File).WriteString", Method, 0},
+		{"(*File).WriteTo", Method, 22},
+		{"(*LinkError).Error", Method, 0},
+		{"(*LinkError).Unwrap", Method, 13},
+		{"(*PathError).Error", Method, 0},
+		{"(*PathError).Timeout", Method, 10},
+		{"(*PathError).Unwrap", Method, 13},
+		{"(*Process).Kill", Method, 0},
+		{"(*Process).Release", Method, 0},
+		{"(*Process).Signal", Method, 0},
+		{"(*Process).Wait", Method, 0},
+		{"(*ProcessState).ExitCode", Method, 12},
+		{"(*ProcessState).Exited", Method, 0},
+		{"(*ProcessState).Pid", Method, 0},
+		{"(*ProcessState).String", Method, 0},
+		{"(*ProcessState).Success", Method, 0},
+		{"(*ProcessState).Sys", Method, 0},
+		{"(*ProcessState).SysUsage", Method, 0},
+		{"(*ProcessState).SystemTime", Method, 0},
+		{"(*ProcessState).UserTime", Method, 0},
+		{"(*Root).Close", Method, 24},
+		{"(*Root).Create", Method, 24},
+		{"(*Root).FS", Method, 24},
+		{"(*Root).Lstat", Method, 24},
+		{"(*Root).Mkdir", Method, 24},
+		{"(*Root).Name", Method, 24},
+		{"(*Root).Open", Method, 24},
+		{"(*Root).OpenFile", Method, 24},
+		{"(*Root).OpenRoot", Method, 24},
+		{"(*Root).Remove", Method, 24},
+		{"(*Root).Stat", Method, 24},
+		{"(*SyscallError).Error", Method, 0},
+		{"(*SyscallError).Timeout", Method, 10},
+		{"(*SyscallError).Unwrap", Method, 13},
+		{"(FileMode).IsDir", Method, 0},
+		{"(FileMode).IsRegular", Method, 1},
+		{"(FileMode).Perm", Method, 0},
+		{"(FileMode).String", Method, 0},
+		{"Args", Var, 0},
+		{"Chdir", Func, 0},
+		{"Chmod", Func, 0},
+		{"Chown", Func, 0},
+		{"Chtimes", Func, 0},
+		{"Clearenv", Func, 0},
+		{"CopyFS", Func, 23},
+		{"Create", Func, 0},
+		{"CreateTemp", Func, 16},
+		{"DevNull", Const, 0},
+		{"DirEntry", Type, 16},
+		{"DirFS", Func, 16},
+		{"Environ", Func, 0},
+		{"ErrClosed", Var, 8},
+		{"ErrDeadlineExceeded", Var, 15},
+		{"ErrExist", Var, 0},
+		{"ErrInvalid", Var, 0},
+		{"ErrNoDeadline", Var, 10},
+		{"ErrNotExist", Var, 0},
+		{"ErrPermission", Var, 0},
+		{"ErrProcessDone", Var, 16},
+		{"Executable", Func, 8},
+		{"Exit", Func, 0},
+		{"Expand", Func, 0},
+		{"ExpandEnv", Func, 0},
+		{"File", Type, 0},
+		{"FileInfo", Type, 0},
+		{"FileMode", Type, 0},
+		{"FindProcess", Func, 0},
+		{"Getegid", Func, 0},
+		{"Getenv", Func, 0},
+		{"Geteuid", Func, 0},
+		{"Getgid", Func, 0},
+		{"Getgroups", Func, 0},
+		{"Getpagesize", Func, 0},
+		{"Getpid", Func, 0},
+		{"Getppid", Func, 0},
+		{"Getuid", Func, 0},
+		{"Getwd", Func, 0},
+		{"Hostname", Func, 0},
+		{"Interrupt", Var, 0},
+		{"IsExist", Func, 0},
+		{"IsNotExist", Func, 0},
+		{"IsPathSeparator", Func, 0},
+		{"IsPermission", Func, 0},
+		{"IsTimeout", Func, 10},
+		{"Kill", Var, 0},
+		{"Lchown", Func, 0},
+		{"Link", Func, 0},
+		{"LinkError", Type, 0},
+		{"LinkError.Err", Field, 0},
+		{"LinkError.New", Field, 0},
+		{"LinkError.Old", Field, 0},
+		{"LinkError.Op", Field, 0},
+		{"LookupEnv", Func, 5},
+		{"Lstat", Func, 0},
+		{"Mkdir", Func, 0},
+		{"MkdirAll", Func, 0},
+		{"MkdirTemp", Func, 16},
+		{"ModeAppend", Const, 0},
+		{"ModeCharDevice", Const, 0},
+		{"ModeDevice", Const, 0},
+		{"ModeDir", Const, 0},
+		{"ModeExclusive", Const, 0},
+		{"ModeIrregular", Const, 11},
+		{"ModeNamedPipe", Const, 0},
+		{"ModePerm", Const, 0},
+		{"ModeSetgid", Const, 0},
+		{"ModeSetuid", Const, 0},
+		{"ModeSocket", Const, 0},
+		{"ModeSticky", Const, 0},
+		{"ModeSymlink", Const, 0},
+		{"ModeTemporary", Const, 0},
+		{"ModeType", Const, 0},
+		{"NewFile", Func, 0},
+		{"NewSyscallError", Func, 0},
+		{"O_APPEND", Const, 0},
+		{"O_CREATE", Const, 0},
+		{"O_EXCL", Const, 0},
+		{"O_RDONLY", Const, 0},
+		{"O_RDWR", Const, 0},
+		{"O_SYNC", Const, 0},
+		{"O_TRUNC", Const, 0},
+		{"O_WRONLY", Const, 0},
+		{"Open", Func, 0},
+		{"OpenFile", Func, 0},
+		{"OpenInRoot", Func, 24},
+		{"OpenRoot", Func, 24},
+		{"PathError", Type, 0},
+		{"PathError.Err", Field, 0},
+		{"PathError.Op", Field, 0},
+		{"PathError.Path", Field, 0},
+		{"PathListSeparator", Const, 0},
+		{"PathSeparator", Const, 0},
+		{"Pipe", Func, 0},
+		{"ProcAttr", Type, 0},
+		{"ProcAttr.Dir", Field, 0},
+		{"ProcAttr.Env", Field, 0},
+		{"ProcAttr.Files", Field, 0},
+		{"ProcAttr.Sys", Field, 0},
+		{"Process", Type, 0},
+		{"Process.Pid", Field, 0},
+		{"ProcessState", Type, 0},
+		{"ReadDir", Func, 16},
+		{"ReadFile", Func, 16},
+		{"Readlink", Func, 0},
+		{"Remove", Func, 0},
+		{"RemoveAll", Func, 0},
+		{"Rename", Func, 0},
+		{"Root", Type, 24},
+		{"SEEK_CUR", Const, 0},
+		{"SEEK_END", Const, 0},
+		{"SEEK_SET", Const, 0},
+		{"SameFile", Func, 0},
+		{"Setenv", Func, 0},
+		{"Signal", Type, 0},
+		{"StartProcess", Func, 0},
+		{"Stat", Func, 0},
+		{"Stderr", Var, 0},
+		{"Stdin", Var, 0},
+		{"Stdout", Var, 0},
+		{"Symlink", Func, 0},
+		{"SyscallError", Type, 0},
+		{"SyscallError.Err", Field, 0},
+		{"SyscallError.Syscall", Field, 0},
+		{"TempDir", Func, 0},
+		{"Truncate", Func, 0},
+		{"Unsetenv", Func, 4},
+		{"UserCacheDir", Func, 11},
+		{"UserConfigDir", Func, 13},
+		{"UserHomeDir", Func, 12},
+		{"WriteFile", Func, 16},
+	},
+	"os/exec": {
+		{"(*Cmd).CombinedOutput", Method, 0},
+		{"(*Cmd).Environ", Method, 19},
+		{"(*Cmd).Output", Method, 0},
+		{"(*Cmd).Run", Method, 0},
+		{"(*Cmd).Start", Method, 0},
+		{"(*Cmd).StderrPipe", Method, 0},
+		{"(*Cmd).StdinPipe", Method, 0},
+		{"(*Cmd).StdoutPipe", Method, 0},
+		{"(*Cmd).String", Method, 13},
+		{"(*Cmd).Wait", Method, 0},
+		{"(*Error).Error", Method, 0},
+		{"(*Error).Unwrap", Method, 13},
+		{"(*ExitError).Error", Method, 0},
+		{"(ExitError).ExitCode", Method, 12},
+		{"(ExitError).Exited", Method, 0},
+		{"(ExitError).Pid", Method, 0},
+		{"(ExitError).String", Method, 0},
+		{"(ExitError).Success", Method, 0},
+		{"(ExitError).Sys", Method, 0},
+		{"(ExitError).SysUsage", Method, 0},
+		{"(ExitError).SystemTime", Method, 0},
+		{"(ExitError).UserTime", Method, 0},
+		{"Cmd", Type, 0},
+		{"Cmd.Args", Field, 0},
+		{"Cmd.Cancel", Field, 20},
+		{"Cmd.Dir", Field, 0},
+		{"Cmd.Env", Field, 0},
+		{"Cmd.Err", Field, 19},
+		{"Cmd.ExtraFiles", Field, 0},
+		{"Cmd.Path", Field, 0},
+		{"Cmd.Process", Field, 0},
+		{"Cmd.ProcessState", Field, 0},
+		{"Cmd.Stderr", Field, 0},
+		{"Cmd.Stdin", Field, 0},
+		{"Cmd.Stdout", Field, 0},
+		{"Cmd.SysProcAttr", Field, 0},
+		{"Cmd.WaitDelay", Field, 20},
+		{"Command", Func, 0},
+		{"CommandContext", Func, 7},
+		{"ErrDot", Var, 19},
+		{"ErrNotFound", Var, 0},
+		{"ErrWaitDelay", Var, 20},
+		{"Error", Type, 0},
+		{"Error.Err", Field, 0},
+		{"Error.Name", Field, 0},
+		{"ExitError", Type, 0},
+		{"ExitError.ProcessState", Field, 0},
+		{"ExitError.Stderr", Field, 6},
+		{"LookPath", Func, 0},
+	},
+	"os/signal": {
+		{"Ignore", Func, 5},
+		{"Ignored", Func, 11},
+		{"Notify", Func, 0},
+		{"NotifyContext", Func, 16},
+		{"Reset", Func, 5},
+		{"Stop", Func, 1},
+	},
+	"os/user": {
+		{"(*User).GroupIds", Method, 7},
+		{"(UnknownGroupError).Error", Method, 7},
+		{"(UnknownGroupIdError).Error", Method, 7},
+		{"(UnknownUserError).Error", Method, 0},
+		{"(UnknownUserIdError).Error", Method, 0},
+		{"Current", Func, 0},
+		{"Group", Type, 7},
+		{"Group.Gid", Field, 7},
+		{"Group.Name", Field, 7},
+		{"Lookup", Func, 0},
+		{"LookupGroup", Func, 7},
+		{"LookupGroupId", Func, 7},
+		{"LookupId", Func, 0},
+		{"UnknownGroupError", Type, 7},
+		{"UnknownGroupIdError", Type, 7},
+		{"UnknownUserError", Type, 0},
+		{"UnknownUserIdError", Type, 0},
+		{"User", Type, 0},
+		{"User.Gid", Field, 0},
+		{"User.HomeDir", Field, 0},
+		{"User.Name", Field, 0},
+		{"User.Uid", Field, 0},
+		{"User.Username", Field, 0},
+	},
+	"path": {
+		{"Base", Func, 0},
+		{"Clean", Func, 0},
+		{"Dir", Func, 0},
+		{"ErrBadPattern", Var, 0},
+		{"Ext", Func, 0},
+		{"IsAbs", Func, 0},
+		{"Join", Func, 0},
+		{"Match", Func, 0},
+		{"Split", Func, 0},
+	},
+	"path/filepath": {
+		{"Abs", Func, 0},
+		{"Base", Func, 0},
+		{"Clean", Func, 0},
+		{"Dir", Func, 0},
+		{"ErrBadPattern", Var, 0},
+		{"EvalSymlinks", Func, 0},
+		{"Ext", Func, 0},
+		{"FromSlash", Func, 0},
+		{"Glob", Func, 0},
+		{"HasPrefix", Func, 0},
+		{"IsAbs", Func, 0},
+		{"IsLocal", Func, 20},
+		{"Join", Func, 0},
+		{"ListSeparator", Const, 0},
+		{"Localize", Func, 23},
+		{"Match", Func, 0},
+		{"Rel", Func, 0},
+		{"Separator", Const, 0},
+		{"SkipAll", Var, 20},
+		{"SkipDir", Var, 0},
+		{"Split", Func, 0},
+		{"SplitList", Func, 0},
+		{"ToSlash", Func, 0},
+		{"VolumeName", Func, 0},
+		{"Walk", Func, 0},
+		{"WalkDir", Func, 16},
+		{"WalkFunc", Type, 0},
+	},
+	"plugin": {
+		{"(*Plugin).Lookup", Method, 8},
+		{"Open", Func, 8},
+		{"Plugin", Type, 8},
+		{"Symbol", Type, 8},
+	},
+	"reflect": {
+		{"(*MapIter).Key", Method, 12},
+		{"(*MapIter).Next", Method, 12},
+		{"(*MapIter).Reset", Method, 18},
+		{"(*MapIter).Value", Method, 12},
+		{"(*ValueError).Error", Method, 0},
+		{"(ChanDir).String", Method, 0},
+		{"(Kind).String", Method, 0},
+		{"(Method).IsExported", Method, 17},
+		{"(StructField).IsExported", Method, 17},
+		{"(StructTag).Get", Method, 0},
+		{"(StructTag).Lookup", Method, 7},
+		{"(Value).Addr", Method, 0},
+		{"(Value).Bool", Method, 0},
+		{"(Value).Bytes", Method, 0},
+		{"(Value).Call", Method, 0},
+		{"(Value).CallSlice", Method, 0},
+		{"(Value).CanAddr", Method, 0},
+		{"(Value).CanComplex", Method, 18},
+		{"(Value).CanConvert", Method, 17},
+		{"(Value).CanFloat", Method, 18},
+		{"(Value).CanInt", Method, 18},
+		{"(Value).CanInterface", Method, 0},
+		{"(Value).CanSet", Method, 0},
+		{"(Value).CanUint", Method, 18},
+		{"(Value).Cap", Method, 0},
+		{"(Value).Clear", Method, 21},
+		{"(Value).Close", Method, 0},
+		{"(Value).Comparable", Method, 20},
+		{"(Value).Complex", Method, 0},
+		{"(Value).Convert", Method, 1},
+		{"(Value).Elem", Method, 0},
+		{"(Value).Equal", Method, 20},
+		{"(Value).Field", Method, 0},
+		{"(Value).FieldByIndex", Method, 0},
+		{"(Value).FieldByIndexErr", Method, 18},
+		{"(Value).FieldByName", Method, 0},
+		{"(Value).FieldByNameFunc", Method, 0},
+		{"(Value).Float", Method, 0},
+		{"(Value).Grow", Method, 20},
+		{"(Value).Index", Method, 0},
+		{"(Value).Int", Method, 0},
+		{"(Value).Interface", Method, 0},
+		{"(Value).InterfaceData", Method, 0},
+		{"(Value).IsNil", Method, 0},
+		{"(Value).IsValid", Method, 0},
+		{"(Value).IsZero", Method, 13},
+		{"(Value).Kind", Method, 0},
+		{"(Value).Len", Method, 0},
+		{"(Value).MapIndex", Method, 0},
+		{"(Value).MapKeys", Method, 0},
+		{"(Value).MapRange", Method, 12},
+		{"(Value).Method", Method, 0},
+		{"(Value).MethodByName", Method, 0},
+		{"(Value).NumField", Method, 0},
+		{"(Value).NumMethod", Method, 0},
+		{"(Value).OverflowComplex", Method, 0},
+		{"(Value).OverflowFloat", Method, 0},
+		{"(Value).OverflowInt", Method, 0},
+		{"(Value).OverflowUint", Method, 0},
+		{"(Value).Pointer", Method, 0},
+		{"(Value).Recv", Method, 0},
+		{"(Value).Send", Method, 0},
+		{"(Value).Seq", Method, 23},
+		{"(Value).Seq2", Method, 23},
+		{"(Value).Set", Method, 0},
+		{"(Value).SetBool", Method, 0},
+		{"(Value).SetBytes", Method, 0},
+		{"(Value).SetCap", Method, 2},
+		{"(Value).SetComplex", Method, 0},
+		{"(Value).SetFloat", Method, 0},
+		{"(Value).SetInt", Method, 0},
+		{"(Value).SetIterKey", Method, 18},
+		{"(Value).SetIterValue", Method, 18},
+		{"(Value).SetLen", Method, 0},
+		{"(Value).SetMapIndex", Method, 0},
+		{"(Value).SetPointer", Method, 0},
+		{"(Value).SetString", Method, 0},
+		{"(Value).SetUint", Method, 0},
+		{"(Value).SetZero", Method, 20},
+		{"(Value).Slice", Method, 0},
+		{"(Value).Slice3", Method, 2},
+		{"(Value).String", Method, 0},
+		{"(Value).TryRecv", Method, 0},
+		{"(Value).TrySend", Method, 0},
+		{"(Value).Type", Method, 0},
+		{"(Value).Uint", Method, 0},
+		{"(Value).UnsafeAddr", Method, 0},
+		{"(Value).UnsafePointer", Method, 18},
+		{"Append", Func, 0},
+		{"AppendSlice", Func, 0},
+		{"Array", Const, 0},
+		{"ArrayOf", Func, 5},
+		{"Bool", Const, 0},
+		{"BothDir", Const, 0},
+		{"Chan", Const, 0},
+		{"ChanDir", Type, 0},
+		{"ChanOf", Func, 1},
+		{"Complex128", Const, 0},
+		{"Complex64", Const, 0},
+		{"Copy", Func, 0},
+		{"DeepEqual", Func, 0},
+		{"Float32", Const, 0},
+		{"Float64", Const, 0},
+		{"Func", Const, 0},
+		{"FuncOf", Func, 5},
+		{"Indirect", Func, 0},
+		{"Int", Const, 0},
+		{"Int16", Const, 0},
+		{"Int32", Const, 0},
+		{"Int64", Const, 0},
+		{"Int8", Const, 0},
+		{"Interface", Const, 0},
+		{"Invalid", Const, 0},
+		{"Kind", Type, 0},
+		{"MakeChan", Func, 0},
+		{"MakeFunc", Func, 1},
+		{"MakeMap", Func, 0},
+		{"MakeMapWithSize", Func, 9},
+		{"MakeSlice", Func, 0},
+		{"Map", Const, 0},
+		{"MapIter", Type, 12},
+		{"MapOf", Func, 1},
+		{"Method", Type, 0},
+		{"Method.Func", Field, 0},
+		{"Method.Index", Field, 0},
+		{"Method.Name", Field, 0},
+		{"Method.PkgPath", Field, 0},
+		{"Method.Type", Field, 0},
+		{"New", Func, 0},
+		{"NewAt", Func, 0},
+		{"Pointer", Const, 18},
+		{"PointerTo", Func, 18},
+		{"Ptr", Const, 0},
+		{"PtrTo", Func, 0},
+		{"RecvDir", Const, 0},
+		{"Select", Func, 1},
+		{"SelectCase", Type, 1},
+		{"SelectCase.Chan", Field, 1},
+		{"SelectCase.Dir", Field, 1},
+		{"SelectCase.Send", Field, 1},
+		{"SelectDefault", Const, 1},
+		{"SelectDir", Type, 1},
+		{"SelectRecv", Const, 1},
+		{"SelectSend", Const, 1},
+		{"SendDir", Const, 0},
+		{"Slice", Const, 0},
+		{"SliceAt", Func, 23},
+		{"SliceHeader", Type, 0},
+		{"SliceHeader.Cap", Field, 0},
+		{"SliceHeader.Data", Field, 0},
+		{"SliceHeader.Len", Field, 0},
+		{"SliceOf", Func, 1},
+		{"String", Const, 0},
+		{"StringHeader", Type, 0},
+		{"StringHeader.Data", Field, 0},
+		{"StringHeader.Len", Field, 0},
+		{"Struct", Const, 0},
+		{"StructField", Type, 0},
+		{"StructField.Anonymous", Field, 0},
+		{"StructField.Index", Field, 0},
+		{"StructField.Name", Field, 0},
+		{"StructField.Offset", Field, 0},
+		{"StructField.PkgPath", Field, 0},
+		{"StructField.Tag", Field, 0},
+		{"StructField.Type", Field, 0},
+		{"StructOf", Func, 7},
+		{"StructTag", Type, 0},
+		{"Swapper", Func, 8},
+		{"Type", Type, 0},
+		{"TypeFor", Func, 22},
+		{"TypeOf", Func, 0},
+		{"Uint", Const, 0},
+		{"Uint16", Const, 0},
+		{"Uint32", Const, 0},
+		{"Uint64", Const, 0},
+		{"Uint8", Const, 0},
+		{"Uintptr", Const, 0},
+		{"UnsafePointer", Const, 0},
+		{"Value", Type, 0},
+		{"ValueError", Type, 0},
+		{"ValueError.Kind", Field, 0},
+		{"ValueError.Method", Field, 0},
+		{"ValueOf", Func, 0},
+		{"VisibleFields", Func, 17},
+		{"Zero", Func, 0},
+	},
+	"regexp": {
+		{"(*Regexp).AppendText", Method, 24},
+		{"(*Regexp).Copy", Method, 6},
+		{"(*Regexp).Expand", Method, 0},
+		{"(*Regexp).ExpandString", Method, 0},
+		{"(*Regexp).Find", Method, 0},
+		{"(*Regexp).FindAll", Method, 0},
+		{"(*Regexp).FindAllIndex", Method, 0},
+		{"(*Regexp).FindAllString", Method, 0},
+		{"(*Regexp).FindAllStringIndex", Method, 0},
+		{"(*Regexp).FindAllStringSubmatch", Method, 0},
+		{"(*Regexp).FindAllStringSubmatchIndex", Method, 0},
+		{"(*Regexp).FindAllSubmatch", Method, 0},
+		{"(*Regexp).FindAllSubmatchIndex", Method, 0},
+		{"(*Regexp).FindIndex", Method, 0},
+		{"(*Regexp).FindReaderIndex", Method, 0},
+		{"(*Regexp).FindReaderSubmatchIndex", Method, 0},
+		{"(*Regexp).FindString", Method, 0},
+		{"(*Regexp).FindStringIndex", Method, 0},
+		{"(*Regexp).FindStringSubmatch", Method, 0},
+		{"(*Regexp).FindStringSubmatchIndex", Method, 0},
+		{"(*Regexp).FindSubmatch", Method, 0},
+		{"(*Regexp).FindSubmatchIndex", Method, 0},
+		{"(*Regexp).LiteralPrefix", Method, 0},
+		{"(*Regexp).Longest", Method, 1},
+		{"(*Regexp).MarshalText", Method, 21},
+		{"(*Regexp).Match", Method, 0},
+		{"(*Regexp).MatchReader", Method, 0},
+		{"(*Regexp).MatchString", Method, 0},
+		{"(*Regexp).NumSubexp", Method, 0},
+		{"(*Regexp).ReplaceAll", Method, 0},
+		{"(*Regexp).ReplaceAllFunc", Method, 0},
+		{"(*Regexp).ReplaceAllLiteral", Method, 0},
+		{"(*Regexp).ReplaceAllLiteralString", Method, 0},
+		{"(*Regexp).ReplaceAllString", Method, 0},
+		{"(*Regexp).ReplaceAllStringFunc", Method, 0},
+		{"(*Regexp).Split", Method, 1},
+		{"(*Regexp).String", Method, 0},
+		{"(*Regexp).SubexpIndex", Method, 15},
+		{"(*Regexp).SubexpNames", Method, 0},
+		{"(*Regexp).UnmarshalText", Method, 21},
+		{"Compile", Func, 0},
+		{"CompilePOSIX", Func, 0},
+		{"Match", Func, 0},
+		{"MatchReader", Func, 0},
+		{"MatchString", Func, 0},
+		{"MustCompile", Func, 0},
+		{"MustCompilePOSIX", Func, 0},
+		{"QuoteMeta", Func, 0},
+		{"Regexp", Type, 0},
+	},
+	"regexp/syntax": {
+		{"(*Error).Error", Method, 0},
+		{"(*Inst).MatchEmptyWidth", Method, 0},
+		{"(*Inst).MatchRune", Method, 0},
+		{"(*Inst).MatchRunePos", Method, 3},
+		{"(*Inst).String", Method, 0},
+		{"(*Prog).Prefix", Method, 0},
+		{"(*Prog).StartCond", Method, 0},
+		{"(*Prog).String", Method, 0},
+		{"(*Regexp).CapNames", Method, 0},
+		{"(*Regexp).Equal", Method, 0},
+		{"(*Regexp).MaxCap", Method, 0},
+		{"(*Regexp).Simplify", Method, 0},
+		{"(*Regexp).String", Method, 0},
+		{"(ErrorCode).String", Method, 0},
+		{"(InstOp).String", Method, 3},
+		{"(Op).String", Method, 11},
+		{"ClassNL", Const, 0},
+		{"Compile", Func, 0},
+		{"DotNL", Const, 0},
+		{"EmptyBeginLine", Const, 0},
+		{"EmptyBeginText", Const, 0},
+		{"EmptyEndLine", Const, 0},
+		{"EmptyEndText", Const, 0},
+		{"EmptyNoWordBoundary", Const, 0},
+		{"EmptyOp", Type, 0},
+		{"EmptyOpContext", Func, 0},
+		{"EmptyWordBoundary", Const, 0},
+		{"ErrInternalError", Const, 0},
+		{"ErrInvalidCharClass", Const, 0},
+		{"ErrInvalidCharRange", Const, 0},
+		{"ErrInvalidEscape", Const, 0},
+		{"ErrInvalidNamedCapture", Const, 0},
+		{"ErrInvalidPerlOp", Const, 0},
+		{"ErrInvalidRepeatOp", Const, 0},
+		{"ErrInvalidRepeatSize", Const, 0},
+		{"ErrInvalidUTF8", Const, 0},
+		{"ErrLarge", Const, 20},
+		{"ErrMissingBracket", Const, 0},
+		{"ErrMissingParen", Const, 0},
+		{"ErrMissingRepeatArgument", Const, 0},
+		{"ErrNestingDepth", Const, 19},
+		{"ErrTrailingBackslash", Const, 0},
+		{"ErrUnexpectedParen", Const, 1},
+		{"Error", Type, 0},
+		{"Error.Code", Field, 0},
+		{"Error.Expr", Field, 0},
+		{"ErrorCode", Type, 0},
+		{"Flags", Type, 0},
+		{"FoldCase", Const, 0},
+		{"Inst", Type, 0},
+		{"Inst.Arg", Field, 0},
+		{"Inst.Op", Field, 0},
+		{"Inst.Out", Field, 0},
+		{"Inst.Rune", Field, 0},
+		{"InstAlt", Const, 0},
+		{"InstAltMatch", Const, 0},
+		{"InstCapture", Const, 0},
+		{"InstEmptyWidth", Const, 0},
+		{"InstFail", Const, 0},
+		{"InstMatch", Const, 0},
+		{"InstNop", Const, 0},
+		{"InstOp", Type, 0},
+		{"InstRune", Const, 0},
+		{"InstRune1", Const, 0},
+		{"InstRuneAny", Const, 0},
+		{"InstRuneAnyNotNL", Const, 0},
+		{"IsWordChar", Func, 0},
+		{"Literal", Const, 0},
+		{"MatchNL", Const, 0},
+		{"NonGreedy", Const, 0},
+		{"OneLine", Const, 0},
+		{"Op", Type, 0},
+		{"OpAlternate", Const, 0},
+		{"OpAnyChar", Const, 0},
+		{"OpAnyCharNotNL", Const, 0},
+		{"OpBeginLine", Const, 0},
+		{"OpBeginText", Const, 0},
+		{"OpCapture", Const, 0},
+		{"OpCharClass", Const, 0},
+		{"OpConcat", Const, 0},
+		{"OpEmptyMatch", Const, 0},
+		{"OpEndLine", Const, 0},
+		{"OpEndText", Const, 0},
+		{"OpLiteral", Const, 0},
+		{"OpNoMatch", Const, 0},
+		{"OpNoWordBoundary", Const, 0},
+		{"OpPlus", Const, 0},
+		{"OpQuest", Const, 0},
+		{"OpRepeat", Const, 0},
+		{"OpStar", Const, 0},
+		{"OpWordBoundary", Const, 0},
+		{"POSIX", Const, 0},
+		{"Parse", Func, 0},
+		{"Perl", Const, 0},
+		{"PerlX", Const, 0},
+		{"Prog", Type, 0},
+		{"Prog.Inst", Field, 0},
+		{"Prog.NumCap", Field, 0},
+		{"Prog.Start", Field, 0},
+		{"Regexp", Type, 0},
+		{"Regexp.Cap", Field, 0},
+		{"Regexp.Flags", Field, 0},
+		{"Regexp.Max", Field, 0},
+		{"Regexp.Min", Field, 0},
+		{"Regexp.Name", Field, 0},
+		{"Regexp.Op", Field, 0},
+		{"Regexp.Rune", Field, 0},
+		{"Regexp.Rune0", Field, 0},
+		{"Regexp.Sub", Field, 0},
+		{"Regexp.Sub0", Field, 0},
+		{"Simple", Const, 0},
+		{"UnicodeGroups", Const, 0},
+		{"WasDollar", Const, 0},
+	},
+	"runtime": {
+		{"(*BlockProfileRecord).Stack", Method, 1},
+		{"(*Frames).Next", Method, 7},
+		{"(*Func).Entry", Method, 0},
+		{"(*Func).FileLine", Method, 0},
+		{"(*Func).Name", Method, 0},
+		{"(*MemProfileRecord).InUseBytes", Method, 0},
+		{"(*MemProfileRecord).InUseObjects", Method, 0},
+		{"(*MemProfileRecord).Stack", Method, 0},
+		{"(*PanicNilError).Error", Method, 21},
+		{"(*PanicNilError).RuntimeError", Method, 21},
+		{"(*Pinner).Pin", Method, 21},
+		{"(*Pinner).Unpin", Method, 21},
+		{"(*StackRecord).Stack", Method, 0},
+		{"(*TypeAssertionError).Error", Method, 0},
+		{"(*TypeAssertionError).RuntimeError", Method, 0},
+		{"(Cleanup).Stop", Method, 24},
+		{"AddCleanup", Func, 24},
+		{"BlockProfile", Func, 1},
+		{"BlockProfileRecord", Type, 1},
+		{"BlockProfileRecord.Count", Field, 1},
+		{"BlockProfileRecord.Cycles", Field, 1},
+		{"BlockProfileRecord.StackRecord", Field, 1},
+		{"Breakpoint", Func, 0},
+		{"CPUProfile", Func, 0},
+		{"Caller", Func, 0},
+		{"Callers", Func, 0},
+		{"CallersFrames", Func, 7},
+		{"Cleanup", Type, 24},
+		{"Compiler", Const, 0},
+		{"Error", Type, 0},
+		{"Frame", Type, 7},
+		{"Frame.Entry", Field, 7},
+		{"Frame.File", Field, 7},
+		{"Frame.Func", Field, 7},
+		{"Frame.Function", Field, 7},
+		{"Frame.Line", Field, 7},
+		{"Frame.PC", Field, 7},
+		{"Frames", Type, 7},
+		{"Func", Type, 0},
+		{"FuncForPC", Func, 0},
+		{"GC", Func, 0},
+		{"GOARCH", Const, 0},
+		{"GOMAXPROCS", Func, 0},
+		{"GOOS", Const, 0},
+		{"GOROOT", Func, 0},
+		{"Goexit", Func, 0},
+		{"GoroutineProfile", Func, 0},
+		{"Gosched", Func, 0},
+		{"KeepAlive", Func, 7},
+		{"LockOSThread", Func, 0},
+		{"MemProfile", Func, 0},
+		{"MemProfileRate", Var, 0},
+		{"MemProfileRecord", Type, 0},
+		{"MemProfileRecord.AllocBytes", Field, 0},
+		{"MemProfileRecord.AllocObjects", Field, 0},
+		{"MemProfileRecord.FreeBytes", Field, 0},
+		{"MemProfileRecord.FreeObjects", Field, 0},
+		{"MemProfileRecord.Stack0", Field, 0},
+		{"MemStats", Type, 0},
+		{"MemStats.Alloc", Field, 0},
+		{"MemStats.BuckHashSys", Field, 0},
+		{"MemStats.BySize", Field, 0},
+		{"MemStats.DebugGC", Field, 0},
+		{"MemStats.EnableGC", Field, 0},
+		{"MemStats.Frees", Field, 0},
+		{"MemStats.GCCPUFraction", Field, 5},
+		{"MemStats.GCSys", Field, 2},
+		{"MemStats.HeapAlloc", Field, 0},
+		{"MemStats.HeapIdle", Field, 0},
+		{"MemStats.HeapInuse", Field, 0},
+		{"MemStats.HeapObjects", Field, 0},
+		{"MemStats.HeapReleased", Field, 0},
+		{"MemStats.HeapSys", Field, 0},
+		{"MemStats.LastGC", Field, 0},
+		{"MemStats.Lookups", Field, 0},
+		{"MemStats.MCacheInuse", Field, 0},
+		{"MemStats.MCacheSys", Field, 0},
+		{"MemStats.MSpanInuse", Field, 0},
+		{"MemStats.MSpanSys", Field, 0},
+		{"MemStats.Mallocs", Field, 0},
+		{"MemStats.NextGC", Field, 0},
+		{"MemStats.NumForcedGC", Field, 8},
+		{"MemStats.NumGC", Field, 0},
+		{"MemStats.OtherSys", Field, 2},
+		{"MemStats.PauseEnd", Field, 4},
+		{"MemStats.PauseNs", Field, 0},
+		{"MemStats.PauseTotalNs", Field, 0},
+		{"MemStats.StackInuse", Field, 0},
+		{"MemStats.StackSys", Field, 0},
+		{"MemStats.Sys", Field, 0},
+		{"MemStats.TotalAlloc", Field, 0},
+		{"MutexProfile", Func, 8},
+		{"NumCPU", Func, 0},
+		{"NumCgoCall", Func, 0},
+		{"NumGoroutine", Func, 0},
+		{"PanicNilError", Type, 21},
+		{"Pinner", Type, 21},
+		{"ReadMemStats", Func, 0},
+		{"ReadTrace", Func, 5},
+		{"SetBlockProfileRate", Func, 1},
+		{"SetCPUProfileRate", Func, 0},
+		{"SetCgoTraceback", Func, 7},
+		{"SetFinalizer", Func, 0},
+		{"SetMutexProfileFraction", Func, 8},
+		{"Stack", Func, 0},
+		{"StackRecord", Type, 0},
+		{"StackRecord.Stack0", Field, 0},
+		{"StartTrace", Func, 5},
+		{"StopTrace", Func, 5},
+		{"ThreadCreateProfile", Func, 0},
+		{"TypeAssertionError", Type, 0},
+		{"UnlockOSThread", Func, 0},
+		{"Version", Func, 0},
+	},
+	"runtime/cgo": {
+		{"(Handle).Delete", Method, 17},
+		{"(Handle).Value", Method, 17},
+		{"Handle", Type, 17},
+		{"Incomplete", Type, 20},
+		{"NewHandle", Func, 17},
+	},
+	"runtime/coverage": {
+		{"ClearCounters", Func, 20},
+		{"WriteCounters", Func, 20},
+		{"WriteCountersDir", Func, 20},
+		{"WriteMeta", Func, 20},
+		{"WriteMetaDir", Func, 20},
+	},
+	"runtime/debug": {
+		{"(*BuildInfo).String", Method, 18},
+		{"BuildInfo", Type, 12},
+		{"BuildInfo.Deps", Field, 12},
+		{"BuildInfo.GoVersion", Field, 18},
+		{"BuildInfo.Main", Field, 12},
+		{"BuildInfo.Path", Field, 12},
+		{"BuildInfo.Settings", Field, 18},
+		{"BuildSetting", Type, 18},
+		{"BuildSetting.Key", Field, 18},
+		{"BuildSetting.Value", Field, 18},
+		{"CrashOptions", Type, 23},
+		{"FreeOSMemory", Func, 1},
+		{"GCStats", Type, 1},
+		{"GCStats.LastGC", Field, 1},
+		{"GCStats.NumGC", Field, 1},
+		{"GCStats.Pause", Field, 1},
+		{"GCStats.PauseEnd", Field, 4},
+		{"GCStats.PauseQuantiles", Field, 1},
+		{"GCStats.PauseTotal", Field, 1},
+		{"Module", Type, 12},
+		{"Module.Path", Field, 12},
+		{"Module.Replace", Field, 12},
+		{"Module.Sum", Field, 12},
+		{"Module.Version", Field, 12},
+		{"ParseBuildInfo", Func, 18},
+		{"PrintStack", Func, 0},
+		{"ReadBuildInfo", Func, 12},
+		{"ReadGCStats", Func, 1},
+		{"SetCrashOutput", Func, 23},
+		{"SetGCPercent", Func, 1},
+		{"SetMaxStack", Func, 2},
+		{"SetMaxThreads", Func, 2},
+		{"SetMemoryLimit", Func, 19},
+		{"SetPanicOnFault", Func, 3},
+		{"SetTraceback", Func, 6},
+		{"Stack", Func, 0},
+		{"WriteHeapDump", Func, 3},
+	},
+	"runtime/metrics": {
+		{"(Value).Float64", Method, 16},
+		{"(Value).Float64Histogram", Method, 16},
+		{"(Value).Kind", Method, 16},
+		{"(Value).Uint64", Method, 16},
+		{"All", Func, 16},
+		{"Description", Type, 16},
+		{"Description.Cumulative", Field, 16},
+		{"Description.Description", Field, 16},
+		{"Description.Kind", Field, 16},
+		{"Description.Name", Field, 16},
+		{"Float64Histogram", Type, 16},
+		{"Float64Histogram.Buckets", Field, 16},
+		{"Float64Histogram.Counts", Field, 16},
+		{"KindBad", Const, 16},
+		{"KindFloat64", Const, 16},
+		{"KindFloat64Histogram", Const, 16},
+		{"KindUint64", Const, 16},
+		{"Read", Func, 16},
+		{"Sample", Type, 16},
+		{"Sample.Name", Field, 16},
+		{"Sample.Value", Field, 16},
+		{"Value", Type, 16},
+		{"ValueKind", Type, 16},
+	},
+	"runtime/pprof": {
+		{"(*Profile).Add", Method, 0},
+		{"(*Profile).Count", Method, 0},
+		{"(*Profile).Name", Method, 0},
+		{"(*Profile).Remove", Method, 0},
+		{"(*Profile).WriteTo", Method, 0},
+		{"Do", Func, 9},
+		{"ForLabels", Func, 9},
+		{"Label", Func, 9},
+		{"LabelSet", Type, 9},
+		{"Labels", Func, 9},
+		{"Lookup", Func, 0},
+		{"NewProfile", Func, 0},
+		{"Profile", Type, 0},
+		{"Profiles", Func, 0},
+		{"SetGoroutineLabels", Func, 9},
+		{"StartCPUProfile", Func, 0},
+		{"StopCPUProfile", Func, 0},
+		{"WithLabels", Func, 9},
+		{"WriteHeapProfile", Func, 0},
+	},
+	"runtime/trace": {
+		{"(*Region).End", Method, 11},
+		{"(*Task).End", Method, 11},
+		{"IsEnabled", Func, 11},
+		{"Log", Func, 11},
+		{"Logf", Func, 11},
+		{"NewTask", Func, 11},
+		{"Region", Type, 11},
+		{"Start", Func, 5},
+		{"StartRegion", Func, 11},
+		{"Stop", Func, 5},
+		{"Task", Type, 11},
+		{"WithRegion", Func, 11},
+	},
+	"slices": {
+		{"All", Func, 23},
+		{"AppendSeq", Func, 23},
+		{"Backward", Func, 23},
+		{"BinarySearch", Func, 21},
+		{"BinarySearchFunc", Func, 21},
+		{"Chunk", Func, 23},
+		{"Clip", Func, 21},
+		{"Clone", Func, 21},
+		{"Collect", Func, 23},
+		{"Compact", Func, 21},
+		{"CompactFunc", Func, 21},
+		{"Compare", Func, 21},
+		{"CompareFunc", Func, 21},
+		{"Concat", Func, 22},
+		{"Contains", Func, 21},
+		{"ContainsFunc", Func, 21},
+		{"Delete", Func, 21},
+		{"DeleteFunc", Func, 21},
+		{"Equal", Func, 21},
+		{"EqualFunc", Func, 21},
+		{"Grow", Func, 21},
+		{"Index", Func, 21},
+		{"IndexFunc", Func, 21},
+		{"Insert", Func, 21},
+		{"IsSorted", Func, 21},
+		{"IsSortedFunc", Func, 21},
+		{"Max", Func, 21},
+		{"MaxFunc", Func, 21},
+		{"Min", Func, 21},
+		{"MinFunc", Func, 21},
+		{"Repeat", Func, 23},
+		{"Replace", Func, 21},
+		{"Reverse", Func, 21},
+		{"Sort", Func, 21},
+		{"SortFunc", Func, 21},
+		{"SortStableFunc", Func, 21},
+		{"Sorted", Func, 23},
+		{"SortedFunc", Func, 23},
+		{"SortedStableFunc", Func, 23},
+		{"Values", Func, 23},
+	},
+	"sort": {
+		{"(Float64Slice).Len", Method, 0},
+		{"(Float64Slice).Less", Method, 0},
+		{"(Float64Slice).Search", Method, 0},
+		{"(Float64Slice).Sort", Method, 0},
+		{"(Float64Slice).Swap", Method, 0},
+		{"(IntSlice).Len", Method, 0},
+		{"(IntSlice).Less", Method, 0},
+		{"(IntSlice).Search", Method, 0},
+		{"(IntSlice).Sort", Method, 0},
+		{"(IntSlice).Swap", Method, 0},
+		{"(StringSlice).Len", Method, 0},
+		{"(StringSlice).Less", Method, 0},
+		{"(StringSlice).Search", Method, 0},
+		{"(StringSlice).Sort", Method, 0},
+		{"(StringSlice).Swap", Method, 0},
+		{"Find", Func, 19},
+		{"Float64Slice", Type, 0},
+		{"Float64s", Func, 0},
+		{"Float64sAreSorted", Func, 0},
+		{"IntSlice", Type, 0},
+		{"Interface", Type, 0},
+		{"Ints", Func, 0},
+		{"IntsAreSorted", Func, 0},
+		{"IsSorted", Func, 0},
+		{"Reverse", Func, 1},
+		{"Search", Func, 0},
+		{"SearchFloat64s", Func, 0},
+		{"SearchInts", Func, 0},
+		{"SearchStrings", Func, 0},
+		{"Slice", Func, 8},
+		{"SliceIsSorted", Func, 8},
+		{"SliceStable", Func, 8},
+		{"Sort", Func, 0},
+		{"Stable", Func, 2},
+		{"StringSlice", Type, 0},
+		{"Strings", Func, 0},
+		{"StringsAreSorted", Func, 0},
+	},
+	"strconv": {
+		{"(*NumError).Error", Method, 0},
+		{"(*NumError).Unwrap", Method, 14},
+		{"AppendBool", Func, 0},
+		{"AppendFloat", Func, 0},
+		{"AppendInt", Func, 0},
+		{"AppendQuote", Func, 0},
+		{"AppendQuoteRune", Func, 0},
+		{"AppendQuoteRuneToASCII", Func, 0},
+		{"AppendQuoteRuneToGraphic", Func, 6},
+		{"AppendQuoteToASCII", Func, 0},
+		{"AppendQuoteToGraphic", Func, 6},
+		{"AppendUint", Func, 0},
+		{"Atoi", Func, 0},
+		{"CanBackquote", Func, 0},
+		{"ErrRange", Var, 0},
+		{"ErrSyntax", Var, 0},
+		{"FormatBool", Func, 0},
+		{"FormatComplex", Func, 15},
+		{"FormatFloat", Func, 0},
+		{"FormatInt", Func, 0},
+		{"FormatUint", Func, 0},
+		{"IntSize", Const, 0},
+		{"IsGraphic", Func, 6},
+		{"IsPrint", Func, 0},
+		{"Itoa", Func, 0},
+		{"NumError", Type, 0},
+		{"NumError.Err", Field, 0},
+		{"NumError.Func", Field, 0},
+		{"NumError.Num", Field, 0},
+		{"ParseBool", Func, 0},
+		{"ParseComplex", Func, 15},
+		{"ParseFloat", Func, 0},
+		{"ParseInt", Func, 0},
+		{"ParseUint", Func, 0},
+		{"Quote", Func, 0},
+		{"QuoteRune", Func, 0},
+		{"QuoteRuneToASCII", Func, 0},
+		{"QuoteRuneToGraphic", Func, 6},
+		{"QuoteToASCII", Func, 0},
+		{"QuoteToGraphic", Func, 6},
+		{"QuotedPrefix", Func, 17},
+		{"Unquote", Func, 0},
+		{"UnquoteChar", Func, 0},
+	},
+	"strings": {
+		{"(*Builder).Cap", Method, 12},
+		{"(*Builder).Grow", Method, 10},
+		{"(*Builder).Len", Method, 10},
+		{"(*Builder).Reset", Method, 10},
+		{"(*Builder).String", Method, 10},
+		{"(*Builder).Write", Method, 10},
+		{"(*Builder).WriteByte", Method, 10},
+		{"(*Builder).WriteRune", Method, 10},
+		{"(*Builder).WriteString", Method, 10},
+		{"(*Reader).Len", Method, 0},
+		{"(*Reader).Read", Method, 0},
+		{"(*Reader).ReadAt", Method, 0},
+		{"(*Reader).ReadByte", Method, 0},
+		{"(*Reader).ReadRune", Method, 0},
+		{"(*Reader).Reset", Method, 7},
+		{"(*Reader).Seek", Method, 0},
+		{"(*Reader).Size", Method, 5},
+		{"(*Reader).UnreadByte", Method, 0},
+		{"(*Reader).UnreadRune", Method, 0},
+		{"(*Reader).WriteTo", Method, 1},
+		{"(*Replacer).Replace", Method, 0},
+		{"(*Replacer).WriteString", Method, 0},
+		{"Builder", Type, 10},
+		{"Clone", Func, 18},
+		{"Compare", Func, 5},
+		{"Contains", Func, 0},
+		{"ContainsAny", Func, 0},
+		{"ContainsFunc", Func, 21},
+		{"ContainsRune", Func, 0},
+		{"Count", Func, 0},
+		{"Cut", Func, 18},
+		{"CutPrefix", Func, 20},
+		{"CutSuffix", Func, 20},
+		{"EqualFold", Func, 0},
+		{"Fields", Func, 0},
+		{"FieldsFunc", Func, 0},
+		{"FieldsFuncSeq", Func, 24},
+		{"FieldsSeq", Func, 24},
+		{"HasPrefix", Func, 0},
+		{"HasSuffix", Func, 0},
+		{"Index", Func, 0},
+		{"IndexAny", Func, 0},
+		{"IndexByte", Func, 2},
+		{"IndexFunc", Func, 0},
+		{"IndexRune", Func, 0},
+		{"Join", Func, 0},
+		{"LastIndex", Func, 0},
+		{"LastIndexAny", Func, 0},
+		{"LastIndexByte", Func, 5},
+		{"LastIndexFunc", Func, 0},
+		{"Lines", Func, 24},
+		{"Map", Func, 0},
+		{"NewReader", Func, 0},
+		{"NewReplacer", Func, 0},
+		{"Reader", Type, 0},
+		{"Repeat", Func, 0},
+		{"Replace", Func, 0},
+		{"ReplaceAll", Func, 12},
+		{"Replacer", Type, 0},
+		{"Split", Func, 0},
+		{"SplitAfter", Func, 0},
+		{"SplitAfterN", Func, 0},
+		{"SplitAfterSeq", Func, 24},
+		{"SplitN", Func, 0},
+		{"SplitSeq", Func, 24},
+		{"Title", Func, 0},
+		{"ToLower", Func, 0},
+		{"ToLowerSpecial", Func, 0},
+		{"ToTitle", Func, 0},
+		{"ToTitleSpecial", Func, 0},
+		{"ToUpper", Func, 0},
+		{"ToUpperSpecial", Func, 0},
+		{"ToValidUTF8", Func, 13},
+		{"Trim", Func, 0},
+		{"TrimFunc", Func, 0},
+		{"TrimLeft", Func, 0},
+		{"TrimLeftFunc", Func, 0},
+		{"TrimPrefix", Func, 1},
+		{"TrimRight", Func, 0},
+		{"TrimRightFunc", Func, 0},
+		{"TrimSpace", Func, 0},
+		{"TrimSuffix", Func, 1},
+	},
+	"structs": {
+		{"HostLayout", Type, 23},
+	},
+	"sync": {
+		{"(*Cond).Broadcast", Method, 0},
+		{"(*Cond).Signal", Method, 0},
+		{"(*Cond).Wait", Method, 0},
+		{"(*Map).Clear", Method, 23},
+		{"(*Map).CompareAndDelete", Method, 20},
+		{"(*Map).CompareAndSwap", Method, 20},
+		{"(*Map).Delete", Method, 9},
+		{"(*Map).Load", Method, 9},
+		{"(*Map).LoadAndDelete", Method, 15},
+		{"(*Map).LoadOrStore", Method, 9},
+		{"(*Map).Range", Method, 9},
+		{"(*Map).Store", Method, 9},
+		{"(*Map).Swap", Method, 20},
+		{"(*Mutex).Lock", Method, 0},
+		{"(*Mutex).TryLock", Method, 18},
+		{"(*Mutex).Unlock", Method, 0},
+		{"(*Once).Do", Method, 0},
+		{"(*Pool).Get", Method, 3},
+		{"(*Pool).Put", Method, 3},
+		{"(*RWMutex).Lock", Method, 0},
+		{"(*RWMutex).RLock", Method, 0},
+		{"(*RWMutex).RLocker", Method, 0},
+		{"(*RWMutex).RUnlock", Method, 0},
+		{"(*RWMutex).TryLock", Method, 18},
+		{"(*RWMutex).TryRLock", Method, 18},
+		{"(*RWMutex).Unlock", Method, 0},
+		{"(*WaitGroup).Add", Method, 0},
+		{"(*WaitGroup).Done", Method, 0},
+		{"(*WaitGroup).Wait", Method, 0},
+		{"Cond", Type, 0},
+		{"Cond.L", Field, 0},
+		{"Locker", Type, 0},
+		{"Map", Type, 9},
+		{"Mutex", Type, 0},
+		{"NewCond", Func, 0},
+		{"Once", Type, 0},
+		{"OnceFunc", Func, 21},
+		{"OnceValue", Func, 21},
+		{"OnceValues", Func, 21},
+		{"Pool", Type, 3},
+		{"Pool.New", Field, 3},
+		{"RWMutex", Type, 0},
+		{"WaitGroup", Type, 0},
+	},
+	"sync/atomic": {
+		{"(*Bool).CompareAndSwap", Method, 19},
+		{"(*Bool).Load", Method, 19},
+		{"(*Bool).Store", Method, 19},
+		{"(*Bool).Swap", Method, 19},
+		{"(*Int32).Add", Method, 19},
+		{"(*Int32).And", Method, 23},
+		{"(*Int32).CompareAndSwap", Method, 19},
+		{"(*Int32).Load", Method, 19},
+		{"(*Int32).Or", Method, 23},
+		{"(*Int32).Store", Method, 19},
+		{"(*Int32).Swap", Method, 19},
+		{"(*Int64).Add", Method, 19},
+		{"(*Int64).And", Method, 23},
+		{"(*Int64).CompareAndSwap", Method, 19},
+		{"(*Int64).Load", Method, 19},
+		{"(*Int64).Or", Method, 23},
+		{"(*Int64).Store", Method, 19},
+		{"(*Int64).Swap", Method, 19},
+		{"(*Pointer).CompareAndSwap", Method, 19},
+		{"(*Pointer).Load", Method, 19},
+		{"(*Pointer).Store", Method, 19},
+		{"(*Pointer).Swap", Method, 19},
+		{"(*Uint32).Add", Method, 19},
+		{"(*Uint32).And", Method, 23},
+		{"(*Uint32).CompareAndSwap", Method, 19},
+		{"(*Uint32).Load", Method, 19},
+		{"(*Uint32).Or", Method, 23},
+		{"(*Uint32).Store", Method, 19},
+		{"(*Uint32).Swap", Method, 19},
+		{"(*Uint64).Add", Method, 19},
+		{"(*Uint64).And", Method, 23},
+		{"(*Uint64).CompareAndSwap", Method, 19},
+		{"(*Uint64).Load", Method, 19},
+		{"(*Uint64).Or", Method, 23},
+		{"(*Uint64).Store", Method, 19},
+		{"(*Uint64).Swap", Method, 19},
+		{"(*Uintptr).Add", Method, 19},
+		{"(*Uintptr).And", Method, 23},
+		{"(*Uintptr).CompareAndSwap", Method, 19},
+		{"(*Uintptr).Load", Method, 19},
+		{"(*Uintptr).Or", Method, 23},
+		{"(*Uintptr).Store", Method, 19},
+		{"(*Uintptr).Swap", Method, 19},
+		{"(*Value).CompareAndSwap", Method, 17},
+		{"(*Value).Load", Method, 4},
+		{"(*Value).Store", Method, 4},
+		{"(*Value).Swap", Method, 17},
+		{"AddInt32", Func, 0},
+		{"AddInt64", Func, 0},
+		{"AddUint32", Func, 0},
+		{"AddUint64", Func, 0},
+		{"AddUintptr", Func, 0},
+		{"AndInt32", Func, 23},
+		{"AndInt64", Func, 23},
+		{"AndUint32", Func, 23},
+		{"AndUint64", Func, 23},
+		{"AndUintptr", Func, 23},
+		{"Bool", Type, 19},
+		{"CompareAndSwapInt32", Func, 0},
+		{"CompareAndSwapInt64", Func, 0},
+		{"CompareAndSwapPointer", Func, 0},
+		{"CompareAndSwapUint32", Func, 0},
+		{"CompareAndSwapUint64", Func, 0},
+		{"CompareAndSwapUintptr", Func, 0},
+		{"Int32", Type, 19},
+		{"Int64", Type, 19},
+		{"LoadInt32", Func, 0},
+		{"LoadInt64", Func, 0},
+		{"LoadPointer", Func, 0},
+		{"LoadUint32", Func, 0},
+		{"LoadUint64", Func, 0},
+		{"LoadUintptr", Func, 0},
+		{"OrInt32", Func, 23},
+		{"OrInt64", Func, 23},
+		{"OrUint32", Func, 23},
+		{"OrUint64", Func, 23},
+		{"OrUintptr", Func, 23},
+		{"Pointer", Type, 19},
+		{"StoreInt32", Func, 0},
+		{"StoreInt64", Func, 0},
+		{"StorePointer", Func, 0},
+		{"StoreUint32", Func, 0},
+		{"StoreUint64", Func, 0},
+		{"StoreUintptr", Func, 0},
+		{"SwapInt32", Func, 2},
+		{"SwapInt64", Func, 2},
+		{"SwapPointer", Func, 2},
+		{"SwapUint32", Func, 2},
+		{"SwapUint64", Func, 2},
+		{"SwapUintptr", Func, 2},
+		{"Uint32", Type, 19},
+		{"Uint64", Type, 19},
+		{"Uintptr", Type, 19},
+		{"Value", Type, 4},
+	},
+	"syscall": {
+		{"(*Cmsghdr).SetLen", Method, 0},
+		{"(*DLL).FindProc", Method, 0},
+		{"(*DLL).MustFindProc", Method, 0},
+		{"(*DLL).Release", Method, 0},
+		{"(*DLLError).Error", Method, 0},
+		{"(*DLLError).Unwrap", Method, 16},
+		{"(*Filetime).Nanoseconds", Method, 0},
+		{"(*Iovec).SetLen", Method, 0},
+		{"(*LazyDLL).Handle", Method, 0},
+		{"(*LazyDLL).Load", Method, 0},
+		{"(*LazyDLL).NewProc", Method, 0},
+		{"(*LazyProc).Addr", Method, 0},
+		{"(*LazyProc).Call", Method, 0},
+		{"(*LazyProc).Find", Method, 0},
+		{"(*Msghdr).SetControllen", Method, 0},
+		{"(*Proc).Addr", Method, 0},
+		{"(*Proc).Call", Method, 0},
+		{"(*PtraceRegs).PC", Method, 0},
+		{"(*PtraceRegs).SetPC", Method, 0},
+		{"(*RawSockaddrAny).Sockaddr", Method, 0},
+		{"(*SID).Copy", Method, 0},
+		{"(*SID).Len", Method, 0},
+		{"(*SID).LookupAccount", Method, 0},
+		{"(*SID).String", Method, 0},
+		{"(*Timespec).Nano", Method, 0},
+		{"(*Timespec).Unix", Method, 0},
+		{"(*Timeval).Nano", Method, 0},
+		{"(*Timeval).Nanoseconds", Method, 0},
+		{"(*Timeval).Unix", Method, 0},
+		{"(Errno).Error", Method, 0},
+		{"(Errno).Is", Method, 13},
+		{"(Errno).Temporary", Method, 0},
+		{"(Errno).Timeout", Method, 0},
+		{"(Signal).Signal", Method, 0},
+		{"(Signal).String", Method, 0},
+		{"(Token).Close", Method, 0},
+		{"(Token).GetTokenPrimaryGroup", Method, 0},
+		{"(Token).GetTokenUser", Method, 0},
+		{"(Token).GetUserProfileDirectory", Method, 0},
+		{"(WaitStatus).Continued", Method, 0},
+		{"(WaitStatus).CoreDump", Method, 0},
+		{"(WaitStatus).ExitStatus", Method, 0},
+		{"(WaitStatus).Exited", Method, 0},
+		{"(WaitStatus).Signal", Method, 0},
+		{"(WaitStatus).Signaled", Method, 0},
+		{"(WaitStatus).StopSignal", Method, 0},
+		{"(WaitStatus).Stopped", Method, 0},
+		{"(WaitStatus).TrapCause", Method, 0},
+		{"AF_ALG", Const, 0},
+		{"AF_APPLETALK", Const, 0},
+		{"AF_ARP", Const, 0},
+		{"AF_ASH", Const, 0},
+		{"AF_ATM", Const, 0},
+		{"AF_ATMPVC", Const, 0},
+		{"AF_ATMSVC", Const, 0},
+		{"AF_AX25", Const, 0},
+		{"AF_BLUETOOTH", Const, 0},
+		{"AF_BRIDGE", Const, 0},
+		{"AF_CAIF", Const, 0},
+		{"AF_CAN", Const, 0},
+		{"AF_CCITT", Const, 0},
+		{"AF_CHAOS", Const, 0},
+		{"AF_CNT", Const, 0},
+		{"AF_COIP", Const, 0},
+		{"AF_DATAKIT", Const, 0},
+		{"AF_DECnet", Const, 0},
+		{"AF_DLI", Const, 0},
+		{"AF_E164", Const, 0},
+		{"AF_ECMA", Const, 0},
+		{"AF_ECONET", Const, 0},
+		{"AF_ENCAP", Const, 1},
+		{"AF_FILE", Const, 0},
+		{"AF_HYLINK", Const, 0},
+		{"AF_IEEE80211", Const, 0},
+		{"AF_IEEE802154", Const, 0},
+		{"AF_IMPLINK", Const, 0},
+		{"AF_INET", Const, 0},
+		{"AF_INET6", Const, 0},
+		{"AF_INET6_SDP", Const, 3},
+		{"AF_INET_SDP", Const, 3},
+		{"AF_IPX", Const, 0},
+		{"AF_IRDA", Const, 0},
+		{"AF_ISDN", Const, 0},
+		{"AF_ISO", Const, 0},
+		{"AF_IUCV", Const, 0},
+		{"AF_KEY", Const, 0},
+		{"AF_LAT", Const, 0},
+		{"AF_LINK", Const, 0},
+		{"AF_LLC", Const, 0},
+		{"AF_LOCAL", Const, 0},
+		{"AF_MAX", Const, 0},
+		{"AF_MPLS", Const, 1},
+		{"AF_NATM", Const, 0},
+		{"AF_NDRV", Const, 0},
+		{"AF_NETBEUI", Const, 0},
+		{"AF_NETBIOS", Const, 0},
+		{"AF_NETGRAPH", Const, 0},
+		{"AF_NETLINK", Const, 0},
+		{"AF_NETROM", Const, 0},
+		{"AF_NS", Const, 0},
+		{"AF_OROUTE", Const, 1},
+		{"AF_OSI", Const, 0},
+		{"AF_PACKET", Const, 0},
+		{"AF_PHONET", Const, 0},
+		{"AF_PPP", Const, 0},
+		{"AF_PPPOX", Const, 0},
+		{"AF_PUP", Const, 0},
+		{"AF_RDS", Const, 0},
+		{"AF_RESERVED_36", Const, 0},
+		{"AF_ROSE", Const, 0},
+		{"AF_ROUTE", Const, 0},
+		{"AF_RXRPC", Const, 0},
+		{"AF_SCLUSTER", Const, 0},
+		{"AF_SECURITY", Const, 0},
+		{"AF_SIP", Const, 0},
+		{"AF_SLOW", Const, 0},
+		{"AF_SNA", Const, 0},
+		{"AF_SYSTEM", Const, 0},
+		{"AF_TIPC", Const, 0},
+		{"AF_UNIX", Const, 0},
+		{"AF_UNSPEC", Const, 0},
+		{"AF_UTUN", Const, 16},
+		{"AF_VENDOR00", Const, 0},
+		{"AF_VENDOR01", Const, 0},
+		{"AF_VENDOR02", Const, 0},
+		{"AF_VENDOR03", Const, 0},
+		{"AF_VENDOR04", Const, 0},
+		{"AF_VENDOR05", Const, 0},
+		{"AF_VENDOR06", Const, 0},
+		{"AF_VENDOR07", Const, 0},
+		{"AF_VENDOR08", Const, 0},
+		{"AF_VENDOR09", Const, 0},
+		{"AF_VENDOR10", Const, 0},
+		{"AF_VENDOR11", Const, 0},
+		{"AF_VENDOR12", Const, 0},
+		{"AF_VENDOR13", Const, 0},
+		{"AF_VENDOR14", Const, 0},
+		{"AF_VENDOR15", Const, 0},
+		{"AF_VENDOR16", Const, 0},
+		{"AF_VENDOR17", Const, 0},
+		{"AF_VENDOR18", Const, 0},
+		{"AF_VENDOR19", Const, 0},
+		{"AF_VENDOR20", Const, 0},
+		{"AF_VENDOR21", Const, 0},
+		{"AF_VENDOR22", Const, 0},
+		{"AF_VENDOR23", Const, 0},
+		{"AF_VENDOR24", Const, 0},
+		{"AF_VENDOR25", Const, 0},
+		{"AF_VENDOR26", Const, 0},
+		{"AF_VENDOR27", Const, 0},
+		{"AF_VENDOR28", Const, 0},
+		{"AF_VENDOR29", Const, 0},
+		{"AF_VENDOR30", Const, 0},
+		{"AF_VENDOR31", Const, 0},
+		{"AF_VENDOR32", Const, 0},
+		{"AF_VENDOR33", Const, 0},
+		{"AF_VENDOR34", Const, 0},
+		{"AF_VENDOR35", Const, 0},
+		{"AF_VENDOR36", Const, 0},
+		{"AF_VENDOR37", Const, 0},
+		{"AF_VENDOR38", Const, 0},
+		{"AF_VENDOR39", Const, 0},
+		{"AF_VENDOR40", Const, 0},
+		{"AF_VENDOR41", Const, 0},
+		{"AF_VENDOR42", Const, 0},
+		{"AF_VENDOR43", Const, 0},
+		{"AF_VENDOR44", Const, 0},
+		{"AF_VENDOR45", Const, 0},
+		{"AF_VENDOR46", Const, 0},
+		{"AF_VENDOR47", Const, 0},
+		{"AF_WANPIPE", Const, 0},
+		{"AF_X25", Const, 0},
+		{"AI_CANONNAME", Const, 1},
+		{"AI_NUMERICHOST", Const, 1},
+		{"AI_PASSIVE", Const, 1},
+		{"APPLICATION_ERROR", Const, 0},
+		{"ARPHRD_ADAPT", Const, 0},
+		{"ARPHRD_APPLETLK", Const, 0},
+		{"ARPHRD_ARCNET", Const, 0},
+		{"ARPHRD_ASH", Const, 0},
+		{"ARPHRD_ATM", Const, 0},
+		{"ARPHRD_AX25", Const, 0},
+		{"ARPHRD_BIF", Const, 0},
+		{"ARPHRD_CHAOS", Const, 0},
+		{"ARPHRD_CISCO", Const, 0},
+		{"ARPHRD_CSLIP", Const, 0},
+		{"ARPHRD_CSLIP6", Const, 0},
+		{"ARPHRD_DDCMP", Const, 0},
+		{"ARPHRD_DLCI", Const, 0},
+		{"ARPHRD_ECONET", Const, 0},
+		{"ARPHRD_EETHER", Const, 0},
+		{"ARPHRD_ETHER", Const, 0},
+		{"ARPHRD_EUI64", Const, 0},
+		{"ARPHRD_FCAL", Const, 0},
+		{"ARPHRD_FCFABRIC", Const, 0},
+		{"ARPHRD_FCPL", Const, 0},
+		{"ARPHRD_FCPP", Const, 0},
+		{"ARPHRD_FDDI", Const, 0},
+		{"ARPHRD_FRAD", Const, 0},
+		{"ARPHRD_FRELAY", Const, 1},
+		{"ARPHRD_HDLC", Const, 0},
+		{"ARPHRD_HIPPI", Const, 0},
+		{"ARPHRD_HWX25", Const, 0},
+		{"ARPHRD_IEEE1394", Const, 0},
+		{"ARPHRD_IEEE802", Const, 0},
+		{"ARPHRD_IEEE80211", Const, 0},
+		{"ARPHRD_IEEE80211_PRISM", Const, 0},
+		{"ARPHRD_IEEE80211_RADIOTAP", Const, 0},
+		{"ARPHRD_IEEE802154", Const, 0},
+		{"ARPHRD_IEEE802154_PHY", Const, 0},
+		{"ARPHRD_IEEE802_TR", Const, 0},
+		{"ARPHRD_INFINIBAND", Const, 0},
+		{"ARPHRD_IPDDP", Const, 0},
+		{"ARPHRD_IPGRE", Const, 0},
+		{"ARPHRD_IRDA", Const, 0},
+		{"ARPHRD_LAPB", Const, 0},
+		{"ARPHRD_LOCALTLK", Const, 0},
+		{"ARPHRD_LOOPBACK", Const, 0},
+		{"ARPHRD_METRICOM", Const, 0},
+		{"ARPHRD_NETROM", Const, 0},
+		{"ARPHRD_NONE", Const, 0},
+		{"ARPHRD_PIMREG", Const, 0},
+		{"ARPHRD_PPP", Const, 0},
+		{"ARPHRD_PRONET", Const, 0},
+		{"ARPHRD_RAWHDLC", Const, 0},
+		{"ARPHRD_ROSE", Const, 0},
+		{"ARPHRD_RSRVD", Const, 0},
+		{"ARPHRD_SIT", Const, 0},
+		{"ARPHRD_SKIP", Const, 0},
+		{"ARPHRD_SLIP", Const, 0},
+		{"ARPHRD_SLIP6", Const, 0},
+		{"ARPHRD_STRIP", Const, 1},
+		{"ARPHRD_TUNNEL", Const, 0},
+		{"ARPHRD_TUNNEL6", Const, 0},
+		{"ARPHRD_VOID", Const, 0},
+		{"ARPHRD_X25", Const, 0},
+		{"AUTHTYPE_CLIENT", Const, 0},
+		{"AUTHTYPE_SERVER", Const, 0},
+		{"Accept", Func, 0},
+		{"Accept4", Func, 1},
+		{"AcceptEx", Func, 0},
+		{"Access", Func, 0},
+		{"Acct", Func, 0},
+		{"AddrinfoW", Type, 1},
+		{"AddrinfoW.Addr", Field, 1},
+		{"AddrinfoW.Addrlen", Field, 1},
+		{"AddrinfoW.Canonname", Field, 1},
+		{"AddrinfoW.Family", Field, 1},
+		{"AddrinfoW.Flags", Field, 1},
+		{"AddrinfoW.Next", Field, 1},
+		{"AddrinfoW.Protocol", Field, 1},
+		{"AddrinfoW.Socktype", Field, 1},
+		{"Adjtime", Func, 0},
+		{"Adjtimex", Func, 0},
+		{"AllThreadsSyscall", Func, 16},
+		{"AllThreadsSyscall6", Func, 16},
+		{"AttachLsf", Func, 0},
+		{"B0", Const, 0},
+		{"B1000000", Const, 0},
+		{"B110", Const, 0},
+		{"B115200", Const, 0},
+		{"B1152000", Const, 0},
+		{"B1200", Const, 0},
+		{"B134", Const, 0},
+		{"B14400", Const, 1},
+		{"B150", Const, 0},
+		{"B1500000", Const, 0},
+		{"B1800", Const, 0},
+		{"B19200", Const, 0},
+		{"B200", Const, 0},
+		{"B2000000", Const, 0},
+		{"B230400", Const, 0},
+		{"B2400", Const, 0},
+		{"B2500000", Const, 0},
+		{"B28800", Const, 1},
+		{"B300", Const, 0},
+		{"B3000000", Const, 0},
+		{"B3500000", Const, 0},
+		{"B38400", Const, 0},
+		{"B4000000", Const, 0},
+		{"B460800", Const, 0},
+		{"B4800", Const, 0},
+		{"B50", Const, 0},
+		{"B500000", Const, 0},
+		{"B57600", Const, 0},
+		{"B576000", Const, 0},
+		{"B600", Const, 0},
+		{"B7200", Const, 1},
+		{"B75", Const, 0},
+		{"B76800", Const, 1},
+		{"B921600", Const, 0},
+		{"B9600", Const, 0},
+		{"BASE_PROTOCOL", Const, 2},
+		{"BIOCFEEDBACK", Const, 0},
+		{"BIOCFLUSH", Const, 0},
+		{"BIOCGBLEN", Const, 0},
+		{"BIOCGDIRECTION", Const, 0},
+		{"BIOCGDIRFILT", Const, 1},
+		{"BIOCGDLT", Const, 0},
+		{"BIOCGDLTLIST", Const, 0},
+		{"BIOCGETBUFMODE", Const, 0},
+		{"BIOCGETIF", Const, 0},
+		{"BIOCGETZMAX", Const, 0},
+		{"BIOCGFEEDBACK", Const, 1},
+		{"BIOCGFILDROP", Const, 1},
+		{"BIOCGHDRCMPLT", Const, 0},
+		{"BIOCGRSIG", Const, 0},
+		{"BIOCGRTIMEOUT", Const, 0},
+		{"BIOCGSEESENT", Const, 0},
+		{"BIOCGSTATS", Const, 0},
+		{"BIOCGSTATSOLD", Const, 1},
+		{"BIOCGTSTAMP", Const, 1},
+		{"BIOCIMMEDIATE", Const, 0},
+		{"BIOCLOCK", Const, 0},
+		{"BIOCPROMISC", Const, 0},
+		{"BIOCROTZBUF", Const, 0},
+		{"BIOCSBLEN", Const, 0},
+		{"BIOCSDIRECTION", Const, 0},
+		{"BIOCSDIRFILT", Const, 1},
+		{"BIOCSDLT", Const, 0},
+		{"BIOCSETBUFMODE", Const, 0},
+		{"BIOCSETF", Const, 0},
+		{"BIOCSETFNR", Const, 0},
+		{"BIOCSETIF", Const, 0},
+		{"BIOCSETWF", Const, 0},
+		{"BIOCSETZBUF", Const, 0},
+		{"BIOCSFEEDBACK", Const, 1},
+		{"BIOCSFILDROP", Const, 1},
+		{"BIOCSHDRCMPLT", Const, 0},
+		{"BIOCSRSIG", Const, 0},
+		{"BIOCSRTIMEOUT", Const, 0},
+		{"BIOCSSEESENT", Const, 0},
+		{"BIOCSTCPF", Const, 1},
+		{"BIOCSTSTAMP", Const, 1},
+		{"BIOCSUDPF", Const, 1},
+		{"BIOCVERSION", Const, 0},
+		{"BPF_A", Const, 0},
+		{"BPF_ABS", Const, 0},
+		{"BPF_ADD", Const, 0},
+		{"BPF_ALIGNMENT", Const, 0},
+		{"BPF_ALIGNMENT32", Const, 1},
+		{"BPF_ALU", Const, 0},
+		{"BPF_AND", Const, 0},
+		{"BPF_B", Const, 0},
+		{"BPF_BUFMODE_BUFFER", Const, 0},
+		{"BPF_BUFMODE_ZBUF", Const, 0},
+		{"BPF_DFLTBUFSIZE", Const, 1},
+		{"BPF_DIRECTION_IN", Const, 1},
+		{"BPF_DIRECTION_OUT", Const, 1},
+		{"BPF_DIV", Const, 0},
+		{"BPF_H", Const, 0},
+		{"BPF_IMM", Const, 0},
+		{"BPF_IND", Const, 0},
+		{"BPF_JA", Const, 0},
+		{"BPF_JEQ", Const, 0},
+		{"BPF_JGE", Const, 0},
+		{"BPF_JGT", Const, 0},
+		{"BPF_JMP", Const, 0},
+		{"BPF_JSET", Const, 0},
+		{"BPF_K", Const, 0},
+		{"BPF_LD", Const, 0},
+		{"BPF_LDX", Const, 0},
+		{"BPF_LEN", Const, 0},
+		{"BPF_LSH", Const, 0},
+		{"BPF_MAJOR_VERSION", Const, 0},
+		{"BPF_MAXBUFSIZE", Const, 0},
+		{"BPF_MAXINSNS", Const, 0},
+		{"BPF_MEM", Const, 0},
+		{"BPF_MEMWORDS", Const, 0},
+		{"BPF_MINBUFSIZE", Const, 0},
+		{"BPF_MINOR_VERSION", Const, 0},
+		{"BPF_MISC", Const, 0},
+		{"BPF_MSH", Const, 0},
+		{"BPF_MUL", Const, 0},
+		{"BPF_NEG", Const, 0},
+		{"BPF_OR", Const, 0},
+		{"BPF_RELEASE", Const, 0},
+		{"BPF_RET", Const, 0},
+		{"BPF_RSH", Const, 0},
+		{"BPF_ST", Const, 0},
+		{"BPF_STX", Const, 0},
+		{"BPF_SUB", Const, 0},
+		{"BPF_TAX", Const, 0},
+		{"BPF_TXA", Const, 0},
+		{"BPF_T_BINTIME", Const, 1},
+		{"BPF_T_BINTIME_FAST", Const, 1},
+		{"BPF_T_BINTIME_MONOTONIC", Const, 1},
+		{"BPF_T_BINTIME_MONOTONIC_FAST", Const, 1},
+		{"BPF_T_FAST", Const, 1},
+		{"BPF_T_FLAG_MASK", Const, 1},
+		{"BPF_T_FORMAT_MASK", Const, 1},
+		{"BPF_T_MICROTIME", Const, 1},
+		{"BPF_T_MICROTIME_FAST", Const, 1},
+		{"BPF_T_MICROTIME_MONOTONIC", Const, 1},
+		{"BPF_T_MICROTIME_MONOTONIC_FAST", Const, 1},
+		{"BPF_T_MONOTONIC", Const, 1},
+		{"BPF_T_MONOTONIC_FAST", Const, 1},
+		{"BPF_T_NANOTIME", Const, 1},
+		{"BPF_T_NANOTIME_FAST", Const, 1},
+		{"BPF_T_NANOTIME_MONOTONIC", Const, 1},
+		{"BPF_T_NANOTIME_MONOTONIC_FAST", Const, 1},
+		{"BPF_T_NONE", Const, 1},
+		{"BPF_T_NORMAL", Const, 1},
+		{"BPF_W", Const, 0},
+		{"BPF_X", Const, 0},
+		{"BRKINT", Const, 0},
+		{"Bind", Func, 0},
+		{"BindToDevice", Func, 0},
+		{"BpfBuflen", Func, 0},
+		{"BpfDatalink", Func, 0},
+		{"BpfHdr", Type, 0},
+		{"BpfHdr.Caplen", Field, 0},
+		{"BpfHdr.Datalen", Field, 0},
+		{"BpfHdr.Hdrlen", Field, 0},
+		{"BpfHdr.Pad_cgo_0", Field, 0},
+		{"BpfHdr.Tstamp", Field, 0},
+		{"BpfHeadercmpl", Func, 0},
+		{"BpfInsn", Type, 0},
+		{"BpfInsn.Code", Field, 0},
+		{"BpfInsn.Jf", Field, 0},
+		{"BpfInsn.Jt", Field, 0},
+		{"BpfInsn.K", Field, 0},
+		{"BpfInterface", Func, 0},
+		{"BpfJump", Func, 0},
+		{"BpfProgram", Type, 0},
+		{"BpfProgram.Insns", Field, 0},
+		{"BpfProgram.Len", Field, 0},
+		{"BpfProgram.Pad_cgo_0", Field, 0},
+		{"BpfStat", Type, 0},
+		{"BpfStat.Capt", Field, 2},
+		{"BpfStat.Drop", Field, 0},
+		{"BpfStat.Padding", Field, 2},
+		{"BpfStat.Recv", Field, 0},
+		{"BpfStats", Func, 0},
+		{"BpfStmt", Func, 0},
+		{"BpfTimeout", Func, 0},
+		{"BpfTimeval", Type, 2},
+		{"BpfTimeval.Sec", Field, 2},
+		{"BpfTimeval.Usec", Field, 2},
+		{"BpfVersion", Type, 0},
+		{"BpfVersion.Major", Field, 0},
+		{"BpfVersion.Minor", Field, 0},
+		{"BpfZbuf", Type, 0},
+		{"BpfZbuf.Bufa", Field, 0},
+		{"BpfZbuf.Bufb", Field, 0},
+		{"BpfZbuf.Buflen", Field, 0},
+		{"BpfZbufHeader", Type, 0},
+		{"BpfZbufHeader.Kernel_gen", Field, 0},
+		{"BpfZbufHeader.Kernel_len", Field, 0},
+		{"BpfZbufHeader.User_gen", Field, 0},
+		{"BpfZbufHeader.X_bzh_pad", Field, 0},
+		{"ByHandleFileInformation", Type, 0},
+		{"ByHandleFileInformation.CreationTime", Field, 0},
+		{"ByHandleFileInformation.FileAttributes", Field, 0},
+		{"ByHandleFileInformation.FileIndexHigh", Field, 0},
+		{"ByHandleFileInformation.FileIndexLow", Field, 0},
+		{"ByHandleFileInformation.FileSizeHigh", Field, 0},
+		{"ByHandleFileInformation.FileSizeLow", Field, 0},
+		{"ByHandleFileInformation.LastAccessTime", Field, 0},
+		{"ByHandleFileInformation.LastWriteTime", Field, 0},
+		{"ByHandleFileInformation.NumberOfLinks", Field, 0},
+		{"ByHandleFileInformation.VolumeSerialNumber", Field, 0},
+		{"BytePtrFromString", Func, 1},
+		{"ByteSliceFromString", Func, 1},
+		{"CCR0_FLUSH", Const, 1},
+		{"CERT_CHAIN_POLICY_AUTHENTICODE", Const, 0},
+		{"CERT_CHAIN_POLICY_AUTHENTICODE_TS", Const, 0},
+		{"CERT_CHAIN_POLICY_BASE", Const, 0},
+		{"CERT_CHAIN_POLICY_BASIC_CONSTRAINTS", Const, 0},
+		{"CERT_CHAIN_POLICY_EV", Const, 0},
+		{"CERT_CHAIN_POLICY_MICROSOFT_ROOT", Const, 0},
+		{"CERT_CHAIN_POLICY_NT_AUTH", Const, 0},
+		{"CERT_CHAIN_POLICY_SSL", Const, 0},
+		{"CERT_E_CN_NO_MATCH", Const, 0},
+		{"CERT_E_EXPIRED", Const, 0},
+		{"CERT_E_PURPOSE", Const, 0},
+		{"CERT_E_ROLE", Const, 0},
+		{"CERT_E_UNTRUSTEDROOT", Const, 0},
+		{"CERT_STORE_ADD_ALWAYS", Const, 0},
+		{"CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG", Const, 0},
+		{"CERT_STORE_PROV_MEMORY", Const, 0},
+		{"CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT", Const, 0},
+		{"CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT", Const, 0},
+		{"CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT", Const, 0},
+		{"CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT", Const, 0},
+		{"CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT", Const, 0},
+		{"CERT_TRUST_INVALID_BASIC_CONSTRAINTS", Const, 0},
+		{"CERT_TRUST_INVALID_EXTENSION", Const, 0},
+		{"CERT_TRUST_INVALID_NAME_CONSTRAINTS", Const, 0},
+		{"CERT_TRUST_INVALID_POLICY_CONSTRAINTS", Const, 0},
+		{"CERT_TRUST_IS_CYCLIC", Const, 0},
+		{"CERT_TRUST_IS_EXPLICIT_DISTRUST", Const, 0},
+		{"CERT_TRUST_IS_NOT_SIGNATURE_VALID", Const, 0},
+		{"CERT_TRUST_IS_NOT_TIME_VALID", Const, 0},
+		{"CERT_TRUST_IS_NOT_VALID_FOR_USAGE", Const, 0},
+		{"CERT_TRUST_IS_OFFLINE_REVOCATION", Const, 0},
+		{"CERT_TRUST_IS_REVOKED", Const, 0},
+		{"CERT_TRUST_IS_UNTRUSTED_ROOT", Const, 0},
+		{"CERT_TRUST_NO_ERROR", Const, 0},
+		{"CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY", Const, 0},
+		{"CERT_TRUST_REVOCATION_STATUS_UNKNOWN", Const, 0},
+		{"CFLUSH", Const, 1},
+		{"CLOCAL", Const, 0},
+		{"CLONE_CHILD_CLEARTID", Const, 2},
+		{"CLONE_CHILD_SETTID", Const, 2},
+		{"CLONE_CLEAR_SIGHAND", Const, 20},
+		{"CLONE_CSIGNAL", Const, 3},
+		{"CLONE_DETACHED", Const, 2},
+		{"CLONE_FILES", Const, 2},
+		{"CLONE_FS", Const, 2},
+		{"CLONE_INTO_CGROUP", Const, 20},
+		{"CLONE_IO", Const, 2},
+		{"CLONE_NEWCGROUP", Const, 20},
+		{"CLONE_NEWIPC", Const, 2},
+		{"CLONE_NEWNET", Const, 2},
+		{"CLONE_NEWNS", Const, 2},
+		{"CLONE_NEWPID", Const, 2},
+		{"CLONE_NEWTIME", Const, 20},
+		{"CLONE_NEWUSER", Const, 2},
+		{"CLONE_NEWUTS", Const, 2},
+		{"CLONE_PARENT", Const, 2},
+		{"CLONE_PARENT_SETTID", Const, 2},
+		{"CLONE_PID", Const, 3},
+		{"CLONE_PIDFD", Const, 20},
+		{"CLONE_PTRACE", Const, 2},
+		{"CLONE_SETTLS", Const, 2},
+		{"CLONE_SIGHAND", Const, 2},
+		{"CLONE_SYSVSEM", Const, 2},
+		{"CLONE_THREAD", Const, 2},
+		{"CLONE_UNTRACED", Const, 2},
+		{"CLONE_VFORK", Const, 2},
+		{"CLONE_VM", Const, 2},
+		{"CPUID_CFLUSH", Const, 1},
+		{"CREAD", Const, 0},
+		{"CREATE_ALWAYS", Const, 0},
+		{"CREATE_NEW", Const, 0},
+		{"CREATE_NEW_PROCESS_GROUP", Const, 1},
+		{"CREATE_UNICODE_ENVIRONMENT", Const, 0},
+		{"CRYPT_DEFAULT_CONTAINER_OPTIONAL", Const, 0},
+		{"CRYPT_DELETEKEYSET", Const, 0},
+		{"CRYPT_MACHINE_KEYSET", Const, 0},
+		{"CRYPT_NEWKEYSET", Const, 0},
+		{"CRYPT_SILENT", Const, 0},
+		{"CRYPT_VERIFYCONTEXT", Const, 0},
+		{"CS5", Const, 0},
+		{"CS6", Const, 0},
+		{"CS7", Const, 0},
+		{"CS8", Const, 0},
+		{"CSIZE", Const, 0},
+		{"CSTART", Const, 1},
+		{"CSTATUS", Const, 1},
+		{"CSTOP", Const, 1},
+		{"CSTOPB", Const, 0},
+		{"CSUSP", Const, 1},
+		{"CTL_MAXNAME", Const, 0},
+		{"CTL_NET", Const, 0},
+		{"CTL_QUERY", Const, 1},
+		{"CTRL_BREAK_EVENT", Const, 1},
+		{"CTRL_CLOSE_EVENT", Const, 14},
+		{"CTRL_C_EVENT", Const, 1},
+		{"CTRL_LOGOFF_EVENT", Const, 14},
+		{"CTRL_SHUTDOWN_EVENT", Const, 14},
+		{"CancelIo", Func, 0},
+		{"CancelIoEx", Func, 1},
+		{"CertAddCertificateContextToStore", Func, 0},
+		{"CertChainContext", Type, 0},
+		{"CertChainContext.ChainCount", Field, 0},
+		{"CertChainContext.Chains", Field, 0},
+		{"CertChainContext.HasRevocationFreshnessTime", Field, 0},
+		{"CertChainContext.LowerQualityChainCount", Field, 0},
+		{"CertChainContext.LowerQualityChains", Field, 0},
+		{"CertChainContext.RevocationFreshnessTime", Field, 0},
+		{"CertChainContext.Size", Field, 0},
+		{"CertChainContext.TrustStatus", Field, 0},
+		{"CertChainElement", Type, 0},
+		{"CertChainElement.ApplicationUsage", Field, 0},
+		{"CertChainElement.CertContext", Field, 0},
+		{"CertChainElement.ExtendedErrorInfo", Field, 0},
+		{"CertChainElement.IssuanceUsage", Field, 0},
+		{"CertChainElement.RevocationInfo", Field, 0},
+		{"CertChainElement.Size", Field, 0},
+		{"CertChainElement.TrustStatus", Field, 0},
+		{"CertChainPara", Type, 0},
+		{"CertChainPara.CacheResync", Field, 0},
+		{"CertChainPara.CheckRevocationFreshnessTime", Field, 0},
+		{"CertChainPara.RequestedUsage", Field, 0},
+		{"CertChainPara.RequstedIssuancePolicy", Field, 0},
+		{"CertChainPara.RevocationFreshnessTime", Field, 0},
+		{"CertChainPara.Size", Field, 0},
+		{"CertChainPara.URLRetrievalTimeout", Field, 0},
+		{"CertChainPolicyPara", Type, 0},
+		{"CertChainPolicyPara.ExtraPolicyPara", Field, 0},
+		{"CertChainPolicyPara.Flags", Field, 0},
+		{"CertChainPolicyPara.Size", Field, 0},
+		{"CertChainPolicyStatus", Type, 0},
+		{"CertChainPolicyStatus.ChainIndex", Field, 0},
+		{"CertChainPolicyStatus.ElementIndex", Field, 0},
+		{"CertChainPolicyStatus.Error", Field, 0},
+		{"CertChainPolicyStatus.ExtraPolicyStatus", Field, 0},
+		{"CertChainPolicyStatus.Size", Field, 0},
+		{"CertCloseStore", Func, 0},
+		{"CertContext", Type, 0},
+		{"CertContext.CertInfo", Field, 0},
+		{"CertContext.EncodedCert", Field, 0},
+		{"CertContext.EncodingType", Field, 0},
+		{"CertContext.Length", Field, 0},
+		{"CertContext.Store", Field, 0},
+		{"CertCreateCertificateContext", Func, 0},
+		{"CertEnhKeyUsage", Type, 0},
+		{"CertEnhKeyUsage.Length", Field, 0},
+		{"CertEnhKeyUsage.UsageIdentifiers", Field, 0},
+		{"CertEnumCertificatesInStore", Func, 0},
+		{"CertFreeCertificateChain", Func, 0},
+		{"CertFreeCertificateContext", Func, 0},
+		{"CertGetCertificateChain", Func, 0},
+		{"CertInfo", Type, 11},
+		{"CertOpenStore", Func, 0},
+		{"CertOpenSystemStore", Func, 0},
+		{"CertRevocationCrlInfo", Type, 11},
+		{"CertRevocationInfo", Type, 0},
+		{"CertRevocationInfo.CrlInfo", Field, 0},
+		{"CertRevocationInfo.FreshnessTime", Field, 0},
+		{"CertRevocationInfo.HasFreshnessTime", Field, 0},
+		{"CertRevocationInfo.OidSpecificInfo", Field, 0},
+		{"CertRevocationInfo.RevocationOid", Field, 0},
+		{"CertRevocationInfo.RevocationResult", Field, 0},
+		{"CertRevocationInfo.Size", Field, 0},
+		{"CertSimpleChain", Type, 0},
+		{"CertSimpleChain.Elements", Field, 0},
+		{"CertSimpleChain.HasRevocationFreshnessTime", Field, 0},
+		{"CertSimpleChain.NumElements", Field, 0},
+		{"CertSimpleChain.RevocationFreshnessTime", Field, 0},
+		{"CertSimpleChain.Size", Field, 0},
+		{"CertSimpleChain.TrustListInfo", Field, 0},
+		{"CertSimpleChain.TrustStatus", Field, 0},
+		{"CertTrustListInfo", Type, 11},
+		{"CertTrustStatus", Type, 0},
+		{"CertTrustStatus.ErrorStatus", Field, 0},
+		{"CertTrustStatus.InfoStatus", Field, 0},
+		{"CertUsageMatch", Type, 0},
+		{"CertUsageMatch.Type", Field, 0},
+		{"CertUsageMatch.Usage", Field, 0},
+		{"CertVerifyCertificateChainPolicy", Func, 0},
+		{"Chdir", Func, 0},
+		{"CheckBpfVersion", Func, 0},
+		{"Chflags", Func, 0},
+		{"Chmod", Func, 0},
+		{"Chown", Func, 0},
+		{"Chroot", Func, 0},
+		{"Clearenv", Func, 0},
+		{"Close", Func, 0},
+		{"CloseHandle", Func, 0},
+		{"CloseOnExec", Func, 0},
+		{"Closesocket", Func, 0},
+		{"CmsgLen", Func, 0},
+		{"CmsgSpace", Func, 0},
+		{"Cmsghdr", Type, 0},
+		{"Cmsghdr.Len", Field, 0},
+		{"Cmsghdr.Level", Field, 0},
+		{"Cmsghdr.Type", Field, 0},
+		{"Cmsghdr.X__cmsg_data", Field, 0},
+		{"CommandLineToArgv", Func, 0},
+		{"ComputerName", Func, 0},
+		{"Conn", Type, 9},
+		{"Connect", Func, 0},
+		{"ConnectEx", Func, 1},
+		{"ConvertSidToStringSid", Func, 0},
+		{"ConvertStringSidToSid", Func, 0},
+		{"CopySid", Func, 0},
+		{"Creat", Func, 0},
+		{"CreateDirectory", Func, 0},
+		{"CreateFile", Func, 0},
+		{"CreateFileMapping", Func, 0},
+		{"CreateHardLink", Func, 4},
+		{"CreateIoCompletionPort", Func, 0},
+		{"CreatePipe", Func, 0},
+		{"CreateProcess", Func, 0},
+		{"CreateProcessAsUser", Func, 10},
+		{"CreateSymbolicLink", Func, 4},
+		{"CreateToolhelp32Snapshot", Func, 4},
+		{"Credential", Type, 0},
+		{"Credential.Gid", Field, 0},
+		{"Credential.Groups", Field, 0},
+		{"Credential.NoSetGroups", Field, 9},
+		{"Credential.Uid", Field, 0},
+		{"CryptAcquireContext", Func, 0},
+		{"CryptGenRandom", Func, 0},
+		{"CryptReleaseContext", Func, 0},
+		{"DIOCBSFLUSH", Const, 1},
+		{"DIOCOSFPFLUSH", Const, 1},
+		{"DLL", Type, 0},
+		{"DLL.Handle", Field, 0},
+		{"DLL.Name", Field, 0},
+		{"DLLError", Type, 0},
+		{"DLLError.Err", Field, 0},
+		{"DLLError.Msg", Field, 0},
+		{"DLLError.ObjName", Field, 0},
+		{"DLT_A429", Const, 0},
+		{"DLT_A653_ICM", Const, 0},
+		{"DLT_AIRONET_HEADER", Const, 0},
+		{"DLT_AOS", Const, 1},
+		{"DLT_APPLE_IP_OVER_IEEE1394", Const, 0},
+		{"DLT_ARCNET", Const, 0},
+		{"DLT_ARCNET_LINUX", Const, 0},
+		{"DLT_ATM_CLIP", Const, 0},
+		{"DLT_ATM_RFC1483", Const, 0},
+		{"DLT_AURORA", Const, 0},
+		{"DLT_AX25", Const, 0},
+		{"DLT_AX25_KISS", Const, 0},
+		{"DLT_BACNET_MS_TP", Const, 0},
+		{"DLT_BLUETOOTH_HCI_H4", Const, 0},
+		{"DLT_BLUETOOTH_HCI_H4_WITH_PHDR", Const, 0},
+		{"DLT_CAN20B", Const, 0},
+		{"DLT_CAN_SOCKETCAN", Const, 1},
+		{"DLT_CHAOS", Const, 0},
+		{"DLT_CHDLC", Const, 0},
+		{"DLT_CISCO_IOS", Const, 0},
+		{"DLT_C_HDLC", Const, 0},
+		{"DLT_C_HDLC_WITH_DIR", Const, 0},
+		{"DLT_DBUS", Const, 1},
+		{"DLT_DECT", Const, 1},
+		{"DLT_DOCSIS", Const, 0},
+		{"DLT_DVB_CI", Const, 1},
+		{"DLT_ECONET", Const, 0},
+		{"DLT_EN10MB", Const, 0},
+		{"DLT_EN3MB", Const, 0},
+		{"DLT_ENC", Const, 0},
+		{"DLT_ERF", Const, 0},
+		{"DLT_ERF_ETH", Const, 0},
+		{"DLT_ERF_POS", Const, 0},
+		{"DLT_FC_2", Const, 1},
+		{"DLT_FC_2_WITH_FRAME_DELIMS", Const, 1},
+		{"DLT_FDDI", Const, 0},
+		{"DLT_FLEXRAY", Const, 0},
+		{"DLT_FRELAY", Const, 0},
+		{"DLT_FRELAY_WITH_DIR", Const, 0},
+		{"DLT_GCOM_SERIAL", Const, 0},
+		{"DLT_GCOM_T1E1", Const, 0},
+		{"DLT_GPF_F", Const, 0},
+		{"DLT_GPF_T", Const, 0},
+		{"DLT_GPRS_LLC", Const, 0},
+		{"DLT_GSMTAP_ABIS", Const, 1},
+		{"DLT_GSMTAP_UM", Const, 1},
+		{"DLT_HDLC", Const, 1},
+		{"DLT_HHDLC", Const, 0},
+		{"DLT_HIPPI", Const, 1},
+		{"DLT_IBM_SN", Const, 0},
+		{"DLT_IBM_SP", Const, 0},
+		{"DLT_IEEE802", Const, 0},
+		{"DLT_IEEE802_11", Const, 0},
+		{"DLT_IEEE802_11_RADIO", Const, 0},
+		{"DLT_IEEE802_11_RADIO_AVS", Const, 0},
+		{"DLT_IEEE802_15_4", Const, 0},
+		{"DLT_IEEE802_15_4_LINUX", Const, 0},
+		{"DLT_IEEE802_15_4_NOFCS", Const, 1},
+		{"DLT_IEEE802_15_4_NONASK_PHY", Const, 0},
+		{"DLT_IEEE802_16_MAC_CPS", Const, 0},
+		{"DLT_IEEE802_16_MAC_CPS_RADIO", Const, 0},
+		{"DLT_IPFILTER", Const, 0},
+		{"DLT_IPMB", Const, 0},
+		{"DLT_IPMB_LINUX", Const, 0},
+		{"DLT_IPNET", Const, 1},
+		{"DLT_IPOIB", Const, 1},
+		{"DLT_IPV4", Const, 1},
+		{"DLT_IPV6", Const, 1},
+		{"DLT_IP_OVER_FC", Const, 0},
+		{"DLT_JUNIPER_ATM1", Const, 0},
+		{"DLT_JUNIPER_ATM2", Const, 0},
+		{"DLT_JUNIPER_ATM_CEMIC", Const, 1},
+		{"DLT_JUNIPER_CHDLC", Const, 0},
+		{"DLT_JUNIPER_ES", Const, 0},
+		{"DLT_JUNIPER_ETHER", Const, 0},
+		{"DLT_JUNIPER_FIBRECHANNEL", Const, 1},
+		{"DLT_JUNIPER_FRELAY", Const, 0},
+		{"DLT_JUNIPER_GGSN", Const, 0},
+		{"DLT_JUNIPER_ISM", Const, 0},
+		{"DLT_JUNIPER_MFR", Const, 0},
+		{"DLT_JUNIPER_MLFR", Const, 0},
+		{"DLT_JUNIPER_MLPPP", Const, 0},
+		{"DLT_JUNIPER_MONITOR", Const, 0},
+		{"DLT_JUNIPER_PIC_PEER", Const, 0},
+		{"DLT_JUNIPER_PPP", Const, 0},
+		{"DLT_JUNIPER_PPPOE", Const, 0},
+		{"DLT_JUNIPER_PPPOE_ATM", Const, 0},
+		{"DLT_JUNIPER_SERVICES", Const, 0},
+		{"DLT_JUNIPER_SRX_E2E", Const, 1},
+		{"DLT_JUNIPER_ST", Const, 0},
+		{"DLT_JUNIPER_VP", Const, 0},
+		{"DLT_JUNIPER_VS", Const, 1},
+		{"DLT_LAPB_WITH_DIR", Const, 0},
+		{"DLT_LAPD", Const, 0},
+		{"DLT_LIN", Const, 0},
+		{"DLT_LINUX_EVDEV", Const, 1},
+		{"DLT_LINUX_IRDA", Const, 0},
+		{"DLT_LINUX_LAPD", Const, 0},
+		{"DLT_LINUX_PPP_WITHDIRECTION", Const, 0},
+		{"DLT_LINUX_SLL", Const, 0},
+		{"DLT_LOOP", Const, 0},
+		{"DLT_LTALK", Const, 0},
+		{"DLT_MATCHING_MAX", Const, 1},
+		{"DLT_MATCHING_MIN", Const, 1},
+		{"DLT_MFR", Const, 0},
+		{"DLT_MOST", Const, 0},
+		{"DLT_MPEG_2_TS", Const, 1},
+		{"DLT_MPLS", Const, 1},
+		{"DLT_MTP2", Const, 0},
+		{"DLT_MTP2_WITH_PHDR", Const, 0},
+		{"DLT_MTP3", Const, 0},
+		{"DLT_MUX27010", Const, 1},
+		{"DLT_NETANALYZER", Const, 1},
+		{"DLT_NETANALYZER_TRANSPARENT", Const, 1},
+		{"DLT_NFC_LLCP", Const, 1},
+		{"DLT_NFLOG", Const, 1},
+		{"DLT_NG40", Const, 1},
+		{"DLT_NULL", Const, 0},
+		{"DLT_PCI_EXP", Const, 0},
+		{"DLT_PFLOG", Const, 0},
+		{"DLT_PFSYNC", Const, 0},
+		{"DLT_PPI", Const, 0},
+		{"DLT_PPP", Const, 0},
+		{"DLT_PPP_BSDOS", Const, 0},
+		{"DLT_PPP_ETHER", Const, 0},
+		{"DLT_PPP_PPPD", Const, 0},
+		{"DLT_PPP_SERIAL", Const, 0},
+		{"DLT_PPP_WITH_DIR", Const, 0},
+		{"DLT_PPP_WITH_DIRECTION", Const, 0},
+		{"DLT_PRISM_HEADER", Const, 0},
+		{"DLT_PRONET", Const, 0},
+		{"DLT_RAIF1", Const, 0},
+		{"DLT_RAW", Const, 0},
+		{"DLT_RAWAF_MASK", Const, 1},
+		{"DLT_RIO", Const, 0},
+		{"DLT_SCCP", Const, 0},
+		{"DLT_SITA", Const, 0},
+		{"DLT_SLIP", Const, 0},
+		{"DLT_SLIP_BSDOS", Const, 0},
+		{"DLT_STANAG_5066_D_PDU", Const, 1},
+		{"DLT_SUNATM", Const, 0},
+		{"DLT_SYMANTEC_FIREWALL", Const, 0},
+		{"DLT_TZSP", Const, 0},
+		{"DLT_USB", Const, 0},
+		{"DLT_USB_LINUX", Const, 0},
+		{"DLT_USB_LINUX_MMAPPED", Const, 1},
+		{"DLT_USER0", Const, 0},
+		{"DLT_USER1", Const, 0},
+		{"DLT_USER10", Const, 0},
+		{"DLT_USER11", Const, 0},
+		{"DLT_USER12", Const, 0},
+		{"DLT_USER13", Const, 0},
+		{"DLT_USER14", Const, 0},
+		{"DLT_USER15", Const, 0},
+		{"DLT_USER2", Const, 0},
+		{"DLT_USER3", Const, 0},
+		{"DLT_USER4", Const, 0},
+		{"DLT_USER5", Const, 0},
+		{"DLT_USER6", Const, 0},
+		{"DLT_USER7", Const, 0},
+		{"DLT_USER8", Const, 0},
+		{"DLT_USER9", Const, 0},
+		{"DLT_WIHART", Const, 1},
+		{"DLT_X2E_SERIAL", Const, 0},
+		{"DLT_X2E_XORAYA", Const, 0},
+		{"DNSMXData", Type, 0},
+		{"DNSMXData.NameExchange", Field, 0},
+		{"DNSMXData.Pad", Field, 0},
+		{"DNSMXData.Preference", Field, 0},
+		{"DNSPTRData", Type, 0},
+		{"DNSPTRData.Host", Field, 0},
+		{"DNSRecord", Type, 0},
+		{"DNSRecord.Data", Field, 0},
+		{"DNSRecord.Dw", Field, 0},
+		{"DNSRecord.Length", Field, 0},
+		{"DNSRecord.Name", Field, 0},
+		{"DNSRecord.Next", Field, 0},
+		{"DNSRecord.Reserved", Field, 0},
+		{"DNSRecord.Ttl", Field, 0},
+		{"DNSRecord.Type", Field, 0},
+		{"DNSSRVData", Type, 0},
+		{"DNSSRVData.Pad", Field, 0},
+		{"DNSSRVData.Port", Field, 0},
+		{"DNSSRVData.Priority", Field, 0},
+		{"DNSSRVData.Target", Field, 0},
+		{"DNSSRVData.Weight", Field, 0},
+		{"DNSTXTData", Type, 0},
+		{"DNSTXTData.StringArray", Field, 0},
+		{"DNSTXTData.StringCount", Field, 0},
+		{"DNS_INFO_NO_RECORDS", Const, 4},
+		{"DNS_TYPE_A", Const, 0},
+		{"DNS_TYPE_A6", Const, 0},
+		{"DNS_TYPE_AAAA", Const, 0},
+		{"DNS_TYPE_ADDRS", Const, 0},
+		{"DNS_TYPE_AFSDB", Const, 0},
+		{"DNS_TYPE_ALL", Const, 0},
+		{"DNS_TYPE_ANY", Const, 0},
+		{"DNS_TYPE_ATMA", Const, 0},
+		{"DNS_TYPE_AXFR", Const, 0},
+		{"DNS_TYPE_CERT", Const, 0},
+		{"DNS_TYPE_CNAME", Const, 0},
+		{"DNS_TYPE_DHCID", Const, 0},
+		{"DNS_TYPE_DNAME", Const, 0},
+		{"DNS_TYPE_DNSKEY", Const, 0},
+		{"DNS_TYPE_DS", Const, 0},
+		{"DNS_TYPE_EID", Const, 0},
+		{"DNS_TYPE_GID", Const, 0},
+		{"DNS_TYPE_GPOS", Const, 0},
+		{"DNS_TYPE_HINFO", Const, 0},
+		{"DNS_TYPE_ISDN", Const, 0},
+		{"DNS_TYPE_IXFR", Const, 0},
+		{"DNS_TYPE_KEY", Const, 0},
+		{"DNS_TYPE_KX", Const, 0},
+		{"DNS_TYPE_LOC", Const, 0},
+		{"DNS_TYPE_MAILA", Const, 0},
+		{"DNS_TYPE_MAILB", Const, 0},
+		{"DNS_TYPE_MB", Const, 0},
+		{"DNS_TYPE_MD", Const, 0},
+		{"DNS_TYPE_MF", Const, 0},
+		{"DNS_TYPE_MG", Const, 0},
+		{"DNS_TYPE_MINFO", Const, 0},
+		{"DNS_TYPE_MR", Const, 0},
+		{"DNS_TYPE_MX", Const, 0},
+		{"DNS_TYPE_NAPTR", Const, 0},
+		{"DNS_TYPE_NBSTAT", Const, 0},
+		{"DNS_TYPE_NIMLOC", Const, 0},
+		{"DNS_TYPE_NS", Const, 0},
+		{"DNS_TYPE_NSAP", Const, 0},
+		{"DNS_TYPE_NSAPPTR", Const, 0},
+		{"DNS_TYPE_NSEC", Const, 0},
+		{"DNS_TYPE_NULL", Const, 0},
+		{"DNS_TYPE_NXT", Const, 0},
+		{"DNS_TYPE_OPT", Const, 0},
+		{"DNS_TYPE_PTR", Const, 0},
+		{"DNS_TYPE_PX", Const, 0},
+		{"DNS_TYPE_RP", Const, 0},
+		{"DNS_TYPE_RRSIG", Const, 0},
+		{"DNS_TYPE_RT", Const, 0},
+		{"DNS_TYPE_SIG", Const, 0},
+		{"DNS_TYPE_SINK", Const, 0},
+		{"DNS_TYPE_SOA", Const, 0},
+		{"DNS_TYPE_SRV", Const, 0},
+		{"DNS_TYPE_TEXT", Const, 0},
+		{"DNS_TYPE_TKEY", Const, 0},
+		{"DNS_TYPE_TSIG", Const, 0},
+		{"DNS_TYPE_UID", Const, 0},
+		{"DNS_TYPE_UINFO", Const, 0},
+		{"DNS_TYPE_UNSPEC", Const, 0},
+		{"DNS_TYPE_WINS", Const, 0},
+		{"DNS_TYPE_WINSR", Const, 0},
+		{"DNS_TYPE_WKS", Const, 0},
+		{"DNS_TYPE_X25", Const, 0},
+		{"DT_BLK", Const, 0},
+		{"DT_CHR", Const, 0},
+		{"DT_DIR", Const, 0},
+		{"DT_FIFO", Const, 0},
+		{"DT_LNK", Const, 0},
+		{"DT_REG", Const, 0},
+		{"DT_SOCK", Const, 0},
+		{"DT_UNKNOWN", Const, 0},
+		{"DT_WHT", Const, 0},
+		{"DUPLICATE_CLOSE_SOURCE", Const, 0},
+		{"DUPLICATE_SAME_ACCESS", Const, 0},
+		{"DeleteFile", Func, 0},
+		{"DetachLsf", Func, 0},
+		{"DeviceIoControl", Func, 4},
+		{"Dirent", Type, 0},
+		{"Dirent.Fileno", Field, 0},
+		{"Dirent.Ino", Field, 0},
+		{"Dirent.Name", Field, 0},
+		{"Dirent.Namlen", Field, 0},
+		{"Dirent.Off", Field, 0},
+		{"Dirent.Pad0", Field, 12},
+		{"Dirent.Pad1", Field, 12},
+		{"Dirent.Pad_cgo_0", Field, 0},
+		{"Dirent.Reclen", Field, 0},
+		{"Dirent.Seekoff", Field, 0},
+		{"Dirent.Type", Field, 0},
+		{"Dirent.X__d_padding", Field, 3},
+		{"DnsNameCompare", Func, 4},
+		{"DnsQuery", Func, 0},
+		{"DnsRecordListFree", Func, 0},
+		{"DnsSectionAdditional", Const, 4},
+		{"DnsSectionAnswer", Const, 4},
+		{"DnsSectionAuthority", Const, 4},
+		{"DnsSectionQuestion", Const, 4},
+		{"Dup", Func, 0},
+		{"Dup2", Func, 0},
+		{"Dup3", Func, 2},
+		{"DuplicateHandle", Func, 0},
+		{"E2BIG", Const, 0},
+		{"EACCES", Const, 0},
+		{"EADDRINUSE", Const, 0},
+		{"EADDRNOTAVAIL", Const, 0},
+		{"EADV", Const, 0},
+		{"EAFNOSUPPORT", Const, 0},
+		{"EAGAIN", Const, 0},
+		{"EALREADY", Const, 0},
+		{"EAUTH", Const, 0},
+		{"EBADARCH", Const, 0},
+		{"EBADE", Const, 0},
+		{"EBADEXEC", Const, 0},
+		{"EBADF", Const, 0},
+		{"EBADFD", Const, 0},
+		{"EBADMACHO", Const, 0},
+		{"EBADMSG", Const, 0},
+		{"EBADR", Const, 0},
+		{"EBADRPC", Const, 0},
+		{"EBADRQC", Const, 0},
+		{"EBADSLT", Const, 0},
+		{"EBFONT", Const, 0},
+		{"EBUSY", Const, 0},
+		{"ECANCELED", Const, 0},
+		{"ECAPMODE", Const, 1},
+		{"ECHILD", Const, 0},
+		{"ECHO", Const, 0},
+		{"ECHOCTL", Const, 0},
+		{"ECHOE", Const, 0},
+		{"ECHOK", Const, 0},
+		{"ECHOKE", Const, 0},
+		{"ECHONL", Const, 0},
+		{"ECHOPRT", Const, 0},
+		{"ECHRNG", Const, 0},
+		{"ECOMM", Const, 0},
+		{"ECONNABORTED", Const, 0},
+		{"ECONNREFUSED", Const, 0},
+		{"ECONNRESET", Const, 0},
+		{"EDEADLK", Const, 0},
+		{"EDEADLOCK", Const, 0},
+		{"EDESTADDRREQ", Const, 0},
+		{"EDEVERR", Const, 0},
+		{"EDOM", Const, 0},
+		{"EDOOFUS", Const, 0},
+		{"EDOTDOT", Const, 0},
+		{"EDQUOT", Const, 0},
+		{"EEXIST", Const, 0},
+		{"EFAULT", Const, 0},
+		{"EFBIG", Const, 0},
+		{"EFER_LMA", Const, 1},
+		{"EFER_LME", Const, 1},
+		{"EFER_NXE", Const, 1},
+		{"EFER_SCE", Const, 1},
+		{"EFTYPE", Const, 0},
+		{"EHOSTDOWN", Const, 0},
+		{"EHOSTUNREACH", Const, 0},
+		{"EHWPOISON", Const, 0},
+		{"EIDRM", Const, 0},
+		{"EILSEQ", Const, 0},
+		{"EINPROGRESS", Const, 0},
+		{"EINTR", Const, 0},
+		{"EINVAL", Const, 0},
+		{"EIO", Const, 0},
+		{"EIPSEC", Const, 1},
+		{"EISCONN", Const, 0},
+		{"EISDIR", Const, 0},
+		{"EISNAM", Const, 0},
+		{"EKEYEXPIRED", Const, 0},
+		{"EKEYREJECTED", Const, 0},
+		{"EKEYREVOKED", Const, 0},
+		{"EL2HLT", Const, 0},
+		{"EL2NSYNC", Const, 0},
+		{"EL3HLT", Const, 0},
+		{"EL3RST", Const, 0},
+		{"ELAST", Const, 0},
+		{"ELF_NGREG", Const, 0},
+		{"ELF_PRARGSZ", Const, 0},
+		{"ELIBACC", Const, 0},
+		{"ELIBBAD", Const, 0},
+		{"ELIBEXEC", Const, 0},
+		{"ELIBMAX", Const, 0},
+		{"ELIBSCN", Const, 0},
+		{"ELNRNG", Const, 0},
+		{"ELOOP", Const, 0},
+		{"EMEDIUMTYPE", Const, 0},
+		{"EMFILE", Const, 0},
+		{"EMLINK", Const, 0},
+		{"EMSGSIZE", Const, 0},
+		{"EMT_TAGOVF", Const, 1},
+		{"EMULTIHOP", Const, 0},
+		{"EMUL_ENABLED", Const, 1},
+		{"EMUL_LINUX", Const, 1},
+		{"EMUL_LINUX32", Const, 1},
+		{"EMUL_MAXID", Const, 1},
+		{"EMUL_NATIVE", Const, 1},
+		{"ENAMETOOLONG", Const, 0},
+		{"ENAVAIL", Const, 0},
+		{"ENDRUNDISC", Const, 1},
+		{"ENEEDAUTH", Const, 0},
+		{"ENETDOWN", Const, 0},
+		{"ENETRESET", Const, 0},
+		{"ENETUNREACH", Const, 0},
+		{"ENFILE", Const, 0},
+		{"ENOANO", Const, 0},
+		{"ENOATTR", Const, 0},
+		{"ENOBUFS", Const, 0},
+		{"ENOCSI", Const, 0},
+		{"ENODATA", Const, 0},
+		{"ENODEV", Const, 0},
+		{"ENOENT", Const, 0},
+		{"ENOEXEC", Const, 0},
+		{"ENOKEY", Const, 0},
+		{"ENOLCK", Const, 0},
+		{"ENOLINK", Const, 0},
+		{"ENOMEDIUM", Const, 0},
+		{"ENOMEM", Const, 0},
+		{"ENOMSG", Const, 0},
+		{"ENONET", Const, 0},
+		{"ENOPKG", Const, 0},
+		{"ENOPOLICY", Const, 0},
+		{"ENOPROTOOPT", Const, 0},
+		{"ENOSPC", Const, 0},
+		{"ENOSR", Const, 0},
+		{"ENOSTR", Const, 0},
+		{"ENOSYS", Const, 0},
+		{"ENOTBLK", Const, 0},
+		{"ENOTCAPABLE", Const, 0},
+		{"ENOTCONN", Const, 0},
+		{"ENOTDIR", Const, 0},
+		{"ENOTEMPTY", Const, 0},
+		{"ENOTNAM", Const, 0},
+		{"ENOTRECOVERABLE", Const, 0},
+		{"ENOTSOCK", Const, 0},
+		{"ENOTSUP", Const, 0},
+		{"ENOTTY", Const, 0},
+		{"ENOTUNIQ", Const, 0},
+		{"ENXIO", Const, 0},
+		{"EN_SW_CTL_INF", Const, 1},
+		{"EN_SW_CTL_PREC", Const, 1},
+		{"EN_SW_CTL_ROUND", Const, 1},
+		{"EN_SW_DATACHAIN", Const, 1},
+		{"EN_SW_DENORM", Const, 1},
+		{"EN_SW_INVOP", Const, 1},
+		{"EN_SW_OVERFLOW", Const, 1},
+		{"EN_SW_PRECLOSS", Const, 1},
+		{"EN_SW_UNDERFLOW", Const, 1},
+		{"EN_SW_ZERODIV", Const, 1},
+		{"EOPNOTSUPP", Const, 0},
+		{"EOVERFLOW", Const, 0},
+		{"EOWNERDEAD", Const, 0},
+		{"EPERM", Const, 0},
+		{"EPFNOSUPPORT", Const, 0},
+		{"EPIPE", Const, 0},
+		{"EPOLLERR", Const, 0},
+		{"EPOLLET", Const, 0},
+		{"EPOLLHUP", Const, 0},
+		{"EPOLLIN", Const, 0},
+		{"EPOLLMSG", Const, 0},
+		{"EPOLLONESHOT", Const, 0},
+		{"EPOLLOUT", Const, 0},
+		{"EPOLLPRI", Const, 0},
+		{"EPOLLRDBAND", Const, 0},
+		{"EPOLLRDHUP", Const, 0},
+		{"EPOLLRDNORM", Const, 0},
+		{"EPOLLWRBAND", Const, 0},
+		{"EPOLLWRNORM", Const, 0},
+		{"EPOLL_CLOEXEC", Const, 0},
+		{"EPOLL_CTL_ADD", Const, 0},
+		{"EPOLL_CTL_DEL", Const, 0},
+		{"EPOLL_CTL_MOD", Const, 0},
+		{"EPOLL_NONBLOCK", Const, 0},
+		{"EPROCLIM", Const, 0},
+		{"EPROCUNAVAIL", Const, 0},
+		{"EPROGMISMATCH", Const, 0},
+		{"EPROGUNAVAIL", Const, 0},
+		{"EPROTO", Const, 0},
+		{"EPROTONOSUPPORT", Const, 0},
+		{"EPROTOTYPE", Const, 0},
+		{"EPWROFF", Const, 0},
+		{"EQFULL", Const, 16},
+		{"ERANGE", Const, 0},
+		{"EREMCHG", Const, 0},
+		{"EREMOTE", Const, 0},
+		{"EREMOTEIO", Const, 0},
+		{"ERESTART", Const, 0},
+		{"ERFKILL", Const, 0},
+		{"EROFS", Const, 0},
+		{"ERPCMISMATCH", Const, 0},
+		{"ERROR_ACCESS_DENIED", Const, 0},
+		{"ERROR_ALREADY_EXISTS", Const, 0},
+		{"ERROR_BROKEN_PIPE", Const, 0},
+		{"ERROR_BUFFER_OVERFLOW", Const, 0},
+		{"ERROR_DIR_NOT_EMPTY", Const, 8},
+		{"ERROR_ENVVAR_NOT_FOUND", Const, 0},
+		{"ERROR_FILE_EXISTS", Const, 0},
+		{"ERROR_FILE_NOT_FOUND", Const, 0},
+		{"ERROR_HANDLE_EOF", Const, 2},
+		{"ERROR_INSUFFICIENT_BUFFER", Const, 0},
+		{"ERROR_IO_PENDING", Const, 0},
+		{"ERROR_MOD_NOT_FOUND", Const, 0},
+		{"ERROR_MORE_DATA", Const, 3},
+		{"ERROR_NETNAME_DELETED", Const, 3},
+		{"ERROR_NOT_FOUND", Const, 1},
+		{"ERROR_NO_MORE_FILES", Const, 0},
+		{"ERROR_OPERATION_ABORTED", Const, 0},
+		{"ERROR_PATH_NOT_FOUND", Const, 0},
+		{"ERROR_PRIVILEGE_NOT_HELD", Const, 4},
+		{"ERROR_PROC_NOT_FOUND", Const, 0},
+		{"ESHLIBVERS", Const, 0},
+		{"ESHUTDOWN", Const, 0},
+		{"ESOCKTNOSUPPORT", Const, 0},
+		{"ESPIPE", Const, 0},
+		{"ESRCH", Const, 0},
+		{"ESRMNT", Const, 0},
+		{"ESTALE", Const, 0},
+		{"ESTRPIPE", Const, 0},
+		{"ETHERCAP_JUMBO_MTU", Const, 1},
+		{"ETHERCAP_VLAN_HWTAGGING", Const, 1},
+		{"ETHERCAP_VLAN_MTU", Const, 1},
+		{"ETHERMIN", Const, 1},
+		{"ETHERMTU", Const, 1},
+		{"ETHERMTU_JUMBO", Const, 1},
+		{"ETHERTYPE_8023", Const, 1},
+		{"ETHERTYPE_AARP", Const, 1},
+		{"ETHERTYPE_ACCTON", Const, 1},
+		{"ETHERTYPE_AEONIC", Const, 1},
+		{"ETHERTYPE_ALPHA", Const, 1},
+		{"ETHERTYPE_AMBER", Const, 1},
+		{"ETHERTYPE_AMOEBA", Const, 1},
+		{"ETHERTYPE_AOE", Const, 1},
+		{"ETHERTYPE_APOLLO", Const, 1},
+		{"ETHERTYPE_APOLLODOMAIN", Const, 1},
+		{"ETHERTYPE_APPLETALK", Const, 1},
+		{"ETHERTYPE_APPLITEK", Const, 1},
+		{"ETHERTYPE_ARGONAUT", Const, 1},
+		{"ETHERTYPE_ARP", Const, 1},
+		{"ETHERTYPE_AT", Const, 1},
+		{"ETHERTYPE_ATALK", Const, 1},
+		{"ETHERTYPE_ATOMIC", Const, 1},
+		{"ETHERTYPE_ATT", Const, 1},
+		{"ETHERTYPE_ATTSTANFORD", Const, 1},
+		{"ETHERTYPE_AUTOPHON", Const, 1},
+		{"ETHERTYPE_AXIS", Const, 1},
+		{"ETHERTYPE_BCLOOP", Const, 1},
+		{"ETHERTYPE_BOFL", Const, 1},
+		{"ETHERTYPE_CABLETRON", Const, 1},
+		{"ETHERTYPE_CHAOS", Const, 1},
+		{"ETHERTYPE_COMDESIGN", Const, 1},
+		{"ETHERTYPE_COMPUGRAPHIC", Const, 1},
+		{"ETHERTYPE_COUNTERPOINT", Const, 1},
+		{"ETHERTYPE_CRONUS", Const, 1},
+		{"ETHERTYPE_CRONUSVLN", Const, 1},
+		{"ETHERTYPE_DCA", Const, 1},
+		{"ETHERTYPE_DDE", Const, 1},
+		{"ETHERTYPE_DEBNI", Const, 1},
+		{"ETHERTYPE_DECAM", Const, 1},
+		{"ETHERTYPE_DECCUST", Const, 1},
+		{"ETHERTYPE_DECDIAG", Const, 1},
+		{"ETHERTYPE_DECDNS", Const, 1},
+		{"ETHERTYPE_DECDTS", Const, 1},
+		{"ETHERTYPE_DECEXPER", Const, 1},
+		{"ETHERTYPE_DECLAST", Const, 1},
+		{"ETHERTYPE_DECLTM", Const, 1},
+		{"ETHERTYPE_DECMUMPS", Const, 1},
+		{"ETHERTYPE_DECNETBIOS", Const, 1},
+		{"ETHERTYPE_DELTACON", Const, 1},
+		{"ETHERTYPE_DIDDLE", Const, 1},
+		{"ETHERTYPE_DLOG1", Const, 1},
+		{"ETHERTYPE_DLOG2", Const, 1},
+		{"ETHERTYPE_DN", Const, 1},
+		{"ETHERTYPE_DOGFIGHT", Const, 1},
+		{"ETHERTYPE_DSMD", Const, 1},
+		{"ETHERTYPE_ECMA", Const, 1},
+		{"ETHERTYPE_ENCRYPT", Const, 1},
+		{"ETHERTYPE_ES", Const, 1},
+		{"ETHERTYPE_EXCELAN", Const, 1},
+		{"ETHERTYPE_EXPERDATA", Const, 1},
+		{"ETHERTYPE_FLIP", Const, 1},
+		{"ETHERTYPE_FLOWCONTROL", Const, 1},
+		{"ETHERTYPE_FRARP", Const, 1},
+		{"ETHERTYPE_GENDYN", Const, 1},
+		{"ETHERTYPE_HAYES", Const, 1},
+		{"ETHERTYPE_HIPPI_FP", Const, 1},
+		{"ETHERTYPE_HITACHI", Const, 1},
+		{"ETHERTYPE_HP", Const, 1},
+		{"ETHERTYPE_IEEEPUP", Const, 1},
+		{"ETHERTYPE_IEEEPUPAT", Const, 1},
+		{"ETHERTYPE_IMLBL", Const, 1},
+		{"ETHERTYPE_IMLBLDIAG", Const, 1},
+		{"ETHERTYPE_IP", Const, 1},
+		{"ETHERTYPE_IPAS", Const, 1},
+		{"ETHERTYPE_IPV6", Const, 1},
+		{"ETHERTYPE_IPX", Const, 1},
+		{"ETHERTYPE_IPXNEW", Const, 1},
+		{"ETHERTYPE_KALPANA", Const, 1},
+		{"ETHERTYPE_LANBRIDGE", Const, 1},
+		{"ETHERTYPE_LANPROBE", Const, 1},
+		{"ETHERTYPE_LAT", Const, 1},
+		{"ETHERTYPE_LBACK", Const, 1},
+		{"ETHERTYPE_LITTLE", Const, 1},
+		{"ETHERTYPE_LLDP", Const, 1},
+		{"ETHERTYPE_LOGICRAFT", Const, 1},
+		{"ETHERTYPE_LOOPBACK", Const, 1},
+		{"ETHERTYPE_MATRA", Const, 1},
+		{"ETHERTYPE_MAX", Const, 1},
+		{"ETHERTYPE_MERIT", Const, 1},
+		{"ETHERTYPE_MICP", Const, 1},
+		{"ETHERTYPE_MOPDL", Const, 1},
+		{"ETHERTYPE_MOPRC", Const, 1},
+		{"ETHERTYPE_MOTOROLA", Const, 1},
+		{"ETHERTYPE_MPLS", Const, 1},
+		{"ETHERTYPE_MPLS_MCAST", Const, 1},
+		{"ETHERTYPE_MUMPS", Const, 1},
+		{"ETHERTYPE_NBPCC", Const, 1},
+		{"ETHERTYPE_NBPCLAIM", Const, 1},
+		{"ETHERTYPE_NBPCLREQ", Const, 1},
+		{"ETHERTYPE_NBPCLRSP", Const, 1},
+		{"ETHERTYPE_NBPCREQ", Const, 1},
+		{"ETHERTYPE_NBPCRSP", Const, 1},
+		{"ETHERTYPE_NBPDG", Const, 1},
+		{"ETHERTYPE_NBPDGB", Const, 1},
+		{"ETHERTYPE_NBPDLTE", Const, 1},
+		{"ETHERTYPE_NBPRAR", Const, 1},
+		{"ETHERTYPE_NBPRAS", Const, 1},
+		{"ETHERTYPE_NBPRST", Const, 1},
+		{"ETHERTYPE_NBPSCD", Const, 1},
+		{"ETHERTYPE_NBPVCD", Const, 1},
+		{"ETHERTYPE_NBS", Const, 1},
+		{"ETHERTYPE_NCD", Const, 1},
+		{"ETHERTYPE_NESTAR", Const, 1},
+		{"ETHERTYPE_NETBEUI", Const, 1},
+		{"ETHERTYPE_NOVELL", Const, 1},
+		{"ETHERTYPE_NS", Const, 1},
+		{"ETHERTYPE_NSAT", Const, 1},
+		{"ETHERTYPE_NSCOMPAT", Const, 1},
+		{"ETHERTYPE_NTRAILER", Const, 1},
+		{"ETHERTYPE_OS9", Const, 1},
+		{"ETHERTYPE_OS9NET", Const, 1},
+		{"ETHERTYPE_PACER", Const, 1},
+		{"ETHERTYPE_PAE", Const, 1},
+		{"ETHERTYPE_PCS", Const, 1},
+		{"ETHERTYPE_PLANNING", Const, 1},
+		{"ETHERTYPE_PPP", Const, 1},
+		{"ETHERTYPE_PPPOE", Const, 1},
+		{"ETHERTYPE_PPPOEDISC", Const, 1},
+		{"ETHERTYPE_PRIMENTS", Const, 1},
+		{"ETHERTYPE_PUP", Const, 1},
+		{"ETHERTYPE_PUPAT", Const, 1},
+		{"ETHERTYPE_QINQ", Const, 1},
+		{"ETHERTYPE_RACAL", Const, 1},
+		{"ETHERTYPE_RATIONAL", Const, 1},
+		{"ETHERTYPE_RAWFR", Const, 1},
+		{"ETHERTYPE_RCL", Const, 1},
+		{"ETHERTYPE_RDP", Const, 1},
+		{"ETHERTYPE_RETIX", Const, 1},
+		{"ETHERTYPE_REVARP", Const, 1},
+		{"ETHERTYPE_SCA", Const, 1},
+		{"ETHERTYPE_SECTRA", Const, 1},
+		{"ETHERTYPE_SECUREDATA", Const, 1},
+		{"ETHERTYPE_SGITW", Const, 1},
+		{"ETHERTYPE_SG_BOUNCE", Const, 1},
+		{"ETHERTYPE_SG_DIAG", Const, 1},
+		{"ETHERTYPE_SG_NETGAMES", Const, 1},
+		{"ETHERTYPE_SG_RESV", Const, 1},
+		{"ETHERTYPE_SIMNET", Const, 1},
+		{"ETHERTYPE_SLOW", Const, 1},
+		{"ETHERTYPE_SLOWPROTOCOLS", Const, 1},
+		{"ETHERTYPE_SNA", Const, 1},
+		{"ETHERTYPE_SNMP", Const, 1},
+		{"ETHERTYPE_SONIX", Const, 1},
+		{"ETHERTYPE_SPIDER", Const, 1},
+		{"ETHERTYPE_SPRITE", Const, 1},
+		{"ETHERTYPE_STP", Const, 1},
+		{"ETHERTYPE_TALARIS", Const, 1},
+		{"ETHERTYPE_TALARISMC", Const, 1},
+		{"ETHERTYPE_TCPCOMP", Const, 1},
+		{"ETHERTYPE_TCPSM", Const, 1},
+		{"ETHERTYPE_TEC", Const, 1},
+		{"ETHERTYPE_TIGAN", Const, 1},
+		{"ETHERTYPE_TRAIL", Const, 1},
+		{"ETHERTYPE_TRANSETHER", Const, 1},
+		{"ETHERTYPE_TYMSHARE", Const, 1},
+		{"ETHERTYPE_UBBST", Const, 1},
+		{"ETHERTYPE_UBDEBUG", Const, 1},
+		{"ETHERTYPE_UBDIAGLOOP", Const, 1},
+		{"ETHERTYPE_UBDL", Const, 1},
+		{"ETHERTYPE_UBNIU", Const, 1},
+		{"ETHERTYPE_UBNMC", Const, 1},
+		{"ETHERTYPE_VALID", Const, 1},
+		{"ETHERTYPE_VARIAN", Const, 1},
+		{"ETHERTYPE_VAXELN", Const, 1},
+		{"ETHERTYPE_VEECO", Const, 1},
+		{"ETHERTYPE_VEXP", Const, 1},
+		{"ETHERTYPE_VGLAB", Const, 1},
+		{"ETHERTYPE_VINES", Const, 1},
+		{"ETHERTYPE_VINESECHO", Const, 1},
+		{"ETHERTYPE_VINESLOOP", Const, 1},
+		{"ETHERTYPE_VITAL", Const, 1},
+		{"ETHERTYPE_VLAN", Const, 1},
+		{"ETHERTYPE_VLTLMAN", Const, 1},
+		{"ETHERTYPE_VPROD", Const, 1},
+		{"ETHERTYPE_VURESERVED", Const, 1},
+		{"ETHERTYPE_WATERLOO", Const, 1},
+		{"ETHERTYPE_WELLFLEET", Const, 1},
+		{"ETHERTYPE_X25", Const, 1},
+		{"ETHERTYPE_X75", Const, 1},
+		{"ETHERTYPE_XNSSM", Const, 1},
+		{"ETHERTYPE_XTP", Const, 1},
+		{"ETHER_ADDR_LEN", Const, 1},
+		{"ETHER_ALIGN", Const, 1},
+		{"ETHER_CRC_LEN", Const, 1},
+		{"ETHER_CRC_POLY_BE", Const, 1},
+		{"ETHER_CRC_POLY_LE", Const, 1},
+		{"ETHER_HDR_LEN", Const, 1},
+		{"ETHER_MAX_DIX_LEN", Const, 1},
+		{"ETHER_MAX_LEN", Const, 1},
+		{"ETHER_MAX_LEN_JUMBO", Const, 1},
+		{"ETHER_MIN_LEN", Const, 1},
+		{"ETHER_PPPOE_ENCAP_LEN", Const, 1},
+		{"ETHER_TYPE_LEN", Const, 1},
+		{"ETHER_VLAN_ENCAP_LEN", Const, 1},
+		{"ETH_P_1588", Const, 0},
+		{"ETH_P_8021Q", Const, 0},
+		{"ETH_P_802_2", Const, 0},
+		{"ETH_P_802_3", Const, 0},
+		{"ETH_P_AARP", Const, 0},
+		{"ETH_P_ALL", Const, 0},
+		{"ETH_P_AOE", Const, 0},
+		{"ETH_P_ARCNET", Const, 0},
+		{"ETH_P_ARP", Const, 0},
+		{"ETH_P_ATALK", Const, 0},
+		{"ETH_P_ATMFATE", Const, 0},
+		{"ETH_P_ATMMPOA", Const, 0},
+		{"ETH_P_AX25", Const, 0},
+		{"ETH_P_BPQ", Const, 0},
+		{"ETH_P_CAIF", Const, 0},
+		{"ETH_P_CAN", Const, 0},
+		{"ETH_P_CONTROL", Const, 0},
+		{"ETH_P_CUST", Const, 0},
+		{"ETH_P_DDCMP", Const, 0},
+		{"ETH_P_DEC", Const, 0},
+		{"ETH_P_DIAG", Const, 0},
+		{"ETH_P_DNA_DL", Const, 0},
+		{"ETH_P_DNA_RC", Const, 0},
+		{"ETH_P_DNA_RT", Const, 0},
+		{"ETH_P_DSA", Const, 0},
+		{"ETH_P_ECONET", Const, 0},
+		{"ETH_P_EDSA", Const, 0},
+		{"ETH_P_FCOE", Const, 0},
+		{"ETH_P_FIP", Const, 0},
+		{"ETH_P_HDLC", Const, 0},
+		{"ETH_P_IEEE802154", Const, 0},
+		{"ETH_P_IEEEPUP", Const, 0},
+		{"ETH_P_IEEEPUPAT", Const, 0},
+		{"ETH_P_IP", Const, 0},
+		{"ETH_P_IPV6", Const, 0},
+		{"ETH_P_IPX", Const, 0},
+		{"ETH_P_IRDA", Const, 0},
+		{"ETH_P_LAT", Const, 0},
+		{"ETH_P_LINK_CTL", Const, 0},
+		{"ETH_P_LOCALTALK", Const, 0},
+		{"ETH_P_LOOP", Const, 0},
+		{"ETH_P_MOBITEX", Const, 0},
+		{"ETH_P_MPLS_MC", Const, 0},
+		{"ETH_P_MPLS_UC", Const, 0},
+		{"ETH_P_PAE", Const, 0},
+		{"ETH_P_PAUSE", Const, 0},
+		{"ETH_P_PHONET", Const, 0},
+		{"ETH_P_PPPTALK", Const, 0},
+		{"ETH_P_PPP_DISC", Const, 0},
+		{"ETH_P_PPP_MP", Const, 0},
+		{"ETH_P_PPP_SES", Const, 0},
+		{"ETH_P_PUP", Const, 0},
+		{"ETH_P_PUPAT", Const, 0},
+		{"ETH_P_RARP", Const, 0},
+		{"ETH_P_SCA", Const, 0},
+		{"ETH_P_SLOW", Const, 0},
+		{"ETH_P_SNAP", Const, 0},
+		{"ETH_P_TEB", Const, 0},
+		{"ETH_P_TIPC", Const, 0},
+		{"ETH_P_TRAILER", Const, 0},
+		{"ETH_P_TR_802_2", Const, 0},
+		{"ETH_P_WAN_PPP", Const, 0},
+		{"ETH_P_WCCP", Const, 0},
+		{"ETH_P_X25", Const, 0},
+		{"ETIME", Const, 0},
+		{"ETIMEDOUT", Const, 0},
+		{"ETOOMANYREFS", Const, 0},
+		{"ETXTBSY", Const, 0},
+		{"EUCLEAN", Const, 0},
+		{"EUNATCH", Const, 0},
+		{"EUSERS", Const, 0},
+		{"EVFILT_AIO", Const, 0},
+		{"EVFILT_FS", Const, 0},
+		{"EVFILT_LIO", Const, 0},
+		{"EVFILT_MACHPORT", Const, 0},
+		{"EVFILT_PROC", Const, 0},
+		{"EVFILT_READ", Const, 0},
+		{"EVFILT_SIGNAL", Const, 0},
+		{"EVFILT_SYSCOUNT", Const, 0},
+		{"EVFILT_THREADMARKER", Const, 0},
+		{"EVFILT_TIMER", Const, 0},
+		{"EVFILT_USER", Const, 0},
+		{"EVFILT_VM", Const, 0},
+		{"EVFILT_VNODE", Const, 0},
+		{"EVFILT_WRITE", Const, 0},
+		{"EV_ADD", Const, 0},
+		{"EV_CLEAR", Const, 0},
+		{"EV_DELETE", Const, 0},
+		{"EV_DISABLE", Const, 0},
+		{"EV_DISPATCH", Const, 0},
+		{"EV_DROP", Const, 3},
+		{"EV_ENABLE", Const, 0},
+		{"EV_EOF", Const, 0},
+		{"EV_ERROR", Const, 0},
+		{"EV_FLAG0", Const, 0},
+		{"EV_FLAG1", Const, 0},
+		{"EV_ONESHOT", Const, 0},
+		{"EV_OOBAND", Const, 0},
+		{"EV_POLL", Const, 0},
+		{"EV_RECEIPT", Const, 0},
+		{"EV_SYSFLAGS", Const, 0},
+		{"EWINDOWS", Const, 0},
+		{"EWOULDBLOCK", Const, 0},
+		{"EXDEV", Const, 0},
+		{"EXFULL", Const, 0},
+		{"EXTA", Const, 0},
+		{"EXTB", Const, 0},
+		{"EXTPROC", Const, 0},
+		{"Environ", Func, 0},
+		{"EpollCreate", Func, 0},
+		{"EpollCreate1", Func, 0},
+		{"EpollCtl", Func, 0},
+		{"EpollEvent", Type, 0},
+		{"EpollEvent.Events", Field, 0},
+		{"EpollEvent.Fd", Field, 0},
+		{"EpollEvent.Pad", Field, 0},
+		{"EpollEvent.PadFd", Field, 0},
+		{"EpollWait", Func, 0},
+		{"Errno", Type, 0},
+		{"EscapeArg", Func, 0},
+		{"Exchangedata", Func, 0},
+		{"Exec", Func, 0},
+		{"Exit", Func, 0},
+		{"ExitProcess", Func, 0},
+		{"FD_CLOEXEC", Const, 0},
+		{"FD_SETSIZE", Const, 0},
+		{"FILE_ACTION_ADDED", Const, 0},
+		{"FILE_ACTION_MODIFIED", Const, 0},
+		{"FILE_ACTION_REMOVED", Const, 0},
+		{"FILE_ACTION_RENAMED_NEW_NAME", Const, 0},
+		{"FILE_ACTION_RENAMED_OLD_NAME", Const, 0},
+		{"FILE_APPEND_DATA", Const, 0},
+		{"FILE_ATTRIBUTE_ARCHIVE", Const, 0},
+		{"FILE_ATTRIBUTE_DIRECTORY", Const, 0},
+		{"FILE_ATTRIBUTE_HIDDEN", Const, 0},
+		{"FILE_ATTRIBUTE_NORMAL", Const, 0},
+		{"FILE_ATTRIBUTE_READONLY", Const, 0},
+		{"FILE_ATTRIBUTE_REPARSE_POINT", Const, 4},
+		{"FILE_ATTRIBUTE_SYSTEM", Const, 0},
+		{"FILE_BEGIN", Const, 0},
+		{"FILE_CURRENT", Const, 0},
+		{"FILE_END", Const, 0},
+		{"FILE_FLAG_BACKUP_SEMANTICS", Const, 0},
+		{"FILE_FLAG_OPEN_REPARSE_POINT", Const, 4},
+		{"FILE_FLAG_OVERLAPPED", Const, 0},
+		{"FILE_LIST_DIRECTORY", Const, 0},
+		{"FILE_MAP_COPY", Const, 0},
+		{"FILE_MAP_EXECUTE", Const, 0},
+		{"FILE_MAP_READ", Const, 0},
+		{"FILE_MAP_WRITE", Const, 0},
+		{"FILE_NOTIFY_CHANGE_ATTRIBUTES", Const, 0},
+		{"FILE_NOTIFY_CHANGE_CREATION", Const, 0},
+		{"FILE_NOTIFY_CHANGE_DIR_NAME", Const, 0},
+		{"FILE_NOTIFY_CHANGE_FILE_NAME", Const, 0},
+		{"FILE_NOTIFY_CHANGE_LAST_ACCESS", Const, 0},
+		{"FILE_NOTIFY_CHANGE_LAST_WRITE", Const, 0},
+		{"FILE_NOTIFY_CHANGE_SIZE", Const, 0},
+		{"FILE_SHARE_DELETE", Const, 0},
+		{"FILE_SHARE_READ", Const, 0},
+		{"FILE_SHARE_WRITE", Const, 0},
+		{"FILE_SKIP_COMPLETION_PORT_ON_SUCCESS", Const, 2},
+		{"FILE_SKIP_SET_EVENT_ON_HANDLE", Const, 2},
+		{"FILE_TYPE_CHAR", Const, 0},
+		{"FILE_TYPE_DISK", Const, 0},
+		{"FILE_TYPE_PIPE", Const, 0},
+		{"FILE_TYPE_REMOTE", Const, 0},
+		{"FILE_TYPE_UNKNOWN", Const, 0},
+		{"FILE_WRITE_ATTRIBUTES", Const, 0},
+		{"FLUSHO", Const, 0},
+		{"FORMAT_MESSAGE_ALLOCATE_BUFFER", Const, 0},
+		{"FORMAT_MESSAGE_ARGUMENT_ARRAY", Const, 0},
+		{"FORMAT_MESSAGE_FROM_HMODULE", Const, 0},
+		{"FORMAT_MESSAGE_FROM_STRING", Const, 0},
+		{"FORMAT_MESSAGE_FROM_SYSTEM", Const, 0},
+		{"FORMAT_MESSAGE_IGNORE_INSERTS", Const, 0},
+		{"FORMAT_MESSAGE_MAX_WIDTH_MASK", Const, 0},
+		{"FSCTL_GET_REPARSE_POINT", Const, 4},
+		{"F_ADDFILESIGS", Const, 0},
+		{"F_ADDSIGS", Const, 0},
+		{"F_ALLOCATEALL", Const, 0},
+		{"F_ALLOCATECONTIG", Const, 0},
+		{"F_CANCEL", Const, 0},
+		{"F_CHKCLEAN", Const, 0},
+		{"F_CLOSEM", Const, 1},
+		{"F_DUP2FD", Const, 0},
+		{"F_DUP2FD_CLOEXEC", Const, 1},
+		{"F_DUPFD", Const, 0},
+		{"F_DUPFD_CLOEXEC", Const, 0},
+		{"F_EXLCK", Const, 0},
+		{"F_FINDSIGS", Const, 16},
+		{"F_FLUSH_DATA", Const, 0},
+		{"F_FREEZE_FS", Const, 0},
+		{"F_FSCTL", Const, 1},
+		{"F_FSDIRMASK", Const, 1},
+		{"F_FSIN", Const, 1},
+		{"F_FSINOUT", Const, 1},
+		{"F_FSOUT", Const, 1},
+		{"F_FSPRIV", Const, 1},
+		{"F_FSVOID", Const, 1},
+		{"F_FULLFSYNC", Const, 0},
+		{"F_GETCODEDIR", Const, 16},
+		{"F_GETFD", Const, 0},
+		{"F_GETFL", Const, 0},
+		{"F_GETLEASE", Const, 0},
+		{"F_GETLK", Const, 0},
+		{"F_GETLK64", Const, 0},
+		{"F_GETLKPID", Const, 0},
+		{"F_GETNOSIGPIPE", Const, 0},
+		{"F_GETOWN", Const, 0},
+		{"F_GETOWN_EX", Const, 0},
+		{"F_GETPATH", Const, 0},
+		{"F_GETPATH_MTMINFO", Const, 0},
+		{"F_GETPIPE_SZ", Const, 0},
+		{"F_GETPROTECTIONCLASS", Const, 0},
+		{"F_GETPROTECTIONLEVEL", Const, 16},
+		{"F_GETSIG", Const, 0},
+		{"F_GLOBAL_NOCACHE", Const, 0},
+		{"F_LOCK", Const, 0},
+		{"F_LOG2PHYS", Const, 0},
+		{"F_LOG2PHYS_EXT", Const, 0},
+		{"F_MARKDEPENDENCY", Const, 0},
+		{"F_MAXFD", Const, 1},
+		{"F_NOCACHE", Const, 0},
+		{"F_NODIRECT", Const, 0},
+		{"F_NOTIFY", Const, 0},
+		{"F_OGETLK", Const, 0},
+		{"F_OK", Const, 0},
+		{"F_OSETLK", Const, 0},
+		{"F_OSETLKW", Const, 0},
+		{"F_PARAM_MASK", Const, 1},
+		{"F_PARAM_MAX", Const, 1},
+		{"F_PATHPKG_CHECK", Const, 0},
+		{"F_PEOFPOSMODE", Const, 0},
+		{"F_PREALLOCATE", Const, 0},
+		{"F_RDADVISE", Const, 0},
+		{"F_RDAHEAD", Const, 0},
+		{"F_RDLCK", Const, 0},
+		{"F_READAHEAD", Const, 0},
+		{"F_READBOOTSTRAP", Const, 0},
+		{"F_SETBACKINGSTORE", Const, 0},
+		{"F_SETFD", Const, 0},
+		{"F_SETFL", Const, 0},
+		{"F_SETLEASE", Const, 0},
+		{"F_SETLK", Const, 0},
+		{"F_SETLK64", Const, 0},
+		{"F_SETLKW", Const, 0},
+		{"F_SETLKW64", Const, 0},
+		{"F_SETLKWTIMEOUT", Const, 16},
+		{"F_SETLK_REMOTE", Const, 0},
+		{"F_SETNOSIGPIPE", Const, 0},
+		{"F_SETOWN", Const, 0},
+		{"F_SETOWN_EX", Const, 0},
+		{"F_SETPIPE_SZ", Const, 0},
+		{"F_SETPROTECTIONCLASS", Const, 0},
+		{"F_SETSIG", Const, 0},
+		{"F_SETSIZE", Const, 0},
+		{"F_SHLCK", Const, 0},
+		{"F_SINGLE_WRITER", Const, 16},
+		{"F_TEST", Const, 0},
+		{"F_THAW_FS", Const, 0},
+		{"F_TLOCK", Const, 0},
+		{"F_TRANSCODEKEY", Const, 16},
+		{"F_ULOCK", Const, 0},
+		{"F_UNLCK", Const, 0},
+		{"F_UNLCKSYS", Const, 0},
+		{"F_VOLPOSMODE", Const, 0},
+		{"F_WRITEBOOTSTRAP", Const, 0},
+		{"F_WRLCK", Const, 0},
+		{"Faccessat", Func, 0},
+		{"Fallocate", Func, 0},
+		{"Fbootstraptransfer_t", Type, 0},
+		{"Fbootstraptransfer_t.Buffer", Field, 0},
+		{"Fbootstraptransfer_t.Length", Field, 0},
+		{"Fbootstraptransfer_t.Offset", Field, 0},
+		{"Fchdir", Func, 0},
+		{"Fchflags", Func, 0},
+		{"Fchmod", Func, 0},
+		{"Fchmodat", Func, 0},
+		{"Fchown", Func, 0},
+		{"Fchownat", Func, 0},
+		{"FcntlFlock", Func, 3},
+		{"FdSet", Type, 0},
+		{"FdSet.Bits", Field, 0},
+		{"FdSet.X__fds_bits", Field, 0},
+		{"Fdatasync", Func, 0},
+		{"FileNotifyInformation", Type, 0},
+		{"FileNotifyInformation.Action", Field, 0},
+		{"FileNotifyInformation.FileName", Field, 0},
+		{"FileNotifyInformation.FileNameLength", Field, 0},
+		{"FileNotifyInformation.NextEntryOffset", Field, 0},
+		{"Filetime", Type, 0},
+		{"Filetime.HighDateTime", Field, 0},
+		{"Filetime.LowDateTime", Field, 0},
+		{"FindClose", Func, 0},
+		{"FindFirstFile", Func, 0},
+		{"FindNextFile", Func, 0},
+		{"Flock", Func, 0},
+		{"Flock_t", Type, 0},
+		{"Flock_t.Len", Field, 0},
+		{"Flock_t.Pad_cgo_0", Field, 0},
+		{"Flock_t.Pad_cgo_1", Field, 3},
+		{"Flock_t.Pid", Field, 0},
+		{"Flock_t.Start", Field, 0},
+		{"Flock_t.Sysid", Field, 0},
+		{"Flock_t.Type", Field, 0},
+		{"Flock_t.Whence", Field, 0},
+		{"FlushBpf", Func, 0},
+		{"FlushFileBuffers", Func, 0},
+		{"FlushViewOfFile", Func, 0},
+		{"ForkExec", Func, 0},
+		{"ForkLock", Var, 0},
+		{"FormatMessage", Func, 0},
+		{"Fpathconf", Func, 0},
+		{"FreeAddrInfoW", Func, 1},
+		{"FreeEnvironmentStrings", Func, 0},
+		{"FreeLibrary", Func, 0},
+		{"Fsid", Type, 0},
+		{"Fsid.Val", Field, 0},
+		{"Fsid.X__fsid_val", Field, 2},
+		{"Fsid.X__val", Field, 0},
+		{"Fstat", Func, 0},
+		{"Fstatat", Func, 12},
+		{"Fstatfs", Func, 0},
+		{"Fstore_t", Type, 0},
+		{"Fstore_t.Bytesalloc", Field, 0},
+		{"Fstore_t.Flags", Field, 0},
+		{"Fstore_t.Length", Field, 0},
+		{"Fstore_t.Offset", Field, 0},
+		{"Fstore_t.Posmode", Field, 0},
+		{"Fsync", Func, 0},
+		{"Ftruncate", Func, 0},
+		{"FullPath", Func, 4},
+		{"Futimes", Func, 0},
+		{"Futimesat", Func, 0},
+		{"GENERIC_ALL", Const, 0},
+		{"GENERIC_EXECUTE", Const, 0},
+		{"GENERIC_READ", Const, 0},
+		{"GENERIC_WRITE", Const, 0},
+		{"GUID", Type, 1},
+		{"GUID.Data1", Field, 1},
+		{"GUID.Data2", Field, 1},
+		{"GUID.Data3", Field, 1},
+		{"GUID.Data4", Field, 1},
+		{"GetAcceptExSockaddrs", Func, 0},
+		{"GetAdaptersInfo", Func, 0},
+		{"GetAddrInfoW", Func, 1},
+		{"GetCommandLine", Func, 0},
+		{"GetComputerName", Func, 0},
+		{"GetConsoleMode", Func, 1},
+		{"GetCurrentDirectory", Func, 0},
+		{"GetCurrentProcess", Func, 0},
+		{"GetEnvironmentStrings", Func, 0},
+		{"GetEnvironmentVariable", Func, 0},
+		{"GetExitCodeProcess", Func, 0},
+		{"GetFileAttributes", Func, 0},
+		{"GetFileAttributesEx", Func, 0},
+		{"GetFileExInfoStandard", Const, 0},
+		{"GetFileExMaxInfoLevel", Const, 0},
+		{"GetFileInformationByHandle", Func, 0},
+		{"GetFileType", Func, 0},
+		{"GetFullPathName", Func, 0},
+		{"GetHostByName", Func, 0},
+		{"GetIfEntry", Func, 0},
+		{"GetLastError", Func, 0},
+		{"GetLengthSid", Func, 0},
+		{"GetLongPathName", Func, 0},
+		{"GetProcAddress", Func, 0},
+		{"GetProcessTimes", Func, 0},
+		{"GetProtoByName", Func, 0},
+		{"GetQueuedCompletionStatus", Func, 0},
+		{"GetServByName", Func, 0},
+		{"GetShortPathName", Func, 0},
+		{"GetStartupInfo", Func, 0},
+		{"GetStdHandle", Func, 0},
+		{"GetSystemTimeAsFileTime", Func, 0},
+		{"GetTempPath", Func, 0},
+		{"GetTimeZoneInformation", Func, 0},
+		{"GetTokenInformation", Func, 0},
+		{"GetUserNameEx", Func, 0},
+		{"GetUserProfileDirectory", Func, 0},
+		{"GetVersion", Func, 0},
+		{"Getcwd", Func, 0},
+		{"Getdents", Func, 0},
+		{"Getdirentries", Func, 0},
+		{"Getdtablesize", Func, 0},
+		{"Getegid", Func, 0},
+		{"Getenv", Func, 0},
+		{"Geteuid", Func, 0},
+		{"Getfsstat", Func, 0},
+		{"Getgid", Func, 0},
+		{"Getgroups", Func, 0},
+		{"Getpagesize", Func, 0},
+		{"Getpeername", Func, 0},
+		{"Getpgid", Func, 0},
+		{"Getpgrp", Func, 0},
+		{"Getpid", Func, 0},
+		{"Getppid", Func, 0},
+		{"Getpriority", Func, 0},
+		{"Getrlimit", Func, 0},
+		{"Getrusage", Func, 0},
+		{"Getsid", Func, 0},
+		{"Getsockname", Func, 0},
+		{"Getsockopt", Func, 1},
+		{"GetsockoptByte", Func, 0},
+		{"GetsockoptICMPv6Filter", Func, 2},
+		{"GetsockoptIPMreq", Func, 0},
+		{"GetsockoptIPMreqn", Func, 0},
+		{"GetsockoptIPv6MTUInfo", Func, 2},
+		{"GetsockoptIPv6Mreq", Func, 0},
+		{"GetsockoptInet4Addr", Func, 0},
+		{"GetsockoptInt", Func, 0},
+		{"GetsockoptUcred", Func, 1},
+		{"Gettid", Func, 0},
+		{"Gettimeofday", Func, 0},
+		{"Getuid", Func, 0},
+		{"Getwd", Func, 0},
+		{"Getxattr", Func, 1},
+		{"HANDLE_FLAG_INHERIT", Const, 0},
+		{"HKEY_CLASSES_ROOT", Const, 0},
+		{"HKEY_CURRENT_CONFIG", Const, 0},
+		{"HKEY_CURRENT_USER", Const, 0},
+		{"HKEY_DYN_DATA", Const, 0},
+		{"HKEY_LOCAL_MACHINE", Const, 0},
+		{"HKEY_PERFORMANCE_DATA", Const, 0},
+		{"HKEY_USERS", Const, 0},
+		{"HUPCL", Const, 0},
+		{"Handle", Type, 0},
+		{"Hostent", Type, 0},
+		{"Hostent.AddrList", Field, 0},
+		{"Hostent.AddrType", Field, 0},
+		{"Hostent.Aliases", Field, 0},
+		{"Hostent.Length", Field, 0},
+		{"Hostent.Name", Field, 0},
+		{"ICANON", Const, 0},
+		{"ICMP6_FILTER", Const, 2},
+		{"ICMPV6_FILTER", Const, 2},
+		{"ICMPv6Filter", Type, 2},
+		{"ICMPv6Filter.Data", Field, 2},
+		{"ICMPv6Filter.Filt", Field, 2},
+		{"ICRNL", Const, 0},
+		{"IEXTEN", Const, 0},
+		{"IFAN_ARRIVAL", Const, 1},
+		{"IFAN_DEPARTURE", Const, 1},
+		{"IFA_ADDRESS", Const, 0},
+		{"IFA_ANYCAST", Const, 0},
+		{"IFA_BROADCAST", Const, 0},
+		{"IFA_CACHEINFO", Const, 0},
+		{"IFA_F_DADFAILED", Const, 0},
+		{"IFA_F_DEPRECATED", Const, 0},
+		{"IFA_F_HOMEADDRESS", Const, 0},
+		{"IFA_F_NODAD", Const, 0},
+		{"IFA_F_OPTIMISTIC", Const, 0},
+		{"IFA_F_PERMANENT", Const, 0},
+		{"IFA_F_SECONDARY", Const, 0},
+		{"IFA_F_TEMPORARY", Const, 0},
+		{"IFA_F_TENTATIVE", Const, 0},
+		{"IFA_LABEL", Const, 0},
+		{"IFA_LOCAL", Const, 0},
+		{"IFA_MAX", Const, 0},
+		{"IFA_MULTICAST", Const, 0},
+		{"IFA_ROUTE", Const, 1},
+		{"IFA_UNSPEC", Const, 0},
+		{"IFF_ALLMULTI", Const, 0},
+		{"IFF_ALTPHYS", Const, 0},
+		{"IFF_AUTOMEDIA", Const, 0},
+		{"IFF_BROADCAST", Const, 0},
+		{"IFF_CANTCHANGE", Const, 0},
+		{"IFF_CANTCONFIG", Const, 1},
+		{"IFF_DEBUG", Const, 0},
+		{"IFF_DRV_OACTIVE", Const, 0},
+		{"IFF_DRV_RUNNING", Const, 0},
+		{"IFF_DYING", Const, 0},
+		{"IFF_DYNAMIC", Const, 0},
+		{"IFF_LINK0", Const, 0},
+		{"IFF_LINK1", Const, 0},
+		{"IFF_LINK2", Const, 0},
+		{"IFF_LOOPBACK", Const, 0},
+		{"IFF_MASTER", Const, 0},
+		{"IFF_MONITOR", Const, 0},
+		{"IFF_MULTICAST", Const, 0},
+		{"IFF_NOARP", Const, 0},
+		{"IFF_NOTRAILERS", Const, 0},
+		{"IFF_NO_PI", Const, 0},
+		{"IFF_OACTIVE", Const, 0},
+		{"IFF_ONE_QUEUE", Const, 0},
+		{"IFF_POINTOPOINT", Const, 0},
+		{"IFF_POINTTOPOINT", Const, 0},
+		{"IFF_PORTSEL", Const, 0},
+		{"IFF_PPROMISC", Const, 0},
+		{"IFF_PROMISC", Const, 0},
+		{"IFF_RENAMING", Const, 0},
+		{"IFF_RUNNING", Const, 0},
+		{"IFF_SIMPLEX", Const, 0},
+		{"IFF_SLAVE", Const, 0},
+		{"IFF_SMART", Const, 0},
+		{"IFF_STATICARP", Const, 0},
+		{"IFF_TAP", Const, 0},
+		{"IFF_TUN", Const, 0},
+		{"IFF_TUN_EXCL", Const, 0},
+		{"IFF_UP", Const, 0},
+		{"IFF_VNET_HDR", Const, 0},
+		{"IFLA_ADDRESS", Const, 0},
+		{"IFLA_BROADCAST", Const, 0},
+		{"IFLA_COST", Const, 0},
+		{"IFLA_IFALIAS", Const, 0},
+		{"IFLA_IFNAME", Const, 0},
+		{"IFLA_LINK", Const, 0},
+		{"IFLA_LINKINFO", Const, 0},
+		{"IFLA_LINKMODE", Const, 0},
+		{"IFLA_MAP", Const, 0},
+		{"IFLA_MASTER", Const, 0},
+		{"IFLA_MAX", Const, 0},
+		{"IFLA_MTU", Const, 0},
+		{"IFLA_NET_NS_PID", Const, 0},
+		{"IFLA_OPERSTATE", Const, 0},
+		{"IFLA_PRIORITY", Const, 0},
+		{"IFLA_PROTINFO", Const, 0},
+		{"IFLA_QDISC", Const, 0},
+		{"IFLA_STATS", Const, 0},
+		{"IFLA_TXQLEN", Const, 0},
+		{"IFLA_UNSPEC", Const, 0},
+		{"IFLA_WEIGHT", Const, 0},
+		{"IFLA_WIRELESS", Const, 0},
+		{"IFNAMSIZ", Const, 0},
+		{"IFT_1822", Const, 0},
+		{"IFT_A12MPPSWITCH", Const, 0},
+		{"IFT_AAL2", Const, 0},
+		{"IFT_AAL5", Const, 0},
+		{"IFT_ADSL", Const, 0},
+		{"IFT_AFLANE8023", Const, 0},
+		{"IFT_AFLANE8025", Const, 0},
+		{"IFT_ARAP", Const, 0},
+		{"IFT_ARCNET", Const, 0},
+		{"IFT_ARCNETPLUS", Const, 0},
+		{"IFT_ASYNC", Const, 0},
+		{"IFT_ATM", Const, 0},
+		{"IFT_ATMDXI", Const, 0},
+		{"IFT_ATMFUNI", Const, 0},
+		{"IFT_ATMIMA", Const, 0},
+		{"IFT_ATMLOGICAL", Const, 0},
+		{"IFT_ATMRADIO", Const, 0},
+		{"IFT_ATMSUBINTERFACE", Const, 0},
+		{"IFT_ATMVCIENDPT", Const, 0},
+		{"IFT_ATMVIRTUAL", Const, 0},
+		{"IFT_BGPPOLICYACCOUNTING", Const, 0},
+		{"IFT_BLUETOOTH", Const, 1},
+		{"IFT_BRIDGE", Const, 0},
+		{"IFT_BSC", Const, 0},
+		{"IFT_CARP", Const, 0},
+		{"IFT_CCTEMUL", Const, 0},
+		{"IFT_CELLULAR", Const, 0},
+		{"IFT_CEPT", Const, 0},
+		{"IFT_CES", Const, 0},
+		{"IFT_CHANNEL", Const, 0},
+		{"IFT_CNR", Const, 0},
+		{"IFT_COFFEE", Const, 0},
+		{"IFT_COMPOSITELINK", Const, 0},
+		{"IFT_DCN", Const, 0},
+		{"IFT_DIGITALPOWERLINE", Const, 0},
+		{"IFT_DIGITALWRAPPEROVERHEADCHANNEL", Const, 0},
+		{"IFT_DLSW", Const, 0},
+		{"IFT_DOCSCABLEDOWNSTREAM", Const, 0},
+		{"IFT_DOCSCABLEMACLAYER", Const, 0},
+		{"IFT_DOCSCABLEUPSTREAM", Const, 0},
+		{"IFT_DOCSCABLEUPSTREAMCHANNEL", Const, 1},
+		{"IFT_DS0", Const, 0},
+		{"IFT_DS0BUNDLE", Const, 0},
+		{"IFT_DS1FDL", Const, 0},
+		{"IFT_DS3", Const, 0},
+		{"IFT_DTM", Const, 0},
+		{"IFT_DUMMY", Const, 1},
+		{"IFT_DVBASILN", Const, 0},
+		{"IFT_DVBASIOUT", Const, 0},
+		{"IFT_DVBRCCDOWNSTREAM", Const, 0},
+		{"IFT_DVBRCCMACLAYER", Const, 0},
+		{"IFT_DVBRCCUPSTREAM", Const, 0},
+		{"IFT_ECONET", Const, 1},
+		{"IFT_ENC", Const, 0},
+		{"IFT_EON", Const, 0},
+		{"IFT_EPLRS", Const, 0},
+		{"IFT_ESCON", Const, 0},
+		{"IFT_ETHER", Const, 0},
+		{"IFT_FAITH", Const, 0},
+		{"IFT_FAST", Const, 0},
+		{"IFT_FASTETHER", Const, 0},
+		{"IFT_FASTETHERFX", Const, 0},
+		{"IFT_FDDI", Const, 0},
+		{"IFT_FIBRECHANNEL", Const, 0},
+		{"IFT_FRAMERELAYINTERCONNECT", Const, 0},
+		{"IFT_FRAMERELAYMPI", Const, 0},
+		{"IFT_FRDLCIENDPT", Const, 0},
+		{"IFT_FRELAY", Const, 0},
+		{"IFT_FRELAYDCE", Const, 0},
+		{"IFT_FRF16MFRBUNDLE", Const, 0},
+		{"IFT_FRFORWARD", Const, 0},
+		{"IFT_G703AT2MB", Const, 0},
+		{"IFT_G703AT64K", Const, 0},
+		{"IFT_GIF", Const, 0},
+		{"IFT_GIGABITETHERNET", Const, 0},
+		{"IFT_GR303IDT", Const, 0},
+		{"IFT_GR303RDT", Const, 0},
+		{"IFT_H323GATEKEEPER", Const, 0},
+		{"IFT_H323PROXY", Const, 0},
+		{"IFT_HDH1822", Const, 0},
+		{"IFT_HDLC", Const, 0},
+		{"IFT_HDSL2", Const, 0},
+		{"IFT_HIPERLAN2", Const, 0},
+		{"IFT_HIPPI", Const, 0},
+		{"IFT_HIPPIINTERFACE", Const, 0},
+		{"IFT_HOSTPAD", Const, 0},
+		{"IFT_HSSI", Const, 0},
+		{"IFT_HY", Const, 0},
+		{"IFT_IBM370PARCHAN", Const, 0},
+		{"IFT_IDSL", Const, 0},
+		{"IFT_IEEE1394", Const, 0},
+		{"IFT_IEEE80211", Const, 0},
+		{"IFT_IEEE80212", Const, 0},
+		{"IFT_IEEE8023ADLAG", Const, 0},
+		{"IFT_IFGSN", Const, 0},
+		{"IFT_IMT", Const, 0},
+		{"IFT_INFINIBAND", Const, 1},
+		{"IFT_INTERLEAVE", Const, 0},
+		{"IFT_IP", Const, 0},
+		{"IFT_IPFORWARD", Const, 0},
+		{"IFT_IPOVERATM", Const, 0},
+		{"IFT_IPOVERCDLC", Const, 0},
+		{"IFT_IPOVERCLAW", Const, 0},
+		{"IFT_IPSWITCH", Const, 0},
+		{"IFT_IPXIP", Const, 0},
+		{"IFT_ISDN", Const, 0},
+		{"IFT_ISDNBASIC", Const, 0},
+		{"IFT_ISDNPRIMARY", Const, 0},
+		{"IFT_ISDNS", Const, 0},
+		{"IFT_ISDNU", Const, 0},
+		{"IFT_ISO88022LLC", Const, 0},
+		{"IFT_ISO88023", Const, 0},
+		{"IFT_ISO88024", Const, 0},
+		{"IFT_ISO88025", Const, 0},
+		{"IFT_ISO88025CRFPINT", Const, 0},
+		{"IFT_ISO88025DTR", Const, 0},
+		{"IFT_ISO88025FIBER", Const, 0},
+		{"IFT_ISO88026", Const, 0},
+		{"IFT_ISUP", Const, 0},
+		{"IFT_L2VLAN", Const, 0},
+		{"IFT_L3IPVLAN", Const, 0},
+		{"IFT_L3IPXVLAN", Const, 0},
+		{"IFT_LAPB", Const, 0},
+		{"IFT_LAPD", Const, 0},
+		{"IFT_LAPF", Const, 0},
+		{"IFT_LINEGROUP", Const, 1},
+		{"IFT_LOCALTALK", Const, 0},
+		{"IFT_LOOP", Const, 0},
+		{"IFT_MEDIAMAILOVERIP", Const, 0},
+		{"IFT_MFSIGLINK", Const, 0},
+		{"IFT_MIOX25", Const, 0},
+		{"IFT_MODEM", Const, 0},
+		{"IFT_MPC", Const, 0},
+		{"IFT_MPLS", Const, 0},
+		{"IFT_MPLSTUNNEL", Const, 0},
+		{"IFT_MSDSL", Const, 0},
+		{"IFT_MVL", Const, 0},
+		{"IFT_MYRINET", Const, 0},
+		{"IFT_NFAS", Const, 0},
+		{"IFT_NSIP", Const, 0},
+		{"IFT_OPTICALCHANNEL", Const, 0},
+		{"IFT_OPTICALTRANSPORT", Const, 0},
+		{"IFT_OTHER", Const, 0},
+		{"IFT_P10", Const, 0},
+		{"IFT_P80", Const, 0},
+		{"IFT_PARA", Const, 0},
+		{"IFT_PDP", Const, 0},
+		{"IFT_PFLOG", Const, 0},
+		{"IFT_PFLOW", Const, 1},
+		{"IFT_PFSYNC", Const, 0},
+		{"IFT_PLC", Const, 0},
+		{"IFT_PON155", Const, 1},
+		{"IFT_PON622", Const, 1},
+		{"IFT_POS", Const, 0},
+		{"IFT_PPP", Const, 0},
+		{"IFT_PPPMULTILINKBUNDLE", Const, 0},
+		{"IFT_PROPATM", Const, 1},
+		{"IFT_PROPBWAP2MP", Const, 0},
+		{"IFT_PROPCNLS", Const, 0},
+		{"IFT_PROPDOCSWIRELESSDOWNSTREAM", Const, 0},
+		{"IFT_PROPDOCSWIRELESSMACLAYER", Const, 0},
+		{"IFT_PROPDOCSWIRELESSUPSTREAM", Const, 0},
+		{"IFT_PROPMUX", Const, 0},
+		{"IFT_PROPVIRTUAL", Const, 0},
+		{"IFT_PROPWIRELESSP2P", Const, 0},
+		{"IFT_PTPSERIAL", Const, 0},
+		{"IFT_PVC", Const, 0},
+		{"IFT_Q2931", Const, 1},
+		{"IFT_QLLC", Const, 0},
+		{"IFT_RADIOMAC", Const, 0},
+		{"IFT_RADSL", Const, 0},
+		{"IFT_REACHDSL", Const, 0},
+		{"IFT_RFC1483", Const, 0},
+		{"IFT_RS232", Const, 0},
+		{"IFT_RSRB", Const, 0},
+		{"IFT_SDLC", Const, 0},
+		{"IFT_SDSL", Const, 0},
+		{"IFT_SHDSL", Const, 0},
+		{"IFT_SIP", Const, 0},
+		{"IFT_SIPSIG", Const, 1},
+		{"IFT_SIPTG", Const, 1},
+		{"IFT_SLIP", Const, 0},
+		{"IFT_SMDSDXI", Const, 0},
+		{"IFT_SMDSICIP", Const, 0},
+		{"IFT_SONET", Const, 0},
+		{"IFT_SONETOVERHEADCHANNEL", Const, 0},
+		{"IFT_SONETPATH", Const, 0},
+		{"IFT_SONETVT", Const, 0},
+		{"IFT_SRP", Const, 0},
+		{"IFT_SS7SIGLINK", Const, 0},
+		{"IFT_STACKTOSTACK", Const, 0},
+		{"IFT_STARLAN", Const, 0},
+		{"IFT_STF", Const, 0},
+		{"IFT_T1", Const, 0},
+		{"IFT_TDLC", Const, 0},
+		{"IFT_TELINK", Const, 1},
+		{"IFT_TERMPAD", Const, 0},
+		{"IFT_TR008", Const, 0},
+		{"IFT_TRANSPHDLC", Const, 0},
+		{"IFT_TUNNEL", Const, 0},
+		{"IFT_ULTRA", Const, 0},
+		{"IFT_USB", Const, 0},
+		{"IFT_V11", Const, 0},
+		{"IFT_V35", Const, 0},
+		{"IFT_V36", Const, 0},
+		{"IFT_V37", Const, 0},
+		{"IFT_VDSL", Const, 0},
+		{"IFT_VIRTUALIPADDRESS", Const, 0},
+		{"IFT_VIRTUALTG", Const, 1},
+		{"IFT_VOICEDID", Const, 1},
+		{"IFT_VOICEEM", Const, 0},
+		{"IFT_VOICEEMFGD", Const, 1},
+		{"IFT_VOICEENCAP", Const, 0},
+		{"IFT_VOICEFGDEANA", Const, 1},
+		{"IFT_VOICEFXO", Const, 0},
+		{"IFT_VOICEFXS", Const, 0},
+		{"IFT_VOICEOVERATM", Const, 0},
+		{"IFT_VOICEOVERCABLE", Const, 1},
+		{"IFT_VOICEOVERFRAMERELAY", Const, 0},
+		{"IFT_VOICEOVERIP", Const, 0},
+		{"IFT_X213", Const, 0},
+		{"IFT_X25", Const, 0},
+		{"IFT_X25DDN", Const, 0},
+		{"IFT_X25HUNTGROUP", Const, 0},
+		{"IFT_X25MLP", Const, 0},
+		{"IFT_X25PLE", Const, 0},
+		{"IFT_XETHER", Const, 0},
+		{"IGNBRK", Const, 0},
+		{"IGNCR", Const, 0},
+		{"IGNORE", Const, 0},
+		{"IGNPAR", Const, 0},
+		{"IMAXBEL", Const, 0},
+		{"INFINITE", Const, 0},
+		{"INLCR", Const, 0},
+		{"INPCK", Const, 0},
+		{"INVALID_FILE_ATTRIBUTES", Const, 0},
+		{"IN_ACCESS", Const, 0},
+		{"IN_ALL_EVENTS", Const, 0},
+		{"IN_ATTRIB", Const, 0},
+		{"IN_CLASSA_HOST", Const, 0},
+		{"IN_CLASSA_MAX", Const, 0},
+		{"IN_CLASSA_NET", Const, 0},
+		{"IN_CLASSA_NSHIFT", Const, 0},
+		{"IN_CLASSB_HOST", Const, 0},
+		{"IN_CLASSB_MAX", Const, 0},
+		{"IN_CLASSB_NET", Const, 0},
+		{"IN_CLASSB_NSHIFT", Const, 0},
+		{"IN_CLASSC_HOST", Const, 0},
+		{"IN_CLASSC_NET", Const, 0},
+		{"IN_CLASSC_NSHIFT", Const, 0},
+		{"IN_CLASSD_HOST", Const, 0},
+		{"IN_CLASSD_NET", Const, 0},
+		{"IN_CLASSD_NSHIFT", Const, 0},
+		{"IN_CLOEXEC", Const, 0},
+		{"IN_CLOSE", Const, 0},
+		{"IN_CLOSE_NOWRITE", Const, 0},
+		{"IN_CLOSE_WRITE", Const, 0},
+		{"IN_CREATE", Const, 0},
+		{"IN_DELETE", Const, 0},
+		{"IN_DELETE_SELF", Const, 0},
+		{"IN_DONT_FOLLOW", Const, 0},
+		{"IN_EXCL_UNLINK", Const, 0},
+		{"IN_IGNORED", Const, 0},
+		{"IN_ISDIR", Const, 0},
+		{"IN_LINKLOCALNETNUM", Const, 0},
+		{"IN_LOOPBACKNET", Const, 0},
+		{"IN_MASK_ADD", Const, 0},
+		{"IN_MODIFY", Const, 0},
+		{"IN_MOVE", Const, 0},
+		{"IN_MOVED_FROM", Const, 0},
+		{"IN_MOVED_TO", Const, 0},
+		{"IN_MOVE_SELF", Const, 0},
+		{"IN_NONBLOCK", Const, 0},
+		{"IN_ONESHOT", Const, 0},
+		{"IN_ONLYDIR", Const, 0},
+		{"IN_OPEN", Const, 0},
+		{"IN_Q_OVERFLOW", Const, 0},
+		{"IN_RFC3021_HOST", Const, 1},
+		{"IN_RFC3021_MASK", Const, 1},
+		{"IN_RFC3021_NET", Const, 1},
+		{"IN_RFC3021_NSHIFT", Const, 1},
+		{"IN_UNMOUNT", Const, 0},
+		{"IOC_IN", Const, 1},
+		{"IOC_INOUT", Const, 1},
+		{"IOC_OUT", Const, 1},
+		{"IOC_VENDOR", Const, 3},
+		{"IOC_WS2", Const, 1},
+		{"IO_REPARSE_TAG_SYMLINK", Const, 4},
+		{"IPMreq", Type, 0},
+		{"IPMreq.Interface", Field, 0},
+		{"IPMreq.Multiaddr", Field, 0},
+		{"IPMreqn", Type, 0},
+		{"IPMreqn.Address", Field, 0},
+		{"IPMreqn.Ifindex", Field, 0},
+		{"IPMreqn.Multiaddr", Field, 0},
+		{"IPPROTO_3PC", Const, 0},
+		{"IPPROTO_ADFS", Const, 0},
+		{"IPPROTO_AH", Const, 0},
+		{"IPPROTO_AHIP", Const, 0},
+		{"IPPROTO_APES", Const, 0},
+		{"IPPROTO_ARGUS", Const, 0},
+		{"IPPROTO_AX25", Const, 0},
+		{"IPPROTO_BHA", Const, 0},
+		{"IPPROTO_BLT", Const, 0},
+		{"IPPROTO_BRSATMON", Const, 0},
+		{"IPPROTO_CARP", Const, 0},
+		{"IPPROTO_CFTP", Const, 0},
+		{"IPPROTO_CHAOS", Const, 0},
+		{"IPPROTO_CMTP", Const, 0},
+		{"IPPROTO_COMP", Const, 0},
+		{"IPPROTO_CPHB", Const, 0},
+		{"IPPROTO_CPNX", Const, 0},
+		{"IPPROTO_DCCP", Const, 0},
+		{"IPPROTO_DDP", Const, 0},
+		{"IPPROTO_DGP", Const, 0},
+		{"IPPROTO_DIVERT", Const, 0},
+		{"IPPROTO_DIVERT_INIT", Const, 3},
+		{"IPPROTO_DIVERT_RESP", Const, 3},
+		{"IPPROTO_DONE", Const, 0},
+		{"IPPROTO_DSTOPTS", Const, 0},
+		{"IPPROTO_EGP", Const, 0},
+		{"IPPROTO_EMCON", Const, 0},
+		{"IPPROTO_ENCAP", Const, 0},
+		{"IPPROTO_EON", Const, 0},
+		{"IPPROTO_ESP", Const, 0},
+		{"IPPROTO_ETHERIP", Const, 0},
+		{"IPPROTO_FRAGMENT", Const, 0},
+		{"IPPROTO_GGP", Const, 0},
+		{"IPPROTO_GMTP", Const, 0},
+		{"IPPROTO_GRE", Const, 0},
+		{"IPPROTO_HELLO", Const, 0},
+		{"IPPROTO_HMP", Const, 0},
+		{"IPPROTO_HOPOPTS", Const, 0},
+		{"IPPROTO_ICMP", Const, 0},
+		{"IPPROTO_ICMPV6", Const, 0},
+		{"IPPROTO_IDP", Const, 0},
+		{"IPPROTO_IDPR", Const, 0},
+		{"IPPROTO_IDRP", Const, 0},
+		{"IPPROTO_IGMP", Const, 0},
+		{"IPPROTO_IGP", Const, 0},
+		{"IPPROTO_IGRP", Const, 0},
+		{"IPPROTO_IL", Const, 0},
+		{"IPPROTO_INLSP", Const, 0},
+		{"IPPROTO_INP", Const, 0},
+		{"IPPROTO_IP", Const, 0},
+		{"IPPROTO_IPCOMP", Const, 0},
+		{"IPPROTO_IPCV", Const, 0},
+		{"IPPROTO_IPEIP", Const, 0},
+		{"IPPROTO_IPIP", Const, 0},
+		{"IPPROTO_IPPC", Const, 0},
+		{"IPPROTO_IPV4", Const, 0},
+		{"IPPROTO_IPV6", Const, 0},
+		{"IPPROTO_IPV6_ICMP", Const, 1},
+		{"IPPROTO_IRTP", Const, 0},
+		{"IPPROTO_KRYPTOLAN", Const, 0},
+		{"IPPROTO_LARP", Const, 0},
+		{"IPPROTO_LEAF1", Const, 0},
+		{"IPPROTO_LEAF2", Const, 0},
+		{"IPPROTO_MAX", Const, 0},
+		{"IPPROTO_MAXID", Const, 0},
+		{"IPPROTO_MEAS", Const, 0},
+		{"IPPROTO_MH", Const, 1},
+		{"IPPROTO_MHRP", Const, 0},
+		{"IPPROTO_MICP", Const, 0},
+		{"IPPROTO_MOBILE", Const, 0},
+		{"IPPROTO_MPLS", Const, 1},
+		{"IPPROTO_MTP", Const, 0},
+		{"IPPROTO_MUX", Const, 0},
+		{"IPPROTO_ND", Const, 0},
+		{"IPPROTO_NHRP", Const, 0},
+		{"IPPROTO_NONE", Const, 0},
+		{"IPPROTO_NSP", Const, 0},
+		{"IPPROTO_NVPII", Const, 0},
+		{"IPPROTO_OLD_DIVERT", Const, 0},
+		{"IPPROTO_OSPFIGP", Const, 0},
+		{"IPPROTO_PFSYNC", Const, 0},
+		{"IPPROTO_PGM", Const, 0},
+		{"IPPROTO_PIGP", Const, 0},
+		{"IPPROTO_PIM", Const, 0},
+		{"IPPROTO_PRM", Const, 0},
+		{"IPPROTO_PUP", Const, 0},
+		{"IPPROTO_PVP", Const, 0},
+		{"IPPROTO_RAW", Const, 0},
+		{"IPPROTO_RCCMON", Const, 0},
+		{"IPPROTO_RDP", Const, 0},
+		{"IPPROTO_ROUTING", Const, 0},
+		{"IPPROTO_RSVP", Const, 0},
+		{"IPPROTO_RVD", Const, 0},
+		{"IPPROTO_SATEXPAK", Const, 0},
+		{"IPPROTO_SATMON", Const, 0},
+		{"IPPROTO_SCCSP", Const, 0},
+		{"IPPROTO_SCTP", Const, 0},
+		{"IPPROTO_SDRP", Const, 0},
+		{"IPPROTO_SEND", Const, 1},
+		{"IPPROTO_SEP", Const, 0},
+		{"IPPROTO_SKIP", Const, 0},
+		{"IPPROTO_SPACER", Const, 0},
+		{"IPPROTO_SRPC", Const, 0},
+		{"IPPROTO_ST", Const, 0},
+		{"IPPROTO_SVMTP", Const, 0},
+		{"IPPROTO_SWIPE", Const, 0},
+		{"IPPROTO_TCF", Const, 0},
+		{"IPPROTO_TCP", Const, 0},
+		{"IPPROTO_TLSP", Const, 0},
+		{"IPPROTO_TP", Const, 0},
+		{"IPPROTO_TPXX", Const, 0},
+		{"IPPROTO_TRUNK1", Const, 0},
+		{"IPPROTO_TRUNK2", Const, 0},
+		{"IPPROTO_TTP", Const, 0},
+		{"IPPROTO_UDP", Const, 0},
+		{"IPPROTO_UDPLITE", Const, 0},
+		{"IPPROTO_VINES", Const, 0},
+		{"IPPROTO_VISA", Const, 0},
+		{"IPPROTO_VMTP", Const, 0},
+		{"IPPROTO_VRRP", Const, 1},
+		{"IPPROTO_WBEXPAK", Const, 0},
+		{"IPPROTO_WBMON", Const, 0},
+		{"IPPROTO_WSN", Const, 0},
+		{"IPPROTO_XNET", Const, 0},
+		{"IPPROTO_XTP", Const, 0},
+		{"IPV6_2292DSTOPTS", Const, 0},
+		{"IPV6_2292HOPLIMIT", Const, 0},
+		{"IPV6_2292HOPOPTS", Const, 0},
+		{"IPV6_2292NEXTHOP", Const, 0},
+		{"IPV6_2292PKTINFO", Const, 0},
+		{"IPV6_2292PKTOPTIONS", Const, 0},
+		{"IPV6_2292RTHDR", Const, 0},
+		{"IPV6_ADDRFORM", Const, 0},
+		{"IPV6_ADD_MEMBERSHIP", Const, 0},
+		{"IPV6_AUTHHDR", Const, 0},
+		{"IPV6_AUTH_LEVEL", Const, 1},
+		{"IPV6_AUTOFLOWLABEL", Const, 0},
+		{"IPV6_BINDANY", Const, 0},
+		{"IPV6_BINDV6ONLY", Const, 0},
+		{"IPV6_BOUND_IF", Const, 0},
+		{"IPV6_CHECKSUM", Const, 0},
+		{"IPV6_DEFAULT_MULTICAST_HOPS", Const, 0},
+		{"IPV6_DEFAULT_MULTICAST_LOOP", Const, 0},
+		{"IPV6_DEFHLIM", Const, 0},
+		{"IPV6_DONTFRAG", Const, 0},
+		{"IPV6_DROP_MEMBERSHIP", Const, 0},
+		{"IPV6_DSTOPTS", Const, 0},
+		{"IPV6_ESP_NETWORK_LEVEL", Const, 1},
+		{"IPV6_ESP_TRANS_LEVEL", Const, 1},
+		{"IPV6_FAITH", Const, 0},
+		{"IPV6_FLOWINFO_MASK", Const, 0},
+		{"IPV6_FLOWLABEL_MASK", Const, 0},
+		{"IPV6_FRAGTTL", Const, 0},
+		{"IPV6_FW_ADD", Const, 0},
+		{"IPV6_FW_DEL", Const, 0},
+		{"IPV6_FW_FLUSH", Const, 0},
+		{"IPV6_FW_GET", Const, 0},
+		{"IPV6_FW_ZERO", Const, 0},
+		{"IPV6_HLIMDEC", Const, 0},
+		{"IPV6_HOPLIMIT", Const, 0},
+		{"IPV6_HOPOPTS", Const, 0},
+		{"IPV6_IPCOMP_LEVEL", Const, 1},
+		{"IPV6_IPSEC_POLICY", Const, 0},
+		{"IPV6_JOIN_ANYCAST", Const, 0},
+		{"IPV6_JOIN_GROUP", Const, 0},
+		{"IPV6_LEAVE_ANYCAST", Const, 0},
+		{"IPV6_LEAVE_GROUP", Const, 0},
+		{"IPV6_MAXHLIM", Const, 0},
+		{"IPV6_MAXOPTHDR", Const, 0},
+		{"IPV6_MAXPACKET", Const, 0},
+		{"IPV6_MAX_GROUP_SRC_FILTER", Const, 0},
+		{"IPV6_MAX_MEMBERSHIPS", Const, 0},
+		{"IPV6_MAX_SOCK_SRC_FILTER", Const, 0},
+		{"IPV6_MIN_MEMBERSHIPS", Const, 0},
+		{"IPV6_MMTU", Const, 0},
+		{"IPV6_MSFILTER", Const, 0},
+		{"IPV6_MTU", Const, 0},
+		{"IPV6_MTU_DISCOVER", Const, 0},
+		{"IPV6_MULTICAST_HOPS", Const, 0},
+		{"IPV6_MULTICAST_IF", Const, 0},
+		{"IPV6_MULTICAST_LOOP", Const, 0},
+		{"IPV6_NEXTHOP", Const, 0},
+		{"IPV6_OPTIONS", Const, 1},
+		{"IPV6_PATHMTU", Const, 0},
+		{"IPV6_PIPEX", Const, 1},
+		{"IPV6_PKTINFO", Const, 0},
+		{"IPV6_PMTUDISC_DO", Const, 0},
+		{"IPV6_PMTUDISC_DONT", Const, 0},
+		{"IPV6_PMTUDISC_PROBE", Const, 0},
+		{"IPV6_PMTUDISC_WANT", Const, 0},
+		{"IPV6_PORTRANGE", Const, 0},
+		{"IPV6_PORTRANGE_DEFAULT", Const, 0},
+		{"IPV6_PORTRANGE_HIGH", Const, 0},
+		{"IPV6_PORTRANGE_LOW", Const, 0},
+		{"IPV6_PREFER_TEMPADDR", Const, 0},
+		{"IPV6_RECVDSTOPTS", Const, 0},
+		{"IPV6_RECVDSTPORT", Const, 3},
+		{"IPV6_RECVERR", Const, 0},
+		{"IPV6_RECVHOPLIMIT", Const, 0},
+		{"IPV6_RECVHOPOPTS", Const, 0},
+		{"IPV6_RECVPATHMTU", Const, 0},
+		{"IPV6_RECVPKTINFO", Const, 0},
+		{"IPV6_RECVRTHDR", Const, 0},
+		{"IPV6_RECVTCLASS", Const, 0},
+		{"IPV6_ROUTER_ALERT", Const, 0},
+		{"IPV6_RTABLE", Const, 1},
+		{"IPV6_RTHDR", Const, 0},
+		{"IPV6_RTHDRDSTOPTS", Const, 0},
+		{"IPV6_RTHDR_LOOSE", Const, 0},
+		{"IPV6_RTHDR_STRICT", Const, 0},
+		{"IPV6_RTHDR_TYPE_0", Const, 0},
+		{"IPV6_RXDSTOPTS", Const, 0},
+		{"IPV6_RXHOPOPTS", Const, 0},
+		{"IPV6_SOCKOPT_RESERVED1", Const, 0},
+		{"IPV6_TCLASS", Const, 0},
+		{"IPV6_UNICAST_HOPS", Const, 0},
+		{"IPV6_USE_MIN_MTU", Const, 0},
+		{"IPV6_V6ONLY", Const, 0},
+		{"IPV6_VERSION", Const, 0},
+		{"IPV6_VERSION_MASK", Const, 0},
+		{"IPV6_XFRM_POLICY", Const, 0},
+		{"IP_ADD_MEMBERSHIP", Const, 0},
+		{"IP_ADD_SOURCE_MEMBERSHIP", Const, 0},
+		{"IP_AUTH_LEVEL", Const, 1},
+		{"IP_BINDANY", Const, 0},
+		{"IP_BLOCK_SOURCE", Const, 0},
+		{"IP_BOUND_IF", Const, 0},
+		{"IP_DEFAULT_MULTICAST_LOOP", Const, 0},
+		{"IP_DEFAULT_MULTICAST_TTL", Const, 0},
+		{"IP_DF", Const, 0},
+		{"IP_DIVERTFL", Const, 3},
+		{"IP_DONTFRAG", Const, 0},
+		{"IP_DROP_MEMBERSHIP", Const, 0},
+		{"IP_DROP_SOURCE_MEMBERSHIP", Const, 0},
+		{"IP_DUMMYNET3", Const, 0},
+		{"IP_DUMMYNET_CONFIGURE", Const, 0},
+		{"IP_DUMMYNET_DEL", Const, 0},
+		{"IP_DUMMYNET_FLUSH", Const, 0},
+		{"IP_DUMMYNET_GET", Const, 0},
+		{"IP_EF", Const, 1},
+		{"IP_ERRORMTU", Const, 1},
+		{"IP_ESP_NETWORK_LEVEL", Const, 1},
+		{"IP_ESP_TRANS_LEVEL", Const, 1},
+		{"IP_FAITH", Const, 0},
+		{"IP_FREEBIND", Const, 0},
+		{"IP_FW3", Const, 0},
+		{"IP_FW_ADD", Const, 0},
+		{"IP_FW_DEL", Const, 0},
+		{"IP_FW_FLUSH", Const, 0},
+		{"IP_FW_GET", Const, 0},
+		{"IP_FW_NAT_CFG", Const, 0},
+		{"IP_FW_NAT_DEL", Const, 0},
+		{"IP_FW_NAT_GET_CONFIG", Const, 0},
+		{"IP_FW_NAT_GET_LOG", Const, 0},
+		{"IP_FW_RESETLOG", Const, 0},
+		{"IP_FW_TABLE_ADD", Const, 0},
+		{"IP_FW_TABLE_DEL", Const, 0},
+		{"IP_FW_TABLE_FLUSH", Const, 0},
+		{"IP_FW_TABLE_GETSIZE", Const, 0},
+		{"IP_FW_TABLE_LIST", Const, 0},
+		{"IP_FW_ZERO", Const, 0},
+		{"IP_HDRINCL", Const, 0},
+		{"IP_IPCOMP_LEVEL", Const, 1},
+		{"IP_IPSECFLOWINFO", Const, 1},
+		{"IP_IPSEC_LOCAL_AUTH", Const, 1},
+		{"IP_IPSEC_LOCAL_CRED", Const, 1},
+		{"IP_IPSEC_LOCAL_ID", Const, 1},
+		{"IP_IPSEC_POLICY", Const, 0},
+		{"IP_IPSEC_REMOTE_AUTH", Const, 1},
+		{"IP_IPSEC_REMOTE_CRED", Const, 1},
+		{"IP_IPSEC_REMOTE_ID", Const, 1},
+		{"IP_MAXPACKET", Const, 0},
+		{"IP_MAX_GROUP_SRC_FILTER", Const, 0},
+		{"IP_MAX_MEMBERSHIPS", Const, 0},
+		{"IP_MAX_SOCK_MUTE_FILTER", Const, 0},
+		{"IP_MAX_SOCK_SRC_FILTER", Const, 0},
+		{"IP_MAX_SOURCE_FILTER", Const, 0},
+		{"IP_MF", Const, 0},
+		{"IP_MINFRAGSIZE", Const, 1},
+		{"IP_MINTTL", Const, 0},
+		{"IP_MIN_MEMBERSHIPS", Const, 0},
+		{"IP_MSFILTER", Const, 0},
+		{"IP_MSS", Const, 0},
+		{"IP_MTU", Const, 0},
+		{"IP_MTU_DISCOVER", Const, 0},
+		{"IP_MULTICAST_IF", Const, 0},
+		{"IP_MULTICAST_IFINDEX", Const, 0},
+		{"IP_MULTICAST_LOOP", Const, 0},
+		{"IP_MULTICAST_TTL", Const, 0},
+		{"IP_MULTICAST_VIF", Const, 0},
+		{"IP_NAT__XXX", Const, 0},
+		{"IP_OFFMASK", Const, 0},
+		{"IP_OLD_FW_ADD", Const, 0},
+		{"IP_OLD_FW_DEL", Const, 0},
+		{"IP_OLD_FW_FLUSH", Const, 0},
+		{"IP_OLD_FW_GET", Const, 0},
+		{"IP_OLD_FW_RESETLOG", Const, 0},
+		{"IP_OLD_FW_ZERO", Const, 0},
+		{"IP_ONESBCAST", Const, 0},
+		{"IP_OPTIONS", Const, 0},
+		{"IP_ORIGDSTADDR", Const, 0},
+		{"IP_PASSSEC", Const, 0},
+		{"IP_PIPEX", Const, 1},
+		{"IP_PKTINFO", Const, 0},
+		{"IP_PKTOPTIONS", Const, 0},
+		{"IP_PMTUDISC", Const, 0},
+		{"IP_PMTUDISC_DO", Const, 0},
+		{"IP_PMTUDISC_DONT", Const, 0},
+		{"IP_PMTUDISC_PROBE", Const, 0},
+		{"IP_PMTUDISC_WANT", Const, 0},
+		{"IP_PORTRANGE", Const, 0},
+		{"IP_PORTRANGE_DEFAULT", Const, 0},
+		{"IP_PORTRANGE_HIGH", Const, 0},
+		{"IP_PORTRANGE_LOW", Const, 0},
+		{"IP_RECVDSTADDR", Const, 0},
+		{"IP_RECVDSTPORT", Const, 1},
+		{"IP_RECVERR", Const, 0},
+		{"IP_RECVIF", Const, 0},
+		{"IP_RECVOPTS", Const, 0},
+		{"IP_RECVORIGDSTADDR", Const, 0},
+		{"IP_RECVPKTINFO", Const, 0},
+		{"IP_RECVRETOPTS", Const, 0},
+		{"IP_RECVRTABLE", Const, 1},
+		{"IP_RECVTOS", Const, 0},
+		{"IP_RECVTTL", Const, 0},
+		{"IP_RETOPTS", Const, 0},
+		{"IP_RF", Const, 0},
+		{"IP_ROUTER_ALERT", Const, 0},
+		{"IP_RSVP_OFF", Const, 0},
+		{"IP_RSVP_ON", Const, 0},
+		{"IP_RSVP_VIF_OFF", Const, 0},
+		{"IP_RSVP_VIF_ON", Const, 0},
+		{"IP_RTABLE", Const, 1},
+		{"IP_SENDSRCADDR", Const, 0},
+		{"IP_STRIPHDR", Const, 0},
+		{"IP_TOS", Const, 0},
+		{"IP_TRAFFIC_MGT_BACKGROUND", Const, 0},
+		{"IP_TRANSPARENT", Const, 0},
+		{"IP_TTL", Const, 0},
+		{"IP_UNBLOCK_SOURCE", Const, 0},
+		{"IP_XFRM_POLICY", Const, 0},
+		{"IPv6MTUInfo", Type, 2},
+		{"IPv6MTUInfo.Addr", Field, 2},
+		{"IPv6MTUInfo.Mtu", Field, 2},
+		{"IPv6Mreq", Type, 0},
+		{"IPv6Mreq.Interface", Field, 0},
+		{"IPv6Mreq.Multiaddr", Field, 0},
+		{"ISIG", Const, 0},
+		{"ISTRIP", Const, 0},
+		{"IUCLC", Const, 0},
+		{"IUTF8", Const, 0},
+		{"IXANY", Const, 0},
+		{"IXOFF", Const, 0},
+		{"IXON", Const, 0},
+		{"IfAddrmsg", Type, 0},
+		{"IfAddrmsg.Family", Field, 0},
+		{"IfAddrmsg.Flags", Field, 0},
+		{"IfAddrmsg.Index", Field, 0},
+		{"IfAddrmsg.Prefixlen", Field, 0},
+		{"IfAddrmsg.Scope", Field, 0},
+		{"IfAnnounceMsghdr", Type, 1},
+		{"IfAnnounceMsghdr.Hdrlen", Field, 2},
+		{"IfAnnounceMsghdr.Index", Field, 1},
+		{"IfAnnounceMsghdr.Msglen", Field, 1},
+		{"IfAnnounceMsghdr.Name", Field, 1},
+		{"IfAnnounceMsghdr.Type", Field, 1},
+		{"IfAnnounceMsghdr.Version", Field, 1},
+		{"IfAnnounceMsghdr.What", Field, 1},
+		{"IfData", Type, 0},
+		{"IfData.Addrlen", Field, 0},
+		{"IfData.Baudrate", Field, 0},
+		{"IfData.Capabilities", Field, 2},
+		{"IfData.Collisions", Field, 0},
+		{"IfData.Datalen", Field, 0},
+		{"IfData.Epoch", Field, 0},
+		{"IfData.Hdrlen", Field, 0},
+		{"IfData.Hwassist", Field, 0},
+		{"IfData.Ibytes", Field, 0},
+		{"IfData.Ierrors", Field, 0},
+		{"IfData.Imcasts", Field, 0},
+		{"IfData.Ipackets", Field, 0},
+		{"IfData.Iqdrops", Field, 0},
+		{"IfData.Lastchange", Field, 0},
+		{"IfData.Link_state", Field, 0},
+		{"IfData.Mclpool", Field, 2},
+		{"IfData.Metric", Field, 0},
+		{"IfData.Mtu", Field, 0},
+		{"IfData.Noproto", Field, 0},
+		{"IfData.Obytes", Field, 0},
+		{"IfData.Oerrors", Field, 0},
+		{"IfData.Omcasts", Field, 0},
+		{"IfData.Opackets", Field, 0},
+		{"IfData.Pad", Field, 2},
+		{"IfData.Pad_cgo_0", Field, 2},
+		{"IfData.Pad_cgo_1", Field, 2},
+		{"IfData.Physical", Field, 0},
+		{"IfData.Recvquota", Field, 0},
+		{"IfData.Recvtiming", Field, 0},
+		{"IfData.Reserved1", Field, 0},
+		{"IfData.Reserved2", Field, 0},
+		{"IfData.Spare_char1", Field, 0},
+		{"IfData.Spare_char2", Field, 0},
+		{"IfData.Type", Field, 0},
+		{"IfData.Typelen", Field, 0},
+		{"IfData.Unused1", Field, 0},
+		{"IfData.Unused2", Field, 0},
+		{"IfData.Xmitquota", Field, 0},
+		{"IfData.Xmittiming", Field, 0},
+		{"IfInfomsg", Type, 0},
+		{"IfInfomsg.Change", Field, 0},
+		{"IfInfomsg.Family", Field, 0},
+		{"IfInfomsg.Flags", Field, 0},
+		{"IfInfomsg.Index", Field, 0},
+		{"IfInfomsg.Type", Field, 0},
+		{"IfInfomsg.X__ifi_pad", Field, 0},
+		{"IfMsghdr", Type, 0},
+		{"IfMsghdr.Addrs", Field, 0},
+		{"IfMsghdr.Data", Field, 0},
+		{"IfMsghdr.Flags", Field, 0},
+		{"IfMsghdr.Hdrlen", Field, 2},
+		{"IfMsghdr.Index", Field, 0},
+		{"IfMsghdr.Msglen", Field, 0},
+		{"IfMsghdr.Pad1", Field, 2},
+		{"IfMsghdr.Pad2", Field, 2},
+		{"IfMsghdr.Pad_cgo_0", Field, 0},
+		{"IfMsghdr.Pad_cgo_1", Field, 2},
+		{"IfMsghdr.Tableid", Field, 2},
+		{"IfMsghdr.Type", Field, 0},
+		{"IfMsghdr.Version", Field, 0},
+		{"IfMsghdr.Xflags", Field, 2},
+		{"IfaMsghdr", Type, 0},
+		{"IfaMsghdr.Addrs", Field, 0},
+		{"IfaMsghdr.Flags", Field, 0},
+		{"IfaMsghdr.Hdrlen", Field, 2},
+		{"IfaMsghdr.Index", Field, 0},
+		{"IfaMsghdr.Metric", Field, 0},
+		{"IfaMsghdr.Msglen", Field, 0},
+		{"IfaMsghdr.Pad1", Field, 2},
+		{"IfaMsghdr.Pad2", Field, 2},
+		{"IfaMsghdr.Pad_cgo_0", Field, 0},
+		{"IfaMsghdr.Tableid", Field, 2},
+		{"IfaMsghdr.Type", Field, 0},
+		{"IfaMsghdr.Version", Field, 0},
+		{"IfmaMsghdr", Type, 0},
+		{"IfmaMsghdr.Addrs", Field, 0},
+		{"IfmaMsghdr.Flags", Field, 0},
+		{"IfmaMsghdr.Index", Field, 0},
+		{"IfmaMsghdr.Msglen", Field, 0},
+		{"IfmaMsghdr.Pad_cgo_0", Field, 0},
+		{"IfmaMsghdr.Type", Field, 0},
+		{"IfmaMsghdr.Version", Field, 0},
+		{"IfmaMsghdr2", Type, 0},
+		{"IfmaMsghdr2.Addrs", Field, 0},
+		{"IfmaMsghdr2.Flags", Field, 0},
+		{"IfmaMsghdr2.Index", Field, 0},
+		{"IfmaMsghdr2.Msglen", Field, 0},
+		{"IfmaMsghdr2.Pad_cgo_0", Field, 0},
+		{"IfmaMsghdr2.Refcount", Field, 0},
+		{"IfmaMsghdr2.Type", Field, 0},
+		{"IfmaMsghdr2.Version", Field, 0},
+		{"ImplementsGetwd", Const, 0},
+		{"Inet4Pktinfo", Type, 0},
+		{"Inet4Pktinfo.Addr", Field, 0},
+		{"Inet4Pktinfo.Ifindex", Field, 0},
+		{"Inet4Pktinfo.Spec_dst", Field, 0},
+		{"Inet6Pktinfo", Type, 0},
+		{"Inet6Pktinfo.Addr", Field, 0},
+		{"Inet6Pktinfo.Ifindex", Field, 0},
+		{"InotifyAddWatch", Func, 0},
+		{"InotifyEvent", Type, 0},
+		{"InotifyEvent.Cookie", Field, 0},
+		{"InotifyEvent.Len", Field, 0},
+		{"InotifyEvent.Mask", Field, 0},
+		{"InotifyEvent.Name", Field, 0},
+		{"InotifyEvent.Wd", Field, 0},
+		{"InotifyInit", Func, 0},
+		{"InotifyInit1", Func, 0},
+		{"InotifyRmWatch", Func, 0},
+		{"InterfaceAddrMessage", Type, 0},
+		{"InterfaceAddrMessage.Data", Field, 0},
+		{"InterfaceAddrMessage.Header", Field, 0},
+		{"InterfaceAnnounceMessage", Type, 1},
+		{"InterfaceAnnounceMessage.Header", Field, 1},
+		{"InterfaceInfo", Type, 0},
+		{"InterfaceInfo.Address", Field, 0},
+		{"InterfaceInfo.BroadcastAddress", Field, 0},
+		{"InterfaceInfo.Flags", Field, 0},
+		{"InterfaceInfo.Netmask", Field, 0},
+		{"InterfaceMessage", Type, 0},
+		{"InterfaceMessage.Data", Field, 0},
+		{"InterfaceMessage.Header", Field, 0},
+		{"InterfaceMulticastAddrMessage", Type, 0},
+		{"InterfaceMulticastAddrMessage.Data", Field, 0},
+		{"InterfaceMulticastAddrMessage.Header", Field, 0},
+		{"InvalidHandle", Const, 0},
+		{"Ioperm", Func, 0},
+		{"Iopl", Func, 0},
+		{"Iovec", Type, 0},
+		{"Iovec.Base", Field, 0},
+		{"Iovec.Len", Field, 0},
+		{"IpAdapterInfo", Type, 0},
+		{"IpAdapterInfo.AdapterName", Field, 0},
+		{"IpAdapterInfo.Address", Field, 0},
+		{"IpAdapterInfo.AddressLength", Field, 0},
+		{"IpAdapterInfo.ComboIndex", Field, 0},
+		{"IpAdapterInfo.CurrentIpAddress", Field, 0},
+		{"IpAdapterInfo.Description", Field, 0},
+		{"IpAdapterInfo.DhcpEnabled", Field, 0},
+		{"IpAdapterInfo.DhcpServer", Field, 0},
+		{"IpAdapterInfo.GatewayList", Field, 0},
+		{"IpAdapterInfo.HaveWins", Field, 0},
+		{"IpAdapterInfo.Index", Field, 0},
+		{"IpAdapterInfo.IpAddressList", Field, 0},
+		{"IpAdapterInfo.LeaseExpires", Field, 0},
+		{"IpAdapterInfo.LeaseObtained", Field, 0},
+		{"IpAdapterInfo.Next", Field, 0},
+		{"IpAdapterInfo.PrimaryWinsServer", Field, 0},
+		{"IpAdapterInfo.SecondaryWinsServer", Field, 0},
+		{"IpAdapterInfo.Type", Field, 0},
+		{"IpAddrString", Type, 0},
+		{"IpAddrString.Context", Field, 0},
+		{"IpAddrString.IpAddress", Field, 0},
+		{"IpAddrString.IpMask", Field, 0},
+		{"IpAddrString.Next", Field, 0},
+		{"IpAddressString", Type, 0},
+		{"IpAddressString.String", Field, 0},
+		{"IpMaskString", Type, 0},
+		{"IpMaskString.String", Field, 2},
+		{"Issetugid", Func, 0},
+		{"KEY_ALL_ACCESS", Const, 0},
+		{"KEY_CREATE_LINK", Const, 0},
+		{"KEY_CREATE_SUB_KEY", Const, 0},
+		{"KEY_ENUMERATE_SUB_KEYS", Const, 0},
+		{"KEY_EXECUTE", Const, 0},
+		{"KEY_NOTIFY", Const, 0},
+		{"KEY_QUERY_VALUE", Const, 0},
+		{"KEY_READ", Const, 0},
+		{"KEY_SET_VALUE", Const, 0},
+		{"KEY_WOW64_32KEY", Const, 0},
+		{"KEY_WOW64_64KEY", Const, 0},
+		{"KEY_WRITE", Const, 0},
+		{"Kevent", Func, 0},
+		{"Kevent_t", Type, 0},
+		{"Kevent_t.Data", Field, 0},
+		{"Kevent_t.Fflags", Field, 0},
+		{"Kevent_t.Filter", Field, 0},
+		{"Kevent_t.Flags", Field, 0},
+		{"Kevent_t.Ident", Field, 0},
+		{"Kevent_t.Pad_cgo_0", Field, 2},
+		{"Kevent_t.Udata", Field, 0},
+		{"Kill", Func, 0},
+		{"Klogctl", Func, 0},
+		{"Kqueue", Func, 0},
+		{"LANG_ENGLISH", Const, 0},
+		{"LAYERED_PROTOCOL", Const, 2},
+		{"LCNT_OVERLOAD_FLUSH", Const, 1},
+		{"LINUX_REBOOT_CMD_CAD_OFF", Const, 0},
+		{"LINUX_REBOOT_CMD_CAD_ON", Const, 0},
+		{"LINUX_REBOOT_CMD_HALT", Const, 0},
+		{"LINUX_REBOOT_CMD_KEXEC", Const, 0},
+		{"LINUX_REBOOT_CMD_POWER_OFF", Const, 0},
+		{"LINUX_REBOOT_CMD_RESTART", Const, 0},
+		{"LINUX_REBOOT_CMD_RESTART2", Const, 0},
+		{"LINUX_REBOOT_CMD_SW_SUSPEND", Const, 0},
+		{"LINUX_REBOOT_MAGIC1", Const, 0},
+		{"LINUX_REBOOT_MAGIC2", Const, 0},
+		{"LOCK_EX", Const, 0},
+		{"LOCK_NB", Const, 0},
+		{"LOCK_SH", Const, 0},
+		{"LOCK_UN", Const, 0},
+		{"LazyDLL", Type, 0},
+		{"LazyDLL.Name", Field, 0},
+		{"LazyProc", Type, 0},
+		{"LazyProc.Name", Field, 0},
+		{"Lchown", Func, 0},
+		{"Linger", Type, 0},
+		{"Linger.Linger", Field, 0},
+		{"Linger.Onoff", Field, 0},
+		{"Link", Func, 0},
+		{"Listen", Func, 0},
+		{"Listxattr", Func, 1},
+		{"LoadCancelIoEx", Func, 1},
+		{"LoadConnectEx", Func, 1},
+		{"LoadCreateSymbolicLink", Func, 4},
+		{"LoadDLL", Func, 0},
+		{"LoadGetAddrInfo", Func, 1},
+		{"LoadLibrary", Func, 0},
+		{"LoadSetFileCompletionNotificationModes", Func, 2},
+		{"LocalFree", Func, 0},
+		{"Log2phys_t", Type, 0},
+		{"Log2phys_t.Contigbytes", Field, 0},
+		{"Log2phys_t.Devoffset", Field, 0},
+		{"Log2phys_t.Flags", Field, 0},
+		{"LookupAccountName", Func, 0},
+		{"LookupAccountSid", Func, 0},
+		{"LookupSID", Func, 0},
+		{"LsfJump", Func, 0},
+		{"LsfSocket", Func, 0},
+		{"LsfStmt", Func, 0},
+		{"Lstat", Func, 0},
+		{"MADV_AUTOSYNC", Const, 1},
+		{"MADV_CAN_REUSE", Const, 0},
+		{"MADV_CORE", Const, 1},
+		{"MADV_DOFORK", Const, 0},
+		{"MADV_DONTFORK", Const, 0},
+		{"MADV_DONTNEED", Const, 0},
+		{"MADV_FREE", Const, 0},
+		{"MADV_FREE_REUSABLE", Const, 0},
+		{"MADV_FREE_REUSE", Const, 0},
+		{"MADV_HUGEPAGE", Const, 0},
+		{"MADV_HWPOISON", Const, 0},
+		{"MADV_MERGEABLE", Const, 0},
+		{"MADV_NOCORE", Const, 1},
+		{"MADV_NOHUGEPAGE", Const, 0},
+		{"MADV_NORMAL", Const, 0},
+		{"MADV_NOSYNC", Const, 1},
+		{"MADV_PROTECT", Const, 1},
+		{"MADV_RANDOM", Const, 0},
+		{"MADV_REMOVE", Const, 0},
+		{"MADV_SEQUENTIAL", Const, 0},
+		{"MADV_SPACEAVAIL", Const, 3},
+		{"MADV_UNMERGEABLE", Const, 0},
+		{"MADV_WILLNEED", Const, 0},
+		{"MADV_ZERO_WIRED_PAGES", Const, 0},
+		{"MAP_32BIT", Const, 0},
+		{"MAP_ALIGNED_SUPER", Const, 3},
+		{"MAP_ALIGNMENT_16MB", Const, 3},
+		{"MAP_ALIGNMENT_1TB", Const, 3},
+		{"MAP_ALIGNMENT_256TB", Const, 3},
+		{"MAP_ALIGNMENT_4GB", Const, 3},
+		{"MAP_ALIGNMENT_64KB", Const, 3},
+		{"MAP_ALIGNMENT_64PB", Const, 3},
+		{"MAP_ALIGNMENT_MASK", Const, 3},
+		{"MAP_ALIGNMENT_SHIFT", Const, 3},
+		{"MAP_ANON", Const, 0},
+		{"MAP_ANONYMOUS", Const, 0},
+		{"MAP_COPY", Const, 0},
+		{"MAP_DENYWRITE", Const, 0},
+		{"MAP_EXECUTABLE", Const, 0},
+		{"MAP_FILE", Const, 0},
+		{"MAP_FIXED", Const, 0},
+		{"MAP_FLAGMASK", Const, 3},
+		{"MAP_GROWSDOWN", Const, 0},
+		{"MAP_HASSEMAPHORE", Const, 0},
+		{"MAP_HUGETLB", Const, 0},
+		{"MAP_INHERIT", Const, 3},
+		{"MAP_INHERIT_COPY", Const, 3},
+		{"MAP_INHERIT_DEFAULT", Const, 3},
+		{"MAP_INHERIT_DONATE_COPY", Const, 3},
+		{"MAP_INHERIT_NONE", Const, 3},
+		{"MAP_INHERIT_SHARE", Const, 3},
+		{"MAP_JIT", Const, 0},
+		{"MAP_LOCKED", Const, 0},
+		{"MAP_NOCACHE", Const, 0},
+		{"MAP_NOCORE", Const, 1},
+		{"MAP_NOEXTEND", Const, 0},
+		{"MAP_NONBLOCK", Const, 0},
+		{"MAP_NORESERVE", Const, 0},
+		{"MAP_NOSYNC", Const, 1},
+		{"MAP_POPULATE", Const, 0},
+		{"MAP_PREFAULT_READ", Const, 1},
+		{"MAP_PRIVATE", Const, 0},
+		{"MAP_RENAME", Const, 0},
+		{"MAP_RESERVED0080", Const, 0},
+		{"MAP_RESERVED0100", Const, 1},
+		{"MAP_SHARED", Const, 0},
+		{"MAP_STACK", Const, 0},
+		{"MAP_TRYFIXED", Const, 3},
+		{"MAP_TYPE", Const, 0},
+		{"MAP_WIRED", Const, 3},
+		{"MAXIMUM_REPARSE_DATA_BUFFER_SIZE", Const, 4},
+		{"MAXLEN_IFDESCR", Const, 0},
+		{"MAXLEN_PHYSADDR", Const, 0},
+		{"MAX_ADAPTER_ADDRESS_LENGTH", Const, 0},
+		{"MAX_ADAPTER_DESCRIPTION_LENGTH", Const, 0},
+		{"MAX_ADAPTER_NAME_LENGTH", Const, 0},
+		{"MAX_COMPUTERNAME_LENGTH", Const, 0},
+		{"MAX_INTERFACE_NAME_LEN", Const, 0},
+		{"MAX_LONG_PATH", Const, 0},
+		{"MAX_PATH", Const, 0},
+		{"MAX_PROTOCOL_CHAIN", Const, 2},
+		{"MCL_CURRENT", Const, 0},
+		{"MCL_FUTURE", Const, 0},
+		{"MNT_DETACH", Const, 0},
+		{"MNT_EXPIRE", Const, 0},
+		{"MNT_FORCE", Const, 0},
+		{"MSG_BCAST", Const, 1},
+		{"MSG_CMSG_CLOEXEC", Const, 0},
+		{"MSG_COMPAT", Const, 0},
+		{"MSG_CONFIRM", Const, 0},
+		{"MSG_CONTROLMBUF", Const, 1},
+		{"MSG_CTRUNC", Const, 0},
+		{"MSG_DONTROUTE", Const, 0},
+		{"MSG_DONTWAIT", Const, 0},
+		{"MSG_EOF", Const, 0},
+		{"MSG_EOR", Const, 0},
+		{"MSG_ERRQUEUE", Const, 0},
+		{"MSG_FASTOPEN", Const, 1},
+		{"MSG_FIN", Const, 0},
+		{"MSG_FLUSH", Const, 0},
+		{"MSG_HAVEMORE", Const, 0},
+		{"MSG_HOLD", Const, 0},
+		{"MSG_IOVUSRSPACE", Const, 1},
+		{"MSG_LENUSRSPACE", Const, 1},
+		{"MSG_MCAST", Const, 1},
+		{"MSG_MORE", Const, 0},
+		{"MSG_NAMEMBUF", Const, 1},
+		{"MSG_NBIO", Const, 0},
+		{"MSG_NEEDSA", Const, 0},
+		{"MSG_NOSIGNAL", Const, 0},
+		{"MSG_NOTIFICATION", Const, 0},
+		{"MSG_OOB", Const, 0},
+		{"MSG_PEEK", Const, 0},
+		{"MSG_PROXY", Const, 0},
+		{"MSG_RCVMORE", Const, 0},
+		{"MSG_RST", Const, 0},
+		{"MSG_SEND", Const, 0},
+		{"MSG_SYN", Const, 0},
+		{"MSG_TRUNC", Const, 0},
+		{"MSG_TRYHARD", Const, 0},
+		{"MSG_USERFLAGS", Const, 1},
+		{"MSG_WAITALL", Const, 0},
+		{"MSG_WAITFORONE", Const, 0},
+		{"MSG_WAITSTREAM", Const, 0},
+		{"MS_ACTIVE", Const, 0},
+		{"MS_ASYNC", Const, 0},
+		{"MS_BIND", Const, 0},
+		{"MS_DEACTIVATE", Const, 0},
+		{"MS_DIRSYNC", Const, 0},
+		{"MS_INVALIDATE", Const, 0},
+		{"MS_I_VERSION", Const, 0},
+		{"MS_KERNMOUNT", Const, 0},
+		{"MS_KILLPAGES", Const, 0},
+		{"MS_MANDLOCK", Const, 0},
+		{"MS_MGC_MSK", Const, 0},
+		{"MS_MGC_VAL", Const, 0},
+		{"MS_MOVE", Const, 0},
+		{"MS_NOATIME", Const, 0},
+		{"MS_NODEV", Const, 0},
+		{"MS_NODIRATIME", Const, 0},
+		{"MS_NOEXEC", Const, 0},
+		{"MS_NOSUID", Const, 0},
+		{"MS_NOUSER", Const, 0},
+		{"MS_POSIXACL", Const, 0},
+		{"MS_PRIVATE", Const, 0},
+		{"MS_RDONLY", Const, 0},
+		{"MS_REC", Const, 0},
+		{"MS_RELATIME", Const, 0},
+		{"MS_REMOUNT", Const, 0},
+		{"MS_RMT_MASK", Const, 0},
+		{"MS_SHARED", Const, 0},
+		{"MS_SILENT", Const, 0},
+		{"MS_SLAVE", Const, 0},
+		{"MS_STRICTATIME", Const, 0},
+		{"MS_SYNC", Const, 0},
+		{"MS_SYNCHRONOUS", Const, 0},
+		{"MS_UNBINDABLE", Const, 0},
+		{"Madvise", Func, 0},
+		{"MapViewOfFile", Func, 0},
+		{"MaxTokenInfoClass", Const, 0},
+		{"Mclpool", Type, 2},
+		{"Mclpool.Alive", Field, 2},
+		{"Mclpool.Cwm", Field, 2},
+		{"Mclpool.Grown", Field, 2},
+		{"Mclpool.Hwm", Field, 2},
+		{"Mclpool.Lwm", Field, 2},
+		{"MibIfRow", Type, 0},
+		{"MibIfRow.AdminStatus", Field, 0},
+		{"MibIfRow.Descr", Field, 0},
+		{"MibIfRow.DescrLen", Field, 0},
+		{"MibIfRow.InDiscards", Field, 0},
+		{"MibIfRow.InErrors", Field, 0},
+		{"MibIfRow.InNUcastPkts", Field, 0},
+		{"MibIfRow.InOctets", Field, 0},
+		{"MibIfRow.InUcastPkts", Field, 0},
+		{"MibIfRow.InUnknownProtos", Field, 0},
+		{"MibIfRow.Index", Field, 0},
+		{"MibIfRow.LastChange", Field, 0},
+		{"MibIfRow.Mtu", Field, 0},
+		{"MibIfRow.Name", Field, 0},
+		{"MibIfRow.OperStatus", Field, 0},
+		{"MibIfRow.OutDiscards", Field, 0},
+		{"MibIfRow.OutErrors", Field, 0},
+		{"MibIfRow.OutNUcastPkts", Field, 0},
+		{"MibIfRow.OutOctets", Field, 0},
+		{"MibIfRow.OutQLen", Field, 0},
+		{"MibIfRow.OutUcastPkts", Field, 0},
+		{"MibIfRow.PhysAddr", Field, 0},
+		{"MibIfRow.PhysAddrLen", Field, 0},
+		{"MibIfRow.Speed", Field, 0},
+		{"MibIfRow.Type", Field, 0},
+		{"Mkdir", Func, 0},
+		{"Mkdirat", Func, 0},
+		{"Mkfifo", Func, 0},
+		{"Mknod", Func, 0},
+		{"Mknodat", Func, 0},
+		{"Mlock", Func, 0},
+		{"Mlockall", Func, 0},
+		{"Mmap", Func, 0},
+		{"Mount", Func, 0},
+		{"MoveFile", Func, 0},
+		{"Mprotect", Func, 0},
+		{"Msghdr", Type, 0},
+		{"Msghdr.Control", Field, 0},
+		{"Msghdr.Controllen", Field, 0},
+		{"Msghdr.Flags", Field, 0},
+		{"Msghdr.Iov", Field, 0},
+		{"Msghdr.Iovlen", Field, 0},
+		{"Msghdr.Name", Field, 0},
+		{"Msghdr.Namelen", Field, 0},
+		{"Msghdr.Pad_cgo_0", Field, 0},
+		{"Msghdr.Pad_cgo_1", Field, 0},
+		{"Munlock", Func, 0},
+		{"Munlockall", Func, 0},
+		{"Munmap", Func, 0},
+		{"MustLoadDLL", Func, 0},
+		{"NAME_MAX", Const, 0},
+		{"NETLINK_ADD_MEMBERSHIP", Const, 0},
+		{"NETLINK_AUDIT", Const, 0},
+		{"NETLINK_BROADCAST_ERROR", Const, 0},
+		{"NETLINK_CONNECTOR", Const, 0},
+		{"NETLINK_DNRTMSG", Const, 0},
+		{"NETLINK_DROP_MEMBERSHIP", Const, 0},
+		{"NETLINK_ECRYPTFS", Const, 0},
+		{"NETLINK_FIB_LOOKUP", Const, 0},
+		{"NETLINK_FIREWALL", Const, 0},
+		{"NETLINK_GENERIC", Const, 0},
+		{"NETLINK_INET_DIAG", Const, 0},
+		{"NETLINK_IP6_FW", Const, 0},
+		{"NETLINK_ISCSI", Const, 0},
+		{"NETLINK_KOBJECT_UEVENT", Const, 0},
+		{"NETLINK_NETFILTER", Const, 0},
+		{"NETLINK_NFLOG", Const, 0},
+		{"NETLINK_NO_ENOBUFS", Const, 0},
+		{"NETLINK_PKTINFO", Const, 0},
+		{"NETLINK_RDMA", Const, 0},
+		{"NETLINK_ROUTE", Const, 0},
+		{"NETLINK_SCSITRANSPORT", Const, 0},
+		{"NETLINK_SELINUX", Const, 0},
+		{"NETLINK_UNUSED", Const, 0},
+		{"NETLINK_USERSOCK", Const, 0},
+		{"NETLINK_XFRM", Const, 0},
+		{"NET_RT_DUMP", Const, 0},
+		{"NET_RT_DUMP2", Const, 0},
+		{"NET_RT_FLAGS", Const, 0},
+		{"NET_RT_IFLIST", Const, 0},
+		{"NET_RT_IFLIST2", Const, 0},
+		{"NET_RT_IFLISTL", Const, 1},
+		{"NET_RT_IFMALIST", Const, 0},
+		{"NET_RT_MAXID", Const, 0},
+		{"NET_RT_OIFLIST", Const, 1},
+		{"NET_RT_OOIFLIST", Const, 1},
+		{"NET_RT_STAT", Const, 0},
+		{"NET_RT_STATS", Const, 1},
+		{"NET_RT_TABLE", Const, 1},
+		{"NET_RT_TRASH", Const, 0},
+		{"NLA_ALIGNTO", Const, 0},
+		{"NLA_F_NESTED", Const, 0},
+		{"NLA_F_NET_BYTEORDER", Const, 0},
+		{"NLA_HDRLEN", Const, 0},
+		{"NLMSG_ALIGNTO", Const, 0},
+		{"NLMSG_DONE", Const, 0},
+		{"NLMSG_ERROR", Const, 0},
+		{"NLMSG_HDRLEN", Const, 0},
+		{"NLMSG_MIN_TYPE", Const, 0},
+		{"NLMSG_NOOP", Const, 0},
+		{"NLMSG_OVERRUN", Const, 0},
+		{"NLM_F_ACK", Const, 0},
+		{"NLM_F_APPEND", Const, 0},
+		{"NLM_F_ATOMIC", Const, 0},
+		{"NLM_F_CREATE", Const, 0},
+		{"NLM_F_DUMP", Const, 0},
+		{"NLM_F_ECHO", Const, 0},
+		{"NLM_F_EXCL", Const, 0},
+		{"NLM_F_MATCH", Const, 0},
+		{"NLM_F_MULTI", Const, 0},
+		{"NLM_F_REPLACE", Const, 0},
+		{"NLM_F_REQUEST", Const, 0},
+		{"NLM_F_ROOT", Const, 0},
+		{"NOFLSH", Const, 0},
+		{"NOTE_ABSOLUTE", Const, 0},
+		{"NOTE_ATTRIB", Const, 0},
+		{"NOTE_BACKGROUND", Const, 16},
+		{"NOTE_CHILD", Const, 0},
+		{"NOTE_CRITICAL", Const, 16},
+		{"NOTE_DELETE", Const, 0},
+		{"NOTE_EOF", Const, 1},
+		{"NOTE_EXEC", Const, 0},
+		{"NOTE_EXIT", Const, 0},
+		{"NOTE_EXITSTATUS", Const, 0},
+		{"NOTE_EXIT_CSERROR", Const, 16},
+		{"NOTE_EXIT_DECRYPTFAIL", Const, 16},
+		{"NOTE_EXIT_DETAIL", Const, 16},
+		{"NOTE_EXIT_DETAIL_MASK", Const, 16},
+		{"NOTE_EXIT_MEMORY", Const, 16},
+		{"NOTE_EXIT_REPARENTED", Const, 16},
+		{"NOTE_EXTEND", Const, 0},
+		{"NOTE_FFAND", Const, 0},
+		{"NOTE_FFCOPY", Const, 0},
+		{"NOTE_FFCTRLMASK", Const, 0},
+		{"NOTE_FFLAGSMASK", Const, 0},
+		{"NOTE_FFNOP", Const, 0},
+		{"NOTE_FFOR", Const, 0},
+		{"NOTE_FORK", Const, 0},
+		{"NOTE_LEEWAY", Const, 16},
+		{"NOTE_LINK", Const, 0},
+		{"NOTE_LOWAT", Const, 0},
+		{"NOTE_NONE", Const, 0},
+		{"NOTE_NSECONDS", Const, 0},
+		{"NOTE_PCTRLMASK", Const, 0},
+		{"NOTE_PDATAMASK", Const, 0},
+		{"NOTE_REAP", Const, 0},
+		{"NOTE_RENAME", Const, 0},
+		{"NOTE_RESOURCEEND", Const, 0},
+		{"NOTE_REVOKE", Const, 0},
+		{"NOTE_SECONDS", Const, 0},
+		{"NOTE_SIGNAL", Const, 0},
+		{"NOTE_TRACK", Const, 0},
+		{"NOTE_TRACKERR", Const, 0},
+		{"NOTE_TRIGGER", Const, 0},
+		{"NOTE_TRUNCATE", Const, 1},
+		{"NOTE_USECONDS", Const, 0},
+		{"NOTE_VM_ERROR", Const, 0},
+		{"NOTE_VM_PRESSURE", Const, 0},
+		{"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", Const, 0},
+		{"NOTE_VM_PRESSURE_TERMINATE", Const, 0},
+		{"NOTE_WRITE", Const, 0},
+		{"NameCanonical", Const, 0},
+		{"NameCanonicalEx", Const, 0},
+		{"NameDisplay", Const, 0},
+		{"NameDnsDomain", Const, 0},
+		{"NameFullyQualifiedDN", Const, 0},
+		{"NameSamCompatible", Const, 0},
+		{"NameServicePrincipal", Const, 0},
+		{"NameUniqueId", Const, 0},
+		{"NameUnknown", Const, 0},
+		{"NameUserPrincipal", Const, 0},
+		{"Nanosleep", Func, 0},
+		{"NetApiBufferFree", Func, 0},
+		{"NetGetJoinInformation", Func, 2},
+		{"NetSetupDomainName", Const, 2},
+		{"NetSetupUnjoined", Const, 2},
+		{"NetSetupUnknownStatus", Const, 2},
+		{"NetSetupWorkgroupName", Const, 2},
+		{"NetUserGetInfo", Func, 0},
+		{"NetlinkMessage", Type, 0},
+		{"NetlinkMessage.Data", Field, 0},
+		{"NetlinkMessage.Header", Field, 0},
+		{"NetlinkRIB", Func, 0},
+		{"NetlinkRouteAttr", Type, 0},
+		{"NetlinkRouteAttr.Attr", Field, 0},
+		{"NetlinkRouteAttr.Value", Field, 0},
+		{"NetlinkRouteRequest", Type, 0},
+		{"NetlinkRouteRequest.Data", Field, 0},
+		{"NetlinkRouteRequest.Header", Field, 0},
+		{"NewCallback", Func, 0},
+		{"NewCallbackCDecl", Func, 3},
+		{"NewLazyDLL", Func, 0},
+		{"NlAttr", Type, 0},
+		{"NlAttr.Len", Field, 0},
+		{"NlAttr.Type", Field, 0},
+		{"NlMsgerr", Type, 0},
+		{"NlMsgerr.Error", Field, 0},
+		{"NlMsgerr.Msg", Field, 0},
+		{"NlMsghdr", Type, 0},
+		{"NlMsghdr.Flags", Field, 0},
+		{"NlMsghdr.Len", Field, 0},
+		{"NlMsghdr.Pid", Field, 0},
+		{"NlMsghdr.Seq", Field, 0},
+		{"NlMsghdr.Type", Field, 0},
+		{"NsecToFiletime", Func, 0},
+		{"NsecToTimespec", Func, 0},
+		{"NsecToTimeval", Func, 0},
+		{"Ntohs", Func, 0},
+		{"OCRNL", Const, 0},
+		{"OFDEL", Const, 0},
+		{"OFILL", Const, 0},
+		{"OFIOGETBMAP", Const, 1},
+		{"OID_PKIX_KP_SERVER_AUTH", Var, 0},
+		{"OID_SERVER_GATED_CRYPTO", Var, 0},
+		{"OID_SGC_NETSCAPE", Var, 0},
+		{"OLCUC", Const, 0},
+		{"ONLCR", Const, 0},
+		{"ONLRET", Const, 0},
+		{"ONOCR", Const, 0},
+		{"ONOEOT", Const, 1},
+		{"OPEN_ALWAYS", Const, 0},
+		{"OPEN_EXISTING", Const, 0},
+		{"OPOST", Const, 0},
+		{"O_ACCMODE", Const, 0},
+		{"O_ALERT", Const, 0},
+		{"O_ALT_IO", Const, 1},
+		{"O_APPEND", Const, 0},
+		{"O_ASYNC", Const, 0},
+		{"O_CLOEXEC", Const, 0},
+		{"O_CREAT", Const, 0},
+		{"O_DIRECT", Const, 0},
+		{"O_DIRECTORY", Const, 0},
+		{"O_DP_GETRAWENCRYPTED", Const, 16},
+		{"O_DSYNC", Const, 0},
+		{"O_EVTONLY", Const, 0},
+		{"O_EXCL", Const, 0},
+		{"O_EXEC", Const, 0},
+		{"O_EXLOCK", Const, 0},
+		{"O_FSYNC", Const, 0},
+		{"O_LARGEFILE", Const, 0},
+		{"O_NDELAY", Const, 0},
+		{"O_NOATIME", Const, 0},
+		{"O_NOCTTY", Const, 0},
+		{"O_NOFOLLOW", Const, 0},
+		{"O_NONBLOCK", Const, 0},
+		{"O_NOSIGPIPE", Const, 1},
+		{"O_POPUP", Const, 0},
+		{"O_RDONLY", Const, 0},
+		{"O_RDWR", Const, 0},
+		{"O_RSYNC", Const, 0},
+		{"O_SHLOCK", Const, 0},
+		{"O_SYMLINK", Const, 0},
+		{"O_SYNC", Const, 0},
+		{"O_TRUNC", Const, 0},
+		{"O_TTY_INIT", Const, 0},
+		{"O_WRONLY", Const, 0},
+		{"Open", Func, 0},
+		{"OpenCurrentProcessToken", Func, 0},
+		{"OpenProcess", Func, 0},
+		{"OpenProcessToken", Func, 0},
+		{"Openat", Func, 0},
+		{"Overlapped", Type, 0},
+		{"Overlapped.HEvent", Field, 0},
+		{"Overlapped.Internal", Field, 0},
+		{"Overlapped.InternalHigh", Field, 0},
+		{"Overlapped.Offset", Field, 0},
+		{"Overlapped.OffsetHigh", Field, 0},
+		{"PACKET_ADD_MEMBERSHIP", Const, 0},
+		{"PACKET_BROADCAST", Const, 0},
+		{"PACKET_DROP_MEMBERSHIP", Const, 0},
+		{"PACKET_FASTROUTE", Const, 0},
+		{"PACKET_HOST", Const, 0},
+		{"PACKET_LOOPBACK", Const, 0},
+		{"PACKET_MR_ALLMULTI", Const, 0},
+		{"PACKET_MR_MULTICAST", Const, 0},
+		{"PACKET_MR_PROMISC", Const, 0},
+		{"PACKET_MULTICAST", Const, 0},
+		{"PACKET_OTHERHOST", Const, 0},
+		{"PACKET_OUTGOING", Const, 0},
+		{"PACKET_RECV_OUTPUT", Const, 0},
+		{"PACKET_RX_RING", Const, 0},
+		{"PACKET_STATISTICS", Const, 0},
+		{"PAGE_EXECUTE_READ", Const, 0},
+		{"PAGE_EXECUTE_READWRITE", Const, 0},
+		{"PAGE_EXECUTE_WRITECOPY", Const, 0},
+		{"PAGE_READONLY", Const, 0},
+		{"PAGE_READWRITE", Const, 0},
+		{"PAGE_WRITECOPY", Const, 0},
+		{"PARENB", Const, 0},
+		{"PARMRK", Const, 0},
+		{"PARODD", Const, 0},
+		{"PENDIN", Const, 0},
+		{"PFL_HIDDEN", Const, 2},
+		{"PFL_MATCHES_PROTOCOL_ZERO", Const, 2},
+		{"PFL_MULTIPLE_PROTO_ENTRIES", Const, 2},
+		{"PFL_NETWORKDIRECT_PROVIDER", Const, 2},
+		{"PFL_RECOMMENDED_PROTO_ENTRY", Const, 2},
+		{"PF_FLUSH", Const, 1},
+		{"PKCS_7_ASN_ENCODING", Const, 0},
+		{"PMC5_PIPELINE_FLUSH", Const, 1},
+		{"PRIO_PGRP", Const, 2},
+		{"PRIO_PROCESS", Const, 2},
+		{"PRIO_USER", Const, 2},
+		{"PRI_IOFLUSH", Const, 1},
+		{"PROCESS_QUERY_INFORMATION", Const, 0},
+		{"PROCESS_TERMINATE", Const, 2},
+		{"PROT_EXEC", Const, 0},
+		{"PROT_GROWSDOWN", Const, 0},
+		{"PROT_GROWSUP", Const, 0},
+		{"PROT_NONE", Const, 0},
+		{"PROT_READ", Const, 0},
+		{"PROT_WRITE", Const, 0},
+		{"PROV_DH_SCHANNEL", Const, 0},
+		{"PROV_DSS", Const, 0},
+		{"PROV_DSS_DH", Const, 0},
+		{"PROV_EC_ECDSA_FULL", Const, 0},
+		{"PROV_EC_ECDSA_SIG", Const, 0},
+		{"PROV_EC_ECNRA_FULL", Const, 0},
+		{"PROV_EC_ECNRA_SIG", Const, 0},
+		{"PROV_FORTEZZA", Const, 0},
+		{"PROV_INTEL_SEC", Const, 0},
+		{"PROV_MS_EXCHANGE", Const, 0},
+		{"PROV_REPLACE_OWF", Const, 0},
+		{"PROV_RNG", Const, 0},
+		{"PROV_RSA_AES", Const, 0},
+		{"PROV_RSA_FULL", Const, 0},
+		{"PROV_RSA_SCHANNEL", Const, 0},
+		{"PROV_RSA_SIG", Const, 0},
+		{"PROV_SPYRUS_LYNKS", Const, 0},
+		{"PROV_SSL", Const, 0},
+		{"PR_CAPBSET_DROP", Const, 0},
+		{"PR_CAPBSET_READ", Const, 0},
+		{"PR_CLEAR_SECCOMP_FILTER", Const, 0},
+		{"PR_ENDIAN_BIG", Const, 0},
+		{"PR_ENDIAN_LITTLE", Const, 0},
+		{"PR_ENDIAN_PPC_LITTLE", Const, 0},
+		{"PR_FPEMU_NOPRINT", Const, 0},
+		{"PR_FPEMU_SIGFPE", Const, 0},
+		{"PR_FP_EXC_ASYNC", Const, 0},
+		{"PR_FP_EXC_DISABLED", Const, 0},
+		{"PR_FP_EXC_DIV", Const, 0},
+		{"PR_FP_EXC_INV", Const, 0},
+		{"PR_FP_EXC_NONRECOV", Const, 0},
+		{"PR_FP_EXC_OVF", Const, 0},
+		{"PR_FP_EXC_PRECISE", Const, 0},
+		{"PR_FP_EXC_RES", Const, 0},
+		{"PR_FP_EXC_SW_ENABLE", Const, 0},
+		{"PR_FP_EXC_UND", Const, 0},
+		{"PR_GET_DUMPABLE", Const, 0},
+		{"PR_GET_ENDIAN", Const, 0},
+		{"PR_GET_FPEMU", Const, 0},
+		{"PR_GET_FPEXC", Const, 0},
+		{"PR_GET_KEEPCAPS", Const, 0},
+		{"PR_GET_NAME", Const, 0},
+		{"PR_GET_PDEATHSIG", Const, 0},
+		{"PR_GET_SECCOMP", Const, 0},
+		{"PR_GET_SECCOMP_FILTER", Const, 0},
+		{"PR_GET_SECUREBITS", Const, 0},
+		{"PR_GET_TIMERSLACK", Const, 0},
+		{"PR_GET_TIMING", Const, 0},
+		{"PR_GET_TSC", Const, 0},
+		{"PR_GET_UNALIGN", Const, 0},
+		{"PR_MCE_KILL", Const, 0},
+		{"PR_MCE_KILL_CLEAR", Const, 0},
+		{"PR_MCE_KILL_DEFAULT", Const, 0},
+		{"PR_MCE_KILL_EARLY", Const, 0},
+		{"PR_MCE_KILL_GET", Const, 0},
+		{"PR_MCE_KILL_LATE", Const, 0},
+		{"PR_MCE_KILL_SET", Const, 0},
+		{"PR_SECCOMP_FILTER_EVENT", Const, 0},
+		{"PR_SECCOMP_FILTER_SYSCALL", Const, 0},
+		{"PR_SET_DUMPABLE", Const, 0},
+		{"PR_SET_ENDIAN", Const, 0},
+		{"PR_SET_FPEMU", Const, 0},
+		{"PR_SET_FPEXC", Const, 0},
+		{"PR_SET_KEEPCAPS", Const, 0},
+		{"PR_SET_NAME", Const, 0},
+		{"PR_SET_PDEATHSIG", Const, 0},
+		{"PR_SET_PTRACER", Const, 0},
+		{"PR_SET_SECCOMP", Const, 0},
+		{"PR_SET_SECCOMP_FILTER", Const, 0},
+		{"PR_SET_SECUREBITS", Const, 0},
+		{"PR_SET_TIMERSLACK", Const, 0},
+		{"PR_SET_TIMING", Const, 0},
+		{"PR_SET_TSC", Const, 0},
+		{"PR_SET_UNALIGN", Const, 0},
+		{"PR_TASK_PERF_EVENTS_DISABLE", Const, 0},
+		{"PR_TASK_PERF_EVENTS_ENABLE", Const, 0},
+		{"PR_TIMING_STATISTICAL", Const, 0},
+		{"PR_TIMING_TIMESTAMP", Const, 0},
+		{"PR_TSC_ENABLE", Const, 0},
+		{"PR_TSC_SIGSEGV", Const, 0},
+		{"PR_UNALIGN_NOPRINT", Const, 0},
+		{"PR_UNALIGN_SIGBUS", Const, 0},
+		{"PTRACE_ARCH_PRCTL", Const, 0},
+		{"PTRACE_ATTACH", Const, 0},
+		{"PTRACE_CONT", Const, 0},
+		{"PTRACE_DETACH", Const, 0},
+		{"PTRACE_EVENT_CLONE", Const, 0},
+		{"PTRACE_EVENT_EXEC", Const, 0},
+		{"PTRACE_EVENT_EXIT", Const, 0},
+		{"PTRACE_EVENT_FORK", Const, 0},
+		{"PTRACE_EVENT_VFORK", Const, 0},
+		{"PTRACE_EVENT_VFORK_DONE", Const, 0},
+		{"PTRACE_GETCRUNCHREGS", Const, 0},
+		{"PTRACE_GETEVENTMSG", Const, 0},
+		{"PTRACE_GETFPREGS", Const, 0},
+		{"PTRACE_GETFPXREGS", Const, 0},
+		{"PTRACE_GETHBPREGS", Const, 0},
+		{"PTRACE_GETREGS", Const, 0},
+		{"PTRACE_GETREGSET", Const, 0},
+		{"PTRACE_GETSIGINFO", Const, 0},
+		{"PTRACE_GETVFPREGS", Const, 0},
+		{"PTRACE_GETWMMXREGS", Const, 0},
+		{"PTRACE_GET_THREAD_AREA", Const, 0},
+		{"PTRACE_KILL", Const, 0},
+		{"PTRACE_OLDSETOPTIONS", Const, 0},
+		{"PTRACE_O_MASK", Const, 0},
+		{"PTRACE_O_TRACECLONE", Const, 0},
+		{"PTRACE_O_TRACEEXEC", Const, 0},
+		{"PTRACE_O_TRACEEXIT", Const, 0},
+		{"PTRACE_O_TRACEFORK", Const, 0},
+		{"PTRACE_O_TRACESYSGOOD", Const, 0},
+		{"PTRACE_O_TRACEVFORK", Const, 0},
+		{"PTRACE_O_TRACEVFORKDONE", Const, 0},
+		{"PTRACE_PEEKDATA", Const, 0},
+		{"PTRACE_PEEKTEXT", Const, 0},
+		{"PTRACE_PEEKUSR", Const, 0},
+		{"PTRACE_POKEDATA", Const, 0},
+		{"PTRACE_POKETEXT", Const, 0},
+		{"PTRACE_POKEUSR", Const, 0},
+		{"PTRACE_SETCRUNCHREGS", Const, 0},
+		{"PTRACE_SETFPREGS", Const, 0},
+		{"PTRACE_SETFPXREGS", Const, 0},
+		{"PTRACE_SETHBPREGS", Const, 0},
+		{"PTRACE_SETOPTIONS", Const, 0},
+		{"PTRACE_SETREGS", Const, 0},
+		{"PTRACE_SETREGSET", Const, 0},
+		{"PTRACE_SETSIGINFO", Const, 0},
+		{"PTRACE_SETVFPREGS", Const, 0},
+		{"PTRACE_SETWMMXREGS", Const, 0},
+		{"PTRACE_SET_SYSCALL", Const, 0},
+		{"PTRACE_SET_THREAD_AREA", Const, 0},
+		{"PTRACE_SINGLEBLOCK", Const, 0},
+		{"PTRACE_SINGLESTEP", Const, 0},
+		{"PTRACE_SYSCALL", Const, 0},
+		{"PTRACE_SYSEMU", Const, 0},
+		{"PTRACE_SYSEMU_SINGLESTEP", Const, 0},
+		{"PTRACE_TRACEME", Const, 0},
+		{"PT_ATTACH", Const, 0},
+		{"PT_ATTACHEXC", Const, 0},
+		{"PT_CONTINUE", Const, 0},
+		{"PT_DATA_ADDR", Const, 0},
+		{"PT_DENY_ATTACH", Const, 0},
+		{"PT_DETACH", Const, 0},
+		{"PT_FIRSTMACH", Const, 0},
+		{"PT_FORCEQUOTA", Const, 0},
+		{"PT_KILL", Const, 0},
+		{"PT_MASK", Const, 1},
+		{"PT_READ_D", Const, 0},
+		{"PT_READ_I", Const, 0},
+		{"PT_READ_U", Const, 0},
+		{"PT_SIGEXC", Const, 0},
+		{"PT_STEP", Const, 0},
+		{"PT_TEXT_ADDR", Const, 0},
+		{"PT_TEXT_END_ADDR", Const, 0},
+		{"PT_THUPDATE", Const, 0},
+		{"PT_TRACE_ME", Const, 0},
+		{"PT_WRITE_D", Const, 0},
+		{"PT_WRITE_I", Const, 0},
+		{"PT_WRITE_U", Const, 0},
+		{"ParseDirent", Func, 0},
+		{"ParseNetlinkMessage", Func, 0},
+		{"ParseNetlinkRouteAttr", Func, 0},
+		{"ParseRoutingMessage", Func, 0},
+		{"ParseRoutingSockaddr", Func, 0},
+		{"ParseSocketControlMessage", Func, 0},
+		{"ParseUnixCredentials", Func, 0},
+		{"ParseUnixRights", Func, 0},
+		{"PathMax", Const, 0},
+		{"Pathconf", Func, 0},
+		{"Pause", Func, 0},
+		{"Pipe", Func, 0},
+		{"Pipe2", Func, 1},
+		{"PivotRoot", Func, 0},
+		{"Pointer", Type, 11},
+		{"PostQueuedCompletionStatus", Func, 0},
+		{"Pread", Func, 0},
+		{"Proc", Type, 0},
+		{"Proc.Dll", Field, 0},
+		{"Proc.Name", Field, 0},
+		{"ProcAttr", Type, 0},
+		{"ProcAttr.Dir", Field, 0},
+		{"ProcAttr.Env", Field, 0},
+		{"ProcAttr.Files", Field, 0},
+		{"ProcAttr.Sys", Field, 0},
+		{"Process32First", Func, 4},
+		{"Process32Next", Func, 4},
+		{"ProcessEntry32", Type, 4},
+		{"ProcessEntry32.DefaultHeapID", Field, 4},
+		{"ProcessEntry32.ExeFile", Field, 4},
+		{"ProcessEntry32.Flags", Field, 4},
+		{"ProcessEntry32.ModuleID", Field, 4},
+		{"ProcessEntry32.ParentProcessID", Field, 4},
+		{"ProcessEntry32.PriClassBase", Field, 4},
+		{"ProcessEntry32.ProcessID", Field, 4},
+		{"ProcessEntry32.Size", Field, 4},
+		{"ProcessEntry32.Threads", Field, 4},
+		{"ProcessEntry32.Usage", Field, 4},
+		{"ProcessInformation", Type, 0},
+		{"ProcessInformation.Process", Field, 0},
+		{"ProcessInformation.ProcessId", Field, 0},
+		{"ProcessInformation.Thread", Field, 0},
+		{"ProcessInformation.ThreadId", Field, 0},
+		{"Protoent", Type, 0},
+		{"Protoent.Aliases", Field, 0},
+		{"Protoent.Name", Field, 0},
+		{"Protoent.Proto", Field, 0},
+		{"PtraceAttach", Func, 0},
+		{"PtraceCont", Func, 0},
+		{"PtraceDetach", Func, 0},
+		{"PtraceGetEventMsg", Func, 0},
+		{"PtraceGetRegs", Func, 0},
+		{"PtracePeekData", Func, 0},
+		{"PtracePeekText", Func, 0},
+		{"PtracePokeData", Func, 0},
+		{"PtracePokeText", Func, 0},
+		{"PtraceRegs", Type, 0},
+		{"PtraceRegs.Cs", Field, 0},
+		{"PtraceRegs.Ds", Field, 0},
+		{"PtraceRegs.Eax", Field, 0},
+		{"PtraceRegs.Ebp", Field, 0},
+		{"PtraceRegs.Ebx", Field, 0},
+		{"PtraceRegs.Ecx", Field, 0},
+		{"PtraceRegs.Edi", Field, 0},
+		{"PtraceRegs.Edx", Field, 0},
+		{"PtraceRegs.Eflags", Field, 0},
+		{"PtraceRegs.Eip", Field, 0},
+		{"PtraceRegs.Es", Field, 0},
+		{"PtraceRegs.Esi", Field, 0},
+		{"PtraceRegs.Esp", Field, 0},
+		{"PtraceRegs.Fs", Field, 0},
+		{"PtraceRegs.Fs_base", Field, 0},
+		{"PtraceRegs.Gs", Field, 0},
+		{"PtraceRegs.Gs_base", Field, 0},
+		{"PtraceRegs.Orig_eax", Field, 0},
+		{"PtraceRegs.Orig_rax", Field, 0},
+		{"PtraceRegs.R10", Field, 0},
+		{"PtraceRegs.R11", Field, 0},
+		{"PtraceRegs.R12", Field, 0},
+		{"PtraceRegs.R13", Field, 0},
+		{"PtraceRegs.R14", Field, 0},
+		{"PtraceRegs.R15", Field, 0},
+		{"PtraceRegs.R8", Field, 0},
+		{"PtraceRegs.R9", Field, 0},
+		{"PtraceRegs.Rax", Field, 0},
+		{"PtraceRegs.Rbp", Field, 0},
+		{"PtraceRegs.Rbx", Field, 0},
+		{"PtraceRegs.Rcx", Field, 0},
+		{"PtraceRegs.Rdi", Field, 0},
+		{"PtraceRegs.Rdx", Field, 0},
+		{"PtraceRegs.Rip", Field, 0},
+		{"PtraceRegs.Rsi", Field, 0},
+		{"PtraceRegs.Rsp", Field, 0},
+		{"PtraceRegs.Ss", Field, 0},
+		{"PtraceRegs.Uregs", Field, 0},
+		{"PtraceRegs.Xcs", Field, 0},
+		{"PtraceRegs.Xds", Field, 0},
+		{"PtraceRegs.Xes", Field, 0},
+		{"PtraceRegs.Xfs", Field, 0},
+		{"PtraceRegs.Xgs", Field, 0},
+		{"PtraceRegs.Xss", Field, 0},
+		{"PtraceSetOptions", Func, 0},
+		{"PtraceSetRegs", Func, 0},
+		{"PtraceSingleStep", Func, 0},
+		{"PtraceSyscall", Func, 1},
+		{"Pwrite", Func, 0},
+		{"REG_BINARY", Const, 0},
+		{"REG_DWORD", Const, 0},
+		{"REG_DWORD_BIG_ENDIAN", Const, 0},
+		{"REG_DWORD_LITTLE_ENDIAN", Const, 0},
+		{"REG_EXPAND_SZ", Const, 0},
+		{"REG_FULL_RESOURCE_DESCRIPTOR", Const, 0},
+		{"REG_LINK", Const, 0},
+		{"REG_MULTI_SZ", Const, 0},
+		{"REG_NONE", Const, 0},
+		{"REG_QWORD", Const, 0},
+		{"REG_QWORD_LITTLE_ENDIAN", Const, 0},
+		{"REG_RESOURCE_LIST", Const, 0},
+		{"REG_RESOURCE_REQUIREMENTS_LIST", Const, 0},
+		{"REG_SZ", Const, 0},
+		{"RLIMIT_AS", Const, 0},
+		{"RLIMIT_CORE", Const, 0},
+		{"RLIMIT_CPU", Const, 0},
+		{"RLIMIT_CPU_USAGE_MONITOR", Const, 16},
+		{"RLIMIT_DATA", Const, 0},
+		{"RLIMIT_FSIZE", Const, 0},
+		{"RLIMIT_NOFILE", Const, 0},
+		{"RLIMIT_STACK", Const, 0},
+		{"RLIM_INFINITY", Const, 0},
+		{"RTAX_ADVMSS", Const, 0},
+		{"RTAX_AUTHOR", Const, 0},
+		{"RTAX_BRD", Const, 0},
+		{"RTAX_CWND", Const, 0},
+		{"RTAX_DST", Const, 0},
+		{"RTAX_FEATURES", Const, 0},
+		{"RTAX_FEATURE_ALLFRAG", Const, 0},
+		{"RTAX_FEATURE_ECN", Const, 0},
+		{"RTAX_FEATURE_SACK", Const, 0},
+		{"RTAX_FEATURE_TIMESTAMP", Const, 0},
+		{"RTAX_GATEWAY", Const, 0},
+		{"RTAX_GENMASK", Const, 0},
+		{"RTAX_HOPLIMIT", Const, 0},
+		{"RTAX_IFA", Const, 0},
+		{"RTAX_IFP", Const, 0},
+		{"RTAX_INITCWND", Const, 0},
+		{"RTAX_INITRWND", Const, 0},
+		{"RTAX_LABEL", Const, 1},
+		{"RTAX_LOCK", Const, 0},
+		{"RTAX_MAX", Const, 0},
+		{"RTAX_MTU", Const, 0},
+		{"RTAX_NETMASK", Const, 0},
+		{"RTAX_REORDERING", Const, 0},
+		{"RTAX_RTO_MIN", Const, 0},
+		{"RTAX_RTT", Const, 0},
+		{"RTAX_RTTVAR", Const, 0},
+		{"RTAX_SRC", Const, 1},
+		{"RTAX_SRCMASK", Const, 1},
+		{"RTAX_SSTHRESH", Const, 0},
+		{"RTAX_TAG", Const, 1},
+		{"RTAX_UNSPEC", Const, 0},
+		{"RTAX_WINDOW", Const, 0},
+		{"RTA_ALIGNTO", Const, 0},
+		{"RTA_AUTHOR", Const, 0},
+		{"RTA_BRD", Const, 0},
+		{"RTA_CACHEINFO", Const, 0},
+		{"RTA_DST", Const, 0},
+		{"RTA_FLOW", Const, 0},
+		{"RTA_GATEWAY", Const, 0},
+		{"RTA_GENMASK", Const, 0},
+		{"RTA_IFA", Const, 0},
+		{"RTA_IFP", Const, 0},
+		{"RTA_IIF", Const, 0},
+		{"RTA_LABEL", Const, 1},
+		{"RTA_MAX", Const, 0},
+		{"RTA_METRICS", Const, 0},
+		{"RTA_MULTIPATH", Const, 0},
+		{"RTA_NETMASK", Const, 0},
+		{"RTA_OIF", Const, 0},
+		{"RTA_PREFSRC", Const, 0},
+		{"RTA_PRIORITY", Const, 0},
+		{"RTA_SRC", Const, 0},
+		{"RTA_SRCMASK", Const, 1},
+		{"RTA_TABLE", Const, 0},
+		{"RTA_TAG", Const, 1},
+		{"RTA_UNSPEC", Const, 0},
+		{"RTCF_DIRECTSRC", Const, 0},
+		{"RTCF_DOREDIRECT", Const, 0},
+		{"RTCF_LOG", Const, 0},
+		{"RTCF_MASQ", Const, 0},
+		{"RTCF_NAT", Const, 0},
+		{"RTCF_VALVE", Const, 0},
+		{"RTF_ADDRCLASSMASK", Const, 0},
+		{"RTF_ADDRCONF", Const, 0},
+		{"RTF_ALLONLINK", Const, 0},
+		{"RTF_ANNOUNCE", Const, 1},
+		{"RTF_BLACKHOLE", Const, 0},
+		{"RTF_BROADCAST", Const, 0},
+		{"RTF_CACHE", Const, 0},
+		{"RTF_CLONED", Const, 1},
+		{"RTF_CLONING", Const, 0},
+		{"RTF_CONDEMNED", Const, 0},
+		{"RTF_DEFAULT", Const, 0},
+		{"RTF_DELCLONE", Const, 0},
+		{"RTF_DONE", Const, 0},
+		{"RTF_DYNAMIC", Const, 0},
+		{"RTF_FLOW", Const, 0},
+		{"RTF_FMASK", Const, 0},
+		{"RTF_GATEWAY", Const, 0},
+		{"RTF_GWFLAG_COMPAT", Const, 3},
+		{"RTF_HOST", Const, 0},
+		{"RTF_IFREF", Const, 0},
+		{"RTF_IFSCOPE", Const, 0},
+		{"RTF_INTERFACE", Const, 0},
+		{"RTF_IRTT", Const, 0},
+		{"RTF_LINKRT", Const, 0},
+		{"RTF_LLDATA", Const, 0},
+		{"RTF_LLINFO", Const, 0},
+		{"RTF_LOCAL", Const, 0},
+		{"RTF_MASK", Const, 1},
+		{"RTF_MODIFIED", Const, 0},
+		{"RTF_MPATH", Const, 1},
+		{"RTF_MPLS", Const, 1},
+		{"RTF_MSS", Const, 0},
+		{"RTF_MTU", Const, 0},
+		{"RTF_MULTICAST", Const, 0},
+		{"RTF_NAT", Const, 0},
+		{"RTF_NOFORWARD", Const, 0},
+		{"RTF_NONEXTHOP", Const, 0},
+		{"RTF_NOPMTUDISC", Const, 0},
+		{"RTF_PERMANENT_ARP", Const, 1},
+		{"RTF_PINNED", Const, 0},
+		{"RTF_POLICY", Const, 0},
+		{"RTF_PRCLONING", Const, 0},
+		{"RTF_PROTO1", Const, 0},
+		{"RTF_PROTO2", Const, 0},
+		{"RTF_PROTO3", Const, 0},
+		{"RTF_PROXY", Const, 16},
+		{"RTF_REINSTATE", Const, 0},
+		{"RTF_REJECT", Const, 0},
+		{"RTF_RNH_LOCKED", Const, 0},
+		{"RTF_ROUTER", Const, 16},
+		{"RTF_SOURCE", Const, 1},
+		{"RTF_SRC", Const, 1},
+		{"RTF_STATIC", Const, 0},
+		{"RTF_STICKY", Const, 0},
+		{"RTF_THROW", Const, 0},
+		{"RTF_TUNNEL", Const, 1},
+		{"RTF_UP", Const, 0},
+		{"RTF_USETRAILERS", Const, 1},
+		{"RTF_WASCLONED", Const, 0},
+		{"RTF_WINDOW", Const, 0},
+		{"RTF_XRESOLVE", Const, 0},
+		{"RTM_ADD", Const, 0},
+		{"RTM_BASE", Const, 0},
+		{"RTM_CHANGE", Const, 0},
+		{"RTM_CHGADDR", Const, 1},
+		{"RTM_DELACTION", Const, 0},
+		{"RTM_DELADDR", Const, 0},
+		{"RTM_DELADDRLABEL", Const, 0},
+		{"RTM_DELETE", Const, 0},
+		{"RTM_DELLINK", Const, 0},
+		{"RTM_DELMADDR", Const, 0},
+		{"RTM_DELNEIGH", Const, 0},
+		{"RTM_DELQDISC", Const, 0},
+		{"RTM_DELROUTE", Const, 0},
+		{"RTM_DELRULE", Const, 0},
+		{"RTM_DELTCLASS", Const, 0},
+		{"RTM_DELTFILTER", Const, 0},
+		{"RTM_DESYNC", Const, 1},
+		{"RTM_F_CLONED", Const, 0},
+		{"RTM_F_EQUALIZE", Const, 0},
+		{"RTM_F_NOTIFY", Const, 0},
+		{"RTM_F_PREFIX", Const, 0},
+		{"RTM_GET", Const, 0},
+		{"RTM_GET2", Const, 0},
+		{"RTM_GETACTION", Const, 0},
+		{"RTM_GETADDR", Const, 0},
+		{"RTM_GETADDRLABEL", Const, 0},
+		{"RTM_GETANYCAST", Const, 0},
+		{"RTM_GETDCB", Const, 0},
+		{"RTM_GETLINK", Const, 0},
+		{"RTM_GETMULTICAST", Const, 0},
+		{"RTM_GETNEIGH", Const, 0},
+		{"RTM_GETNEIGHTBL", Const, 0},
+		{"RTM_GETQDISC", Const, 0},
+		{"RTM_GETROUTE", Const, 0},
+		{"RTM_GETRULE", Const, 0},
+		{"RTM_GETTCLASS", Const, 0},
+		{"RTM_GETTFILTER", Const, 0},
+		{"RTM_IEEE80211", Const, 0},
+		{"RTM_IFANNOUNCE", Const, 0},
+		{"RTM_IFINFO", Const, 0},
+		{"RTM_IFINFO2", Const, 0},
+		{"RTM_LLINFO_UPD", Const, 1},
+		{"RTM_LOCK", Const, 0},
+		{"RTM_LOSING", Const, 0},
+		{"RTM_MAX", Const, 0},
+		{"RTM_MAXSIZE", Const, 1},
+		{"RTM_MISS", Const, 0},
+		{"RTM_NEWACTION", Const, 0},
+		{"RTM_NEWADDR", Const, 0},
+		{"RTM_NEWADDRLABEL", Const, 0},
+		{"RTM_NEWLINK", Const, 0},
+		{"RTM_NEWMADDR", Const, 0},
+		{"RTM_NEWMADDR2", Const, 0},
+		{"RTM_NEWNDUSEROPT", Const, 0},
+		{"RTM_NEWNEIGH", Const, 0},
+		{"RTM_NEWNEIGHTBL", Const, 0},
+		{"RTM_NEWPREFIX", Const, 0},
+		{"RTM_NEWQDISC", Const, 0},
+		{"RTM_NEWROUTE", Const, 0},
+		{"RTM_NEWRULE", Const, 0},
+		{"RTM_NEWTCLASS", Const, 0},
+		{"RTM_NEWTFILTER", Const, 0},
+		{"RTM_NR_FAMILIES", Const, 0},
+		{"RTM_NR_MSGTYPES", Const, 0},
+		{"RTM_OIFINFO", Const, 1},
+		{"RTM_OLDADD", Const, 0},
+		{"RTM_OLDDEL", Const, 0},
+		{"RTM_OOIFINFO", Const, 1},
+		{"RTM_REDIRECT", Const, 0},
+		{"RTM_RESOLVE", Const, 0},
+		{"RTM_RTTUNIT", Const, 0},
+		{"RTM_SETDCB", Const, 0},
+		{"RTM_SETGATE", Const, 1},
+		{"RTM_SETLINK", Const, 0},
+		{"RTM_SETNEIGHTBL", Const, 0},
+		{"RTM_VERSION", Const, 0},
+		{"RTNH_ALIGNTO", Const, 0},
+		{"RTNH_F_DEAD", Const, 0},
+		{"RTNH_F_ONLINK", Const, 0},
+		{"RTNH_F_PERVASIVE", Const, 0},
+		{"RTNLGRP_IPV4_IFADDR", Const, 1},
+		{"RTNLGRP_IPV4_MROUTE", Const, 1},
+		{"RTNLGRP_IPV4_ROUTE", Const, 1},
+		{"RTNLGRP_IPV4_RULE", Const, 1},
+		{"RTNLGRP_IPV6_IFADDR", Const, 1},
+		{"RTNLGRP_IPV6_IFINFO", Const, 1},
+		{"RTNLGRP_IPV6_MROUTE", Const, 1},
+		{"RTNLGRP_IPV6_PREFIX", Const, 1},
+		{"RTNLGRP_IPV6_ROUTE", Const, 1},
+		{"RTNLGRP_IPV6_RULE", Const, 1},
+		{"RTNLGRP_LINK", Const, 1},
+		{"RTNLGRP_ND_USEROPT", Const, 1},
+		{"RTNLGRP_NEIGH", Const, 1},
+		{"RTNLGRP_NONE", Const, 1},
+		{"RTNLGRP_NOTIFY", Const, 1},
+		{"RTNLGRP_TC", Const, 1},
+		{"RTN_ANYCAST", Const, 0},
+		{"RTN_BLACKHOLE", Const, 0},
+		{"RTN_BROADCAST", Const, 0},
+		{"RTN_LOCAL", Const, 0},
+		{"RTN_MAX", Const, 0},
+		{"RTN_MULTICAST", Const, 0},
+		{"RTN_NAT", Const, 0},
+		{"RTN_PROHIBIT", Const, 0},
+		{"RTN_THROW", Const, 0},
+		{"RTN_UNICAST", Const, 0},
+		{"RTN_UNREACHABLE", Const, 0},
+		{"RTN_UNSPEC", Const, 0},
+		{"RTN_XRESOLVE", Const, 0},
+		{"RTPROT_BIRD", Const, 0},
+		{"RTPROT_BOOT", Const, 0},
+		{"RTPROT_DHCP", Const, 0},
+		{"RTPROT_DNROUTED", Const, 0},
+		{"RTPROT_GATED", Const, 0},
+		{"RTPROT_KERNEL", Const, 0},
+		{"RTPROT_MRT", Const, 0},
+		{"RTPROT_NTK", Const, 0},
+		{"RTPROT_RA", Const, 0},
+		{"RTPROT_REDIRECT", Const, 0},
+		{"RTPROT_STATIC", Const, 0},
+		{"RTPROT_UNSPEC", Const, 0},
+		{"RTPROT_XORP", Const, 0},
+		{"RTPROT_ZEBRA", Const, 0},
+		{"RTV_EXPIRE", Const, 0},
+		{"RTV_HOPCOUNT", Const, 0},
+		{"RTV_MTU", Const, 0},
+		{"RTV_RPIPE", Const, 0},
+		{"RTV_RTT", Const, 0},
+		{"RTV_RTTVAR", Const, 0},
+		{"RTV_SPIPE", Const, 0},
+		{"RTV_SSTHRESH", Const, 0},
+		{"RTV_WEIGHT", Const, 0},
+		{"RT_CACHING_CONTEXT", Const, 1},
+		{"RT_CLASS_DEFAULT", Const, 0},
+		{"RT_CLASS_LOCAL", Const, 0},
+		{"RT_CLASS_MAIN", Const, 0},
+		{"RT_CLASS_MAX", Const, 0},
+		{"RT_CLASS_UNSPEC", Const, 0},
+		{"RT_DEFAULT_FIB", Const, 1},
+		{"RT_NORTREF", Const, 1},
+		{"RT_SCOPE_HOST", Const, 0},
+		{"RT_SCOPE_LINK", Const, 0},
+		{"RT_SCOPE_NOWHERE", Const, 0},
+		{"RT_SCOPE_SITE", Const, 0},
+		{"RT_SCOPE_UNIVERSE", Const, 0},
+		{"RT_TABLEID_MAX", Const, 1},
+		{"RT_TABLE_COMPAT", Const, 0},
+		{"RT_TABLE_DEFAULT", Const, 0},
+		{"RT_TABLE_LOCAL", Const, 0},
+		{"RT_TABLE_MAIN", Const, 0},
+		{"RT_TABLE_MAX", Const, 0},
+		{"RT_TABLE_UNSPEC", Const, 0},
+		{"RUSAGE_CHILDREN", Const, 0},
+		{"RUSAGE_SELF", Const, 0},
+		{"RUSAGE_THREAD", Const, 0},
+		{"Radvisory_t", Type, 0},
+		{"Radvisory_t.Count", Field, 0},
+		{"Radvisory_t.Offset", Field, 0},
+		{"Radvisory_t.Pad_cgo_0", Field, 0},
+		{"RawConn", Type, 9},
+		{"RawSockaddr", Type, 0},
+		{"RawSockaddr.Data", Field, 0},
+		{"RawSockaddr.Family", Field, 0},
+		{"RawSockaddr.Len", Field, 0},
+		{"RawSockaddrAny", Type, 0},
+		{"RawSockaddrAny.Addr", Field, 0},
+		{"RawSockaddrAny.Pad", Field, 0},
+		{"RawSockaddrDatalink", Type, 0},
+		{"RawSockaddrDatalink.Alen", Field, 0},
+		{"RawSockaddrDatalink.Data", Field, 0},
+		{"RawSockaddrDatalink.Family", Field, 0},
+		{"RawSockaddrDatalink.Index", Field, 0},
+		{"RawSockaddrDatalink.Len", Field, 0},
+		{"RawSockaddrDatalink.Nlen", Field, 0},
+		{"RawSockaddrDatalink.Pad_cgo_0", Field, 2},
+		{"RawSockaddrDatalink.Slen", Field, 0},
+		{"RawSockaddrDatalink.Type", Field, 0},
+		{"RawSockaddrInet4", Type, 0},
+		{"RawSockaddrInet4.Addr", Field, 0},
+		{"RawSockaddrInet4.Family", Field, 0},
+		{"RawSockaddrInet4.Len", Field, 0},
+		{"RawSockaddrInet4.Port", Field, 0},
+		{"RawSockaddrInet4.Zero", Field, 0},
+		{"RawSockaddrInet6", Type, 0},
+		{"RawSockaddrInet6.Addr", Field, 0},
+		{"RawSockaddrInet6.Family", Field, 0},
+		{"RawSockaddrInet6.Flowinfo", Field, 0},
+		{"RawSockaddrInet6.Len", Field, 0},
+		{"RawSockaddrInet6.Port", Field, 0},
+		{"RawSockaddrInet6.Scope_id", Field, 0},
+		{"RawSockaddrLinklayer", Type, 0},
+		{"RawSockaddrLinklayer.Addr", Field, 0},
+		{"RawSockaddrLinklayer.Family", Field, 0},
+		{"RawSockaddrLinklayer.Halen", Field, 0},
+		{"RawSockaddrLinklayer.Hatype", Field, 0},
+		{"RawSockaddrLinklayer.Ifindex", Field, 0},
+		{"RawSockaddrLinklayer.Pkttype", Field, 0},
+		{"RawSockaddrLinklayer.Protocol", Field, 0},
+		{"RawSockaddrNetlink", Type, 0},
+		{"RawSockaddrNetlink.Family", Field, 0},
+		{"RawSockaddrNetlink.Groups", Field, 0},
+		{"RawSockaddrNetlink.Pad", Field, 0},
+		{"RawSockaddrNetlink.Pid", Field, 0},
+		{"RawSockaddrUnix", Type, 0},
+		{"RawSockaddrUnix.Family", Field, 0},
+		{"RawSockaddrUnix.Len", Field, 0},
+		{"RawSockaddrUnix.Pad_cgo_0", Field, 2},
+		{"RawSockaddrUnix.Path", Field, 0},
+		{"RawSyscall", Func, 0},
+		{"RawSyscall6", Func, 0},
+		{"Read", Func, 0},
+		{"ReadConsole", Func, 1},
+		{"ReadDirectoryChanges", Func, 0},
+		{"ReadDirent", Func, 0},
+		{"ReadFile", Func, 0},
+		{"Readlink", Func, 0},
+		{"Reboot", Func, 0},
+		{"Recvfrom", Func, 0},
+		{"Recvmsg", Func, 0},
+		{"RegCloseKey", Func, 0},
+		{"RegEnumKeyEx", Func, 0},
+		{"RegOpenKeyEx", Func, 0},
+		{"RegQueryInfoKey", Func, 0},
+		{"RegQueryValueEx", Func, 0},
+		{"RemoveDirectory", Func, 0},
+		{"Removexattr", Func, 1},
+		{"Rename", Func, 0},
+		{"Renameat", Func, 0},
+		{"Revoke", Func, 0},
+		{"Rlimit", Type, 0},
+		{"Rlimit.Cur", Field, 0},
+		{"Rlimit.Max", Field, 0},
+		{"Rmdir", Func, 0},
+		{"RouteMessage", Type, 0},
+		{"RouteMessage.Data", Field, 0},
+		{"RouteMessage.Header", Field, 0},
+		{"RouteRIB", Func, 0},
+		{"RoutingMessage", Type, 0},
+		{"RtAttr", Type, 0},
+		{"RtAttr.Len", Field, 0},
+		{"RtAttr.Type", Field, 0},
+		{"RtGenmsg", Type, 0},
+		{"RtGenmsg.Family", Field, 0},
+		{"RtMetrics", Type, 0},
+		{"RtMetrics.Expire", Field, 0},
+		{"RtMetrics.Filler", Field, 0},
+		{"RtMetrics.Hopcount", Field, 0},
+		{"RtMetrics.Locks", Field, 0},
+		{"RtMetrics.Mtu", Field, 0},
+		{"RtMetrics.Pad", Field, 3},
+		{"RtMetrics.Pksent", Field, 0},
+		{"RtMetrics.Recvpipe", Field, 0},
+		{"RtMetrics.Refcnt", Field, 2},
+		{"RtMetrics.Rtt", Field, 0},
+		{"RtMetrics.Rttvar", Field, 0},
+		{"RtMetrics.Sendpipe", Field, 0},
+		{"RtMetrics.Ssthresh", Field, 0},
+		{"RtMetrics.Weight", Field, 0},
+		{"RtMsg", Type, 0},
+		{"RtMsg.Dst_len", Field, 0},
+		{"RtMsg.Family", Field, 0},
+		{"RtMsg.Flags", Field, 0},
+		{"RtMsg.Protocol", Field, 0},
+		{"RtMsg.Scope", Field, 0},
+		{"RtMsg.Src_len", Field, 0},
+		{"RtMsg.Table", Field, 0},
+		{"RtMsg.Tos", Field, 0},
+		{"RtMsg.Type", Field, 0},
+		{"RtMsghdr", Type, 0},
+		{"RtMsghdr.Addrs", Field, 0},
+		{"RtMsghdr.Errno", Field, 0},
+		{"RtMsghdr.Flags", Field, 0},
+		{"RtMsghdr.Fmask", Field, 0},
+		{"RtMsghdr.Hdrlen", Field, 2},
+		{"RtMsghdr.Index", Field, 0},
+		{"RtMsghdr.Inits", Field, 0},
+		{"RtMsghdr.Mpls", Field, 2},
+		{"RtMsghdr.Msglen", Field, 0},
+		{"RtMsghdr.Pad_cgo_0", Field, 0},
+		{"RtMsghdr.Pad_cgo_1", Field, 2},
+		{"RtMsghdr.Pid", Field, 0},
+		{"RtMsghdr.Priority", Field, 2},
+		{"RtMsghdr.Rmx", Field, 0},
+		{"RtMsghdr.Seq", Field, 0},
+		{"RtMsghdr.Tableid", Field, 2},
+		{"RtMsghdr.Type", Field, 0},
+		{"RtMsghdr.Use", Field, 0},
+		{"RtMsghdr.Version", Field, 0},
+		{"RtNexthop", Type, 0},
+		{"RtNexthop.Flags", Field, 0},
+		{"RtNexthop.Hops", Field, 0},
+		{"RtNexthop.Ifindex", Field, 0},
+		{"RtNexthop.Len", Field, 0},
+		{"Rusage", Type, 0},
+		{"Rusage.CreationTime", Field, 0},
+		{"Rusage.ExitTime", Field, 0},
+		{"Rusage.Idrss", Field, 0},
+		{"Rusage.Inblock", Field, 0},
+		{"Rusage.Isrss", Field, 0},
+		{"Rusage.Ixrss", Field, 0},
+		{"Rusage.KernelTime", Field, 0},
+		{"Rusage.Majflt", Field, 0},
+		{"Rusage.Maxrss", Field, 0},
+		{"Rusage.Minflt", Field, 0},
+		{"Rusage.Msgrcv", Field, 0},
+		{"Rusage.Msgsnd", Field, 0},
+		{"Rusage.Nivcsw", Field, 0},
+		{"Rusage.Nsignals", Field, 0},
+		{"Rusage.Nswap", Field, 0},
+		{"Rusage.Nvcsw", Field, 0},
+		{"Rusage.Oublock", Field, 0},
+		{"Rusage.Stime", Field, 0},
+		{"Rusage.UserTime", Field, 0},
+		{"Rusage.Utime", Field, 0},
+		{"SCM_BINTIME", Const, 0},
+		{"SCM_CREDENTIALS", Const, 0},
+		{"SCM_CREDS", Const, 0},
+		{"SCM_RIGHTS", Const, 0},
+		{"SCM_TIMESTAMP", Const, 0},
+		{"SCM_TIMESTAMPING", Const, 0},
+		{"SCM_TIMESTAMPNS", Const, 0},
+		{"SCM_TIMESTAMP_MONOTONIC", Const, 0},
+		{"SHUT_RD", Const, 0},
+		{"SHUT_RDWR", Const, 0},
+		{"SHUT_WR", Const, 0},
+		{"SID", Type, 0},
+		{"SIDAndAttributes", Type, 0},
+		{"SIDAndAttributes.Attributes", Field, 0},
+		{"SIDAndAttributes.Sid", Field, 0},
+		{"SIGABRT", Const, 0},
+		{"SIGALRM", Const, 0},
+		{"SIGBUS", Const, 0},
+		{"SIGCHLD", Const, 0},
+		{"SIGCLD", Const, 0},
+		{"SIGCONT", Const, 0},
+		{"SIGEMT", Const, 0},
+		{"SIGFPE", Const, 0},
+		{"SIGHUP", Const, 0},
+		{"SIGILL", Const, 0},
+		{"SIGINFO", Const, 0},
+		{"SIGINT", Const, 0},
+		{"SIGIO", Const, 0},
+		{"SIGIOT", Const, 0},
+		{"SIGKILL", Const, 0},
+		{"SIGLIBRT", Const, 1},
+		{"SIGLWP", Const, 0},
+		{"SIGPIPE", Const, 0},
+		{"SIGPOLL", Const, 0},
+		{"SIGPROF", Const, 0},
+		{"SIGPWR", Const, 0},
+		{"SIGQUIT", Const, 0},
+		{"SIGSEGV", Const, 0},
+		{"SIGSTKFLT", Const, 0},
+		{"SIGSTOP", Const, 0},
+		{"SIGSYS", Const, 0},
+		{"SIGTERM", Const, 0},
+		{"SIGTHR", Const, 0},
+		{"SIGTRAP", Const, 0},
+		{"SIGTSTP", Const, 0},
+		{"SIGTTIN", Const, 0},
+		{"SIGTTOU", Const, 0},
+		{"SIGUNUSED", Const, 0},
+		{"SIGURG", Const, 0},
+		{"SIGUSR1", Const, 0},
+		{"SIGUSR2", Const, 0},
+		{"SIGVTALRM", Const, 0},
+		{"SIGWINCH", Const, 0},
+		{"SIGXCPU", Const, 0},
+		{"SIGXFSZ", Const, 0},
+		{"SIOCADDDLCI", Const, 0},
+		{"SIOCADDMULTI", Const, 0},
+		{"SIOCADDRT", Const, 0},
+		{"SIOCAIFADDR", Const, 0},
+		{"SIOCAIFGROUP", Const, 0},
+		{"SIOCALIFADDR", Const, 0},
+		{"SIOCARPIPLL", Const, 0},
+		{"SIOCATMARK", Const, 0},
+		{"SIOCAUTOADDR", Const, 0},
+		{"SIOCAUTONETMASK", Const, 0},
+		{"SIOCBRDGADD", Const, 1},
+		{"SIOCBRDGADDS", Const, 1},
+		{"SIOCBRDGARL", Const, 1},
+		{"SIOCBRDGDADDR", Const, 1},
+		{"SIOCBRDGDEL", Const, 1},
+		{"SIOCBRDGDELS", Const, 1},
+		{"SIOCBRDGFLUSH", Const, 1},
+		{"SIOCBRDGFRL", Const, 1},
+		{"SIOCBRDGGCACHE", Const, 1},
+		{"SIOCBRDGGFD", Const, 1},
+		{"SIOCBRDGGHT", Const, 1},
+		{"SIOCBRDGGIFFLGS", Const, 1},
+		{"SIOCBRDGGMA", Const, 1},
+		{"SIOCBRDGGPARAM", Const, 1},
+		{"SIOCBRDGGPRI", Const, 1},
+		{"SIOCBRDGGRL", Const, 1},
+		{"SIOCBRDGGSIFS", Const, 1},
+		{"SIOCBRDGGTO", Const, 1},
+		{"SIOCBRDGIFS", Const, 1},
+		{"SIOCBRDGRTS", Const, 1},
+		{"SIOCBRDGSADDR", Const, 1},
+		{"SIOCBRDGSCACHE", Const, 1},
+		{"SIOCBRDGSFD", Const, 1},
+		{"SIOCBRDGSHT", Const, 1},
+		{"SIOCBRDGSIFCOST", Const, 1},
+		{"SIOCBRDGSIFFLGS", Const, 1},
+		{"SIOCBRDGSIFPRIO", Const, 1},
+		{"SIOCBRDGSMA", Const, 1},
+		{"SIOCBRDGSPRI", Const, 1},
+		{"SIOCBRDGSPROTO", Const, 1},
+		{"SIOCBRDGSTO", Const, 1},
+		{"SIOCBRDGSTXHC", Const, 1},
+		{"SIOCDARP", Const, 0},
+		{"SIOCDELDLCI", Const, 0},
+		{"SIOCDELMULTI", Const, 0},
+		{"SIOCDELRT", Const, 0},
+		{"SIOCDEVPRIVATE", Const, 0},
+		{"SIOCDIFADDR", Const, 0},
+		{"SIOCDIFGROUP", Const, 0},
+		{"SIOCDIFPHYADDR", Const, 0},
+		{"SIOCDLIFADDR", Const, 0},
+		{"SIOCDRARP", Const, 0},
+		{"SIOCGARP", Const, 0},
+		{"SIOCGDRVSPEC", Const, 0},
+		{"SIOCGETKALIVE", Const, 1},
+		{"SIOCGETLABEL", Const, 1},
+		{"SIOCGETPFLOW", Const, 1},
+		{"SIOCGETPFSYNC", Const, 1},
+		{"SIOCGETSGCNT", Const, 0},
+		{"SIOCGETVIFCNT", Const, 0},
+		{"SIOCGETVLAN", Const, 0},
+		{"SIOCGHIWAT", Const, 0},
+		{"SIOCGIFADDR", Const, 0},
+		{"SIOCGIFADDRPREF", Const, 1},
+		{"SIOCGIFALIAS", Const, 1},
+		{"SIOCGIFALTMTU", Const, 0},
+		{"SIOCGIFASYNCMAP", Const, 0},
+		{"SIOCGIFBOND", Const, 0},
+		{"SIOCGIFBR", Const, 0},
+		{"SIOCGIFBRDADDR", Const, 0},
+		{"SIOCGIFCAP", Const, 0},
+		{"SIOCGIFCONF", Const, 0},
+		{"SIOCGIFCOUNT", Const, 0},
+		{"SIOCGIFDATA", Const, 1},
+		{"SIOCGIFDESCR", Const, 0},
+		{"SIOCGIFDEVMTU", Const, 0},
+		{"SIOCGIFDLT", Const, 1},
+		{"SIOCGIFDSTADDR", Const, 0},
+		{"SIOCGIFENCAP", Const, 0},
+		{"SIOCGIFFIB", Const, 1},
+		{"SIOCGIFFLAGS", Const, 0},
+		{"SIOCGIFGATTR", Const, 1},
+		{"SIOCGIFGENERIC", Const, 0},
+		{"SIOCGIFGMEMB", Const, 0},
+		{"SIOCGIFGROUP", Const, 0},
+		{"SIOCGIFHARDMTU", Const, 3},
+		{"SIOCGIFHWADDR", Const, 0},
+		{"SIOCGIFINDEX", Const, 0},
+		{"SIOCGIFKPI", Const, 0},
+		{"SIOCGIFMAC", Const, 0},
+		{"SIOCGIFMAP", Const, 0},
+		{"SIOCGIFMEDIA", Const, 0},
+		{"SIOCGIFMEM", Const, 0},
+		{"SIOCGIFMETRIC", Const, 0},
+		{"SIOCGIFMTU", Const, 0},
+		{"SIOCGIFNAME", Const, 0},
+		{"SIOCGIFNETMASK", Const, 0},
+		{"SIOCGIFPDSTADDR", Const, 0},
+		{"SIOCGIFPFLAGS", Const, 0},
+		{"SIOCGIFPHYS", Const, 0},
+		{"SIOCGIFPRIORITY", Const, 1},
+		{"SIOCGIFPSRCADDR", Const, 0},
+		{"SIOCGIFRDOMAIN", Const, 1},
+		{"SIOCGIFRTLABEL", Const, 1},
+		{"SIOCGIFSLAVE", Const, 0},
+		{"SIOCGIFSTATUS", Const, 0},
+		{"SIOCGIFTIMESLOT", Const, 1},
+		{"SIOCGIFTXQLEN", Const, 0},
+		{"SIOCGIFVLAN", Const, 0},
+		{"SIOCGIFWAKEFLAGS", Const, 0},
+		{"SIOCGIFXFLAGS", Const, 1},
+		{"SIOCGLIFADDR", Const, 0},
+		{"SIOCGLIFPHYADDR", Const, 0},
+		{"SIOCGLIFPHYRTABLE", Const, 1},
+		{"SIOCGLIFPHYTTL", Const, 3},
+		{"SIOCGLINKSTR", Const, 1},
+		{"SIOCGLOWAT", Const, 0},
+		{"SIOCGPGRP", Const, 0},
+		{"SIOCGPRIVATE_0", Const, 0},
+		{"SIOCGPRIVATE_1", Const, 0},
+		{"SIOCGRARP", Const, 0},
+		{"SIOCGSPPPPARAMS", Const, 3},
+		{"SIOCGSTAMP", Const, 0},
+		{"SIOCGSTAMPNS", Const, 0},
+		{"SIOCGVH", Const, 1},
+		{"SIOCGVNETID", Const, 3},
+		{"SIOCIFCREATE", Const, 0},
+		{"SIOCIFCREATE2", Const, 0},
+		{"SIOCIFDESTROY", Const, 0},
+		{"SIOCIFGCLONERS", Const, 0},
+		{"SIOCINITIFADDR", Const, 1},
+		{"SIOCPROTOPRIVATE", Const, 0},
+		{"SIOCRSLVMULTI", Const, 0},
+		{"SIOCRTMSG", Const, 0},
+		{"SIOCSARP", Const, 0},
+		{"SIOCSDRVSPEC", Const, 0},
+		{"SIOCSETKALIVE", Const, 1},
+		{"SIOCSETLABEL", Const, 1},
+		{"SIOCSETPFLOW", Const, 1},
+		{"SIOCSETPFSYNC", Const, 1},
+		{"SIOCSETVLAN", Const, 0},
+		{"SIOCSHIWAT", Const, 0},
+		{"SIOCSIFADDR", Const, 0},
+		{"SIOCSIFADDRPREF", Const, 1},
+		{"SIOCSIFALTMTU", Const, 0},
+		{"SIOCSIFASYNCMAP", Const, 0},
+		{"SIOCSIFBOND", Const, 0},
+		{"SIOCSIFBR", Const, 0},
+		{"SIOCSIFBRDADDR", Const, 0},
+		{"SIOCSIFCAP", Const, 0},
+		{"SIOCSIFDESCR", Const, 0},
+		{"SIOCSIFDSTADDR", Const, 0},
+		{"SIOCSIFENCAP", Const, 0},
+		{"SIOCSIFFIB", Const, 1},
+		{"SIOCSIFFLAGS", Const, 0},
+		{"SIOCSIFGATTR", Const, 1},
+		{"SIOCSIFGENERIC", Const, 0},
+		{"SIOCSIFHWADDR", Const, 0},
+		{"SIOCSIFHWBROADCAST", Const, 0},
+		{"SIOCSIFKPI", Const, 0},
+		{"SIOCSIFLINK", Const, 0},
+		{"SIOCSIFLLADDR", Const, 0},
+		{"SIOCSIFMAC", Const, 0},
+		{"SIOCSIFMAP", Const, 0},
+		{"SIOCSIFMEDIA", Const, 0},
+		{"SIOCSIFMEM", Const, 0},
+		{"SIOCSIFMETRIC", Const, 0},
+		{"SIOCSIFMTU", Const, 0},
+		{"SIOCSIFNAME", Const, 0},
+		{"SIOCSIFNETMASK", Const, 0},
+		{"SIOCSIFPFLAGS", Const, 0},
+		{"SIOCSIFPHYADDR", Const, 0},
+		{"SIOCSIFPHYS", Const, 0},
+		{"SIOCSIFPRIORITY", Const, 1},
+		{"SIOCSIFRDOMAIN", Const, 1},
+		{"SIOCSIFRTLABEL", Const, 1},
+		{"SIOCSIFRVNET", Const, 0},
+		{"SIOCSIFSLAVE", Const, 0},
+		{"SIOCSIFTIMESLOT", Const, 1},
+		{"SIOCSIFTXQLEN", Const, 0},
+		{"SIOCSIFVLAN", Const, 0},
+		{"SIOCSIFVNET", Const, 0},
+		{"SIOCSIFXFLAGS", Const, 1},
+		{"SIOCSLIFPHYADDR", Const, 0},
+		{"SIOCSLIFPHYRTABLE", Const, 1},
+		{"SIOCSLIFPHYTTL", Const, 3},
+		{"SIOCSLINKSTR", Const, 1},
+		{"SIOCSLOWAT", Const, 0},
+		{"SIOCSPGRP", Const, 0},
+		{"SIOCSRARP", Const, 0},
+		{"SIOCSSPPPPARAMS", Const, 3},
+		{"SIOCSVH", Const, 1},
+		{"SIOCSVNETID", Const, 3},
+		{"SIOCZIFDATA", Const, 1},
+		{"SIO_GET_EXTENSION_FUNCTION_POINTER", Const, 1},
+		{"SIO_GET_INTERFACE_LIST", Const, 0},
+		{"SIO_KEEPALIVE_VALS", Const, 3},
+		{"SIO_UDP_CONNRESET", Const, 4},
+		{"SOCK_CLOEXEC", Const, 0},
+		{"SOCK_DCCP", Const, 0},
+		{"SOCK_DGRAM", Const, 0},
+		{"SOCK_FLAGS_MASK", Const, 1},
+		{"SOCK_MAXADDRLEN", Const, 0},
+		{"SOCK_NONBLOCK", Const, 0},
+		{"SOCK_NOSIGPIPE", Const, 1},
+		{"SOCK_PACKET", Const, 0},
+		{"SOCK_RAW", Const, 0},
+		{"SOCK_RDM", Const, 0},
+		{"SOCK_SEQPACKET", Const, 0},
+		{"SOCK_STREAM", Const, 0},
+		{"SOL_AAL", Const, 0},
+		{"SOL_ATM", Const, 0},
+		{"SOL_DECNET", Const, 0},
+		{"SOL_ICMPV6", Const, 0},
+		{"SOL_IP", Const, 0},
+		{"SOL_IPV6", Const, 0},
+		{"SOL_IRDA", Const, 0},
+		{"SOL_PACKET", Const, 0},
+		{"SOL_RAW", Const, 0},
+		{"SOL_SOCKET", Const, 0},
+		{"SOL_TCP", Const, 0},
+		{"SOL_X25", Const, 0},
+		{"SOMAXCONN", Const, 0},
+		{"SO_ACCEPTCONN", Const, 0},
+		{"SO_ACCEPTFILTER", Const, 0},
+		{"SO_ATTACH_FILTER", Const, 0},
+		{"SO_BINDANY", Const, 1},
+		{"SO_BINDTODEVICE", Const, 0},
+		{"SO_BINTIME", Const, 0},
+		{"SO_BROADCAST", Const, 0},
+		{"SO_BSDCOMPAT", Const, 0},
+		{"SO_DEBUG", Const, 0},
+		{"SO_DETACH_FILTER", Const, 0},
+		{"SO_DOMAIN", Const, 0},
+		{"SO_DONTROUTE", Const, 0},
+		{"SO_DONTTRUNC", Const, 0},
+		{"SO_ERROR", Const, 0},
+		{"SO_KEEPALIVE", Const, 0},
+		{"SO_LABEL", Const, 0},
+		{"SO_LINGER", Const, 0},
+		{"SO_LINGER_SEC", Const, 0},
+		{"SO_LISTENINCQLEN", Const, 0},
+		{"SO_LISTENQLEN", Const, 0},
+		{"SO_LISTENQLIMIT", Const, 0},
+		{"SO_MARK", Const, 0},
+		{"SO_NETPROC", Const, 1},
+		{"SO_NKE", Const, 0},
+		{"SO_NOADDRERR", Const, 0},
+		{"SO_NOHEADER", Const, 1},
+		{"SO_NOSIGPIPE", Const, 0},
+		{"SO_NOTIFYCONFLICT", Const, 0},
+		{"SO_NO_CHECK", Const, 0},
+		{"SO_NO_DDP", Const, 0},
+		{"SO_NO_OFFLOAD", Const, 0},
+		{"SO_NP_EXTENSIONS", Const, 0},
+		{"SO_NREAD", Const, 0},
+		{"SO_NUMRCVPKT", Const, 16},
+		{"SO_NWRITE", Const, 0},
+		{"SO_OOBINLINE", Const, 0},
+		{"SO_OVERFLOWED", Const, 1},
+		{"SO_PASSCRED", Const, 0},
+		{"SO_PASSSEC", Const, 0},
+		{"SO_PEERCRED", Const, 0},
+		{"SO_PEERLABEL", Const, 0},
+		{"SO_PEERNAME", Const, 0},
+		{"SO_PEERSEC", Const, 0},
+		{"SO_PRIORITY", Const, 0},
+		{"SO_PROTOCOL", Const, 0},
+		{"SO_PROTOTYPE", Const, 1},
+		{"SO_RANDOMPORT", Const, 0},
+		{"SO_RCVBUF", Const, 0},
+		{"SO_RCVBUFFORCE", Const, 0},
+		{"SO_RCVLOWAT", Const, 0},
+		{"SO_RCVTIMEO", Const, 0},
+		{"SO_RESTRICTIONS", Const, 0},
+		{"SO_RESTRICT_DENYIN", Const, 0},
+		{"SO_RESTRICT_DENYOUT", Const, 0},
+		{"SO_RESTRICT_DENYSET", Const, 0},
+		{"SO_REUSEADDR", Const, 0},
+		{"SO_REUSEPORT", Const, 0},
+		{"SO_REUSESHAREUID", Const, 0},
+		{"SO_RTABLE", Const, 1},
+		{"SO_RXQ_OVFL", Const, 0},
+		{"SO_SECURITY_AUTHENTICATION", Const, 0},
+		{"SO_SECURITY_ENCRYPTION_NETWORK", Const, 0},
+		{"SO_SECURITY_ENCRYPTION_TRANSPORT", Const, 0},
+		{"SO_SETFIB", Const, 0},
+		{"SO_SNDBUF", Const, 0},
+		{"SO_SNDBUFFORCE", Const, 0},
+		{"SO_SNDLOWAT", Const, 0},
+		{"SO_SNDTIMEO", Const, 0},
+		{"SO_SPLICE", Const, 1},
+		{"SO_TIMESTAMP", Const, 0},
+		{"SO_TIMESTAMPING", Const, 0},
+		{"SO_TIMESTAMPNS", Const, 0},
+		{"SO_TIMESTAMP_MONOTONIC", Const, 0},
+		{"SO_TYPE", Const, 0},
+		{"SO_UPCALLCLOSEWAIT", Const, 0},
+		{"SO_UPDATE_ACCEPT_CONTEXT", Const, 0},
+		{"SO_UPDATE_CONNECT_CONTEXT", Const, 1},
+		{"SO_USELOOPBACK", Const, 0},
+		{"SO_USER_COOKIE", Const, 1},
+		{"SO_VENDOR", Const, 3},
+		{"SO_WANTMORE", Const, 0},
+		{"SO_WANTOOBFLAG", Const, 0},
+		{"SSLExtraCertChainPolicyPara", Type, 0},
+		{"SSLExtraCertChainPolicyPara.AuthType", Field, 0},
+		{"SSLExtraCertChainPolicyPara.Checks", Field, 0},
+		{"SSLExtraCertChainPolicyPara.ServerName", Field, 0},
+		{"SSLExtraCertChainPolicyPara.Size", Field, 0},
+		{"STANDARD_RIGHTS_ALL", Const, 0},
+		{"STANDARD_RIGHTS_EXECUTE", Const, 0},
+		{"STANDARD_RIGHTS_READ", Const, 0},
+		{"STANDARD_RIGHTS_REQUIRED", Const, 0},
+		{"STANDARD_RIGHTS_WRITE", Const, 0},
+		{"STARTF_USESHOWWINDOW", Const, 0},
+		{"STARTF_USESTDHANDLES", Const, 0},
+		{"STD_ERROR_HANDLE", Const, 0},
+		{"STD_INPUT_HANDLE", Const, 0},
+		{"STD_OUTPUT_HANDLE", Const, 0},
+		{"SUBLANG_ENGLISH_US", Const, 0},
+		{"SW_FORCEMINIMIZE", Const, 0},
+		{"SW_HIDE", Const, 0},
+		{"SW_MAXIMIZE", Const, 0},
+		{"SW_MINIMIZE", Const, 0},
+		{"SW_NORMAL", Const, 0},
+		{"SW_RESTORE", Const, 0},
+		{"SW_SHOW", Const, 0},
+		{"SW_SHOWDEFAULT", Const, 0},
+		{"SW_SHOWMAXIMIZED", Const, 0},
+		{"SW_SHOWMINIMIZED", Const, 0},
+		{"SW_SHOWMINNOACTIVE", Const, 0},
+		{"SW_SHOWNA", Const, 0},
+		{"SW_SHOWNOACTIVATE", Const, 0},
+		{"SW_SHOWNORMAL", Const, 0},
+		{"SYMBOLIC_LINK_FLAG_DIRECTORY", Const, 4},
+		{"SYNCHRONIZE", Const, 0},
+		{"SYSCTL_VERSION", Const, 1},
+		{"SYSCTL_VERS_0", Const, 1},
+		{"SYSCTL_VERS_1", Const, 1},
+		{"SYSCTL_VERS_MASK", Const, 1},
+		{"SYS_ABORT2", Const, 0},
+		{"SYS_ACCEPT", Const, 0},
+		{"SYS_ACCEPT4", Const, 0},
+		{"SYS_ACCEPT_NOCANCEL", Const, 0},
+		{"SYS_ACCESS", Const, 0},
+		{"SYS_ACCESS_EXTENDED", Const, 0},
+		{"SYS_ACCT", Const, 0},
+		{"SYS_ADD_KEY", Const, 0},
+		{"SYS_ADD_PROFIL", Const, 0},
+		{"SYS_ADJFREQ", Const, 1},
+		{"SYS_ADJTIME", Const, 0},
+		{"SYS_ADJTIMEX", Const, 0},
+		{"SYS_AFS_SYSCALL", Const, 0},
+		{"SYS_AIO_CANCEL", Const, 0},
+		{"SYS_AIO_ERROR", Const, 0},
+		{"SYS_AIO_FSYNC", Const, 0},
+		{"SYS_AIO_MLOCK", Const, 14},
+		{"SYS_AIO_READ", Const, 0},
+		{"SYS_AIO_RETURN", Const, 0},
+		{"SYS_AIO_SUSPEND", Const, 0},
+		{"SYS_AIO_SUSPEND_NOCANCEL", Const, 0},
+		{"SYS_AIO_WAITCOMPLETE", Const, 14},
+		{"SYS_AIO_WRITE", Const, 0},
+		{"SYS_ALARM", Const, 0},
+		{"SYS_ARCH_PRCTL", Const, 0},
+		{"SYS_ARM_FADVISE64_64", Const, 0},
+		{"SYS_ARM_SYNC_FILE_RANGE", Const, 0},
+		{"SYS_ATGETMSG", Const, 0},
+		{"SYS_ATPGETREQ", Const, 0},
+		{"SYS_ATPGETRSP", Const, 0},
+		{"SYS_ATPSNDREQ", Const, 0},
+		{"SYS_ATPSNDRSP", Const, 0},
+		{"SYS_ATPUTMSG", Const, 0},
+		{"SYS_ATSOCKET", Const, 0},
+		{"SYS_AUDIT", Const, 0},
+		{"SYS_AUDITCTL", Const, 0},
+		{"SYS_AUDITON", Const, 0},
+		{"SYS_AUDIT_SESSION_JOIN", Const, 0},
+		{"SYS_AUDIT_SESSION_PORT", Const, 0},
+		{"SYS_AUDIT_SESSION_SELF", Const, 0},
+		{"SYS_BDFLUSH", Const, 0},
+		{"SYS_BIND", Const, 0},
+		{"SYS_BINDAT", Const, 3},
+		{"SYS_BREAK", Const, 0},
+		{"SYS_BRK", Const, 0},
+		{"SYS_BSDTHREAD_CREATE", Const, 0},
+		{"SYS_BSDTHREAD_REGISTER", Const, 0},
+		{"SYS_BSDTHREAD_TERMINATE", Const, 0},
+		{"SYS_CAPGET", Const, 0},
+		{"SYS_CAPSET", Const, 0},
+		{"SYS_CAP_ENTER", Const, 0},
+		{"SYS_CAP_FCNTLS_GET", Const, 1},
+		{"SYS_CAP_FCNTLS_LIMIT", Const, 1},
+		{"SYS_CAP_GETMODE", Const, 0},
+		{"SYS_CAP_GETRIGHTS", Const, 0},
+		{"SYS_CAP_IOCTLS_GET", Const, 1},
+		{"SYS_CAP_IOCTLS_LIMIT", Const, 1},
+		{"SYS_CAP_NEW", Const, 0},
+		{"SYS_CAP_RIGHTS_GET", Const, 1},
+		{"SYS_CAP_RIGHTS_LIMIT", Const, 1},
+		{"SYS_CHDIR", Const, 0},
+		{"SYS_CHFLAGS", Const, 0},
+		{"SYS_CHFLAGSAT", Const, 3},
+		{"SYS_CHMOD", Const, 0},
+		{"SYS_CHMOD_EXTENDED", Const, 0},
+		{"SYS_CHOWN", Const, 0},
+		{"SYS_CHOWN32", Const, 0},
+		{"SYS_CHROOT", Const, 0},
+		{"SYS_CHUD", Const, 0},
+		{"SYS_CLOCK_ADJTIME", Const, 0},
+		{"SYS_CLOCK_GETCPUCLOCKID2", Const, 1},
+		{"SYS_CLOCK_GETRES", Const, 0},
+		{"SYS_CLOCK_GETTIME", Const, 0},
+		{"SYS_CLOCK_NANOSLEEP", Const, 0},
+		{"SYS_CLOCK_SETTIME", Const, 0},
+		{"SYS_CLONE", Const, 0},
+		{"SYS_CLOSE", Const, 0},
+		{"SYS_CLOSEFROM", Const, 0},
+		{"SYS_CLOSE_NOCANCEL", Const, 0},
+		{"SYS_CONNECT", Const, 0},
+		{"SYS_CONNECTAT", Const, 3},
+		{"SYS_CONNECT_NOCANCEL", Const, 0},
+		{"SYS_COPYFILE", Const, 0},
+		{"SYS_CPUSET", Const, 0},
+		{"SYS_CPUSET_GETAFFINITY", Const, 0},
+		{"SYS_CPUSET_GETID", Const, 0},
+		{"SYS_CPUSET_SETAFFINITY", Const, 0},
+		{"SYS_CPUSET_SETID", Const, 0},
+		{"SYS_CREAT", Const, 0},
+		{"SYS_CREATE_MODULE", Const, 0},
+		{"SYS_CSOPS", Const, 0},
+		{"SYS_CSOPS_AUDITTOKEN", Const, 16},
+		{"SYS_DELETE", Const, 0},
+		{"SYS_DELETE_MODULE", Const, 0},
+		{"SYS_DUP", Const, 0},
+		{"SYS_DUP2", Const, 0},
+		{"SYS_DUP3", Const, 0},
+		{"SYS_EACCESS", Const, 0},
+		{"SYS_EPOLL_CREATE", Const, 0},
+		{"SYS_EPOLL_CREATE1", Const, 0},
+		{"SYS_EPOLL_CTL", Const, 0},
+		{"SYS_EPOLL_CTL_OLD", Const, 0},
+		{"SYS_EPOLL_PWAIT", Const, 0},
+		{"SYS_EPOLL_WAIT", Const, 0},
+		{"SYS_EPOLL_WAIT_OLD", Const, 0},
+		{"SYS_EVENTFD", Const, 0},
+		{"SYS_EVENTFD2", Const, 0},
+		{"SYS_EXCHANGEDATA", Const, 0},
+		{"SYS_EXECVE", Const, 0},
+		{"SYS_EXIT", Const, 0},
+		{"SYS_EXIT_GROUP", Const, 0},
+		{"SYS_EXTATTRCTL", Const, 0},
+		{"SYS_EXTATTR_DELETE_FD", Const, 0},
+		{"SYS_EXTATTR_DELETE_FILE", Const, 0},
+		{"SYS_EXTATTR_DELETE_LINK", Const, 0},
+		{"SYS_EXTATTR_GET_FD", Const, 0},
+		{"SYS_EXTATTR_GET_FILE", Const, 0},
+		{"SYS_EXTATTR_GET_LINK", Const, 0},
+		{"SYS_EXTATTR_LIST_FD", Const, 0},
+		{"SYS_EXTATTR_LIST_FILE", Const, 0},
+		{"SYS_EXTATTR_LIST_LINK", Const, 0},
+		{"SYS_EXTATTR_SET_FD", Const, 0},
+		{"SYS_EXTATTR_SET_FILE", Const, 0},
+		{"SYS_EXTATTR_SET_LINK", Const, 0},
+		{"SYS_FACCESSAT", Const, 0},
+		{"SYS_FADVISE64", Const, 0},
+		{"SYS_FADVISE64_64", Const, 0},
+		{"SYS_FALLOCATE", Const, 0},
+		{"SYS_FANOTIFY_INIT", Const, 0},
+		{"SYS_FANOTIFY_MARK", Const, 0},
+		{"SYS_FCHDIR", Const, 0},
+		{"SYS_FCHFLAGS", Const, 0},
+		{"SYS_FCHMOD", Const, 0},
+		{"SYS_FCHMODAT", Const, 0},
+		{"SYS_FCHMOD_EXTENDED", Const, 0},
+		{"SYS_FCHOWN", Const, 0},
+		{"SYS_FCHOWN32", Const, 0},
+		{"SYS_FCHOWNAT", Const, 0},
+		{"SYS_FCHROOT", Const, 1},
+		{"SYS_FCNTL", Const, 0},
+		{"SYS_FCNTL64", Const, 0},
+		{"SYS_FCNTL_NOCANCEL", Const, 0},
+		{"SYS_FDATASYNC", Const, 0},
+		{"SYS_FEXECVE", Const, 0},
+		{"SYS_FFCLOCK_GETCOUNTER", Const, 0},
+		{"SYS_FFCLOCK_GETESTIMATE", Const, 0},
+		{"SYS_FFCLOCK_SETESTIMATE", Const, 0},
+		{"SYS_FFSCTL", Const, 0},
+		{"SYS_FGETATTRLIST", Const, 0},
+		{"SYS_FGETXATTR", Const, 0},
+		{"SYS_FHOPEN", Const, 0},
+		{"SYS_FHSTAT", Const, 0},
+		{"SYS_FHSTATFS", Const, 0},
+		{"SYS_FILEPORT_MAKEFD", Const, 0},
+		{"SYS_FILEPORT_MAKEPORT", Const, 0},
+		{"SYS_FKTRACE", Const, 1},
+		{"SYS_FLISTXATTR", Const, 0},
+		{"SYS_FLOCK", Const, 0},
+		{"SYS_FORK", Const, 0},
+		{"SYS_FPATHCONF", Const, 0},
+		{"SYS_FREEBSD6_FTRUNCATE", Const, 0},
+		{"SYS_FREEBSD6_LSEEK", Const, 0},
+		{"SYS_FREEBSD6_MMAP", Const, 0},
+		{"SYS_FREEBSD6_PREAD", Const, 0},
+		{"SYS_FREEBSD6_PWRITE", Const, 0},
+		{"SYS_FREEBSD6_TRUNCATE", Const, 0},
+		{"SYS_FREMOVEXATTR", Const, 0},
+		{"SYS_FSCTL", Const, 0},
+		{"SYS_FSETATTRLIST", Const, 0},
+		{"SYS_FSETXATTR", Const, 0},
+		{"SYS_FSGETPATH", Const, 0},
+		{"SYS_FSTAT", Const, 0},
+		{"SYS_FSTAT64", Const, 0},
+		{"SYS_FSTAT64_EXTENDED", Const, 0},
+		{"SYS_FSTATAT", Const, 0},
+		{"SYS_FSTATAT64", Const, 0},
+		{"SYS_FSTATFS", Const, 0},
+		{"SYS_FSTATFS64", Const, 0},
+		{"SYS_FSTATV", Const, 0},
+		{"SYS_FSTATVFS1", Const, 1},
+		{"SYS_FSTAT_EXTENDED", Const, 0},
+		{"SYS_FSYNC", Const, 0},
+		{"SYS_FSYNC_NOCANCEL", Const, 0},
+		{"SYS_FSYNC_RANGE", Const, 1},
+		{"SYS_FTIME", Const, 0},
+		{"SYS_FTRUNCATE", Const, 0},
+		{"SYS_FTRUNCATE64", Const, 0},
+		{"SYS_FUTEX", Const, 0},
+		{"SYS_FUTIMENS", Const, 1},
+		{"SYS_FUTIMES", Const, 0},
+		{"SYS_FUTIMESAT", Const, 0},
+		{"SYS_GETATTRLIST", Const, 0},
+		{"SYS_GETAUDIT", Const, 0},
+		{"SYS_GETAUDIT_ADDR", Const, 0},
+		{"SYS_GETAUID", Const, 0},
+		{"SYS_GETCONTEXT", Const, 0},
+		{"SYS_GETCPU", Const, 0},
+		{"SYS_GETCWD", Const, 0},
+		{"SYS_GETDENTS", Const, 0},
+		{"SYS_GETDENTS64", Const, 0},
+		{"SYS_GETDIRENTRIES", Const, 0},
+		{"SYS_GETDIRENTRIES64", Const, 0},
+		{"SYS_GETDIRENTRIESATTR", Const, 0},
+		{"SYS_GETDTABLECOUNT", Const, 1},
+		{"SYS_GETDTABLESIZE", Const, 0},
+		{"SYS_GETEGID", Const, 0},
+		{"SYS_GETEGID32", Const, 0},
+		{"SYS_GETEUID", Const, 0},
+		{"SYS_GETEUID32", Const, 0},
+		{"SYS_GETFH", Const, 0},
+		{"SYS_GETFSSTAT", Const, 0},
+		{"SYS_GETFSSTAT64", Const, 0},
+		{"SYS_GETGID", Const, 0},
+		{"SYS_GETGID32", Const, 0},
+		{"SYS_GETGROUPS", Const, 0},
+		{"SYS_GETGROUPS32", Const, 0},
+		{"SYS_GETHOSTUUID", Const, 0},
+		{"SYS_GETITIMER", Const, 0},
+		{"SYS_GETLCID", Const, 0},
+		{"SYS_GETLOGIN", Const, 0},
+		{"SYS_GETLOGINCLASS", Const, 0},
+		{"SYS_GETPEERNAME", Const, 0},
+		{"SYS_GETPGID", Const, 0},
+		{"SYS_GETPGRP", Const, 0},
+		{"SYS_GETPID", Const, 0},
+		{"SYS_GETPMSG", Const, 0},
+		{"SYS_GETPPID", Const, 0},
+		{"SYS_GETPRIORITY", Const, 0},
+		{"SYS_GETRESGID", Const, 0},
+		{"SYS_GETRESGID32", Const, 0},
+		{"SYS_GETRESUID", Const, 0},
+		{"SYS_GETRESUID32", Const, 0},
+		{"SYS_GETRLIMIT", Const, 0},
+		{"SYS_GETRTABLE", Const, 1},
+		{"SYS_GETRUSAGE", Const, 0},
+		{"SYS_GETSGROUPS", Const, 0},
+		{"SYS_GETSID", Const, 0},
+		{"SYS_GETSOCKNAME", Const, 0},
+		{"SYS_GETSOCKOPT", Const, 0},
+		{"SYS_GETTHRID", Const, 1},
+		{"SYS_GETTID", Const, 0},
+		{"SYS_GETTIMEOFDAY", Const, 0},
+		{"SYS_GETUID", Const, 0},
+		{"SYS_GETUID32", Const, 0},
+		{"SYS_GETVFSSTAT", Const, 1},
+		{"SYS_GETWGROUPS", Const, 0},
+		{"SYS_GETXATTR", Const, 0},
+		{"SYS_GET_KERNEL_SYMS", Const, 0},
+		{"SYS_GET_MEMPOLICY", Const, 0},
+		{"SYS_GET_ROBUST_LIST", Const, 0},
+		{"SYS_GET_THREAD_AREA", Const, 0},
+		{"SYS_GSSD_SYSCALL", Const, 14},
+		{"SYS_GTTY", Const, 0},
+		{"SYS_IDENTITYSVC", Const, 0},
+		{"SYS_IDLE", Const, 0},
+		{"SYS_INITGROUPS", Const, 0},
+		{"SYS_INIT_MODULE", Const, 0},
+		{"SYS_INOTIFY_ADD_WATCH", Const, 0},
+		{"SYS_INOTIFY_INIT", Const, 0},
+		{"SYS_INOTIFY_INIT1", Const, 0},
+		{"SYS_INOTIFY_RM_WATCH", Const, 0},
+		{"SYS_IOCTL", Const, 0},
+		{"SYS_IOPERM", Const, 0},
+		{"SYS_IOPL", Const, 0},
+		{"SYS_IOPOLICYSYS", Const, 0},
+		{"SYS_IOPRIO_GET", Const, 0},
+		{"SYS_IOPRIO_SET", Const, 0},
+		{"SYS_IO_CANCEL", Const, 0},
+		{"SYS_IO_DESTROY", Const, 0},
+		{"SYS_IO_GETEVENTS", Const, 0},
+		{"SYS_IO_SETUP", Const, 0},
+		{"SYS_IO_SUBMIT", Const, 0},
+		{"SYS_IPC", Const, 0},
+		{"SYS_ISSETUGID", Const, 0},
+		{"SYS_JAIL", Const, 0},
+		{"SYS_JAIL_ATTACH", Const, 0},
+		{"SYS_JAIL_GET", Const, 0},
+		{"SYS_JAIL_REMOVE", Const, 0},
+		{"SYS_JAIL_SET", Const, 0},
+		{"SYS_KAS_INFO", Const, 16},
+		{"SYS_KDEBUG_TRACE", Const, 0},
+		{"SYS_KENV", Const, 0},
+		{"SYS_KEVENT", Const, 0},
+		{"SYS_KEVENT64", Const, 0},
+		{"SYS_KEXEC_LOAD", Const, 0},
+		{"SYS_KEYCTL", Const, 0},
+		{"SYS_KILL", Const, 0},
+		{"SYS_KLDFIND", Const, 0},
+		{"SYS_KLDFIRSTMOD", Const, 0},
+		{"SYS_KLDLOAD", Const, 0},
+		{"SYS_KLDNEXT", Const, 0},
+		{"SYS_KLDSTAT", Const, 0},
+		{"SYS_KLDSYM", Const, 0},
+		{"SYS_KLDUNLOAD", Const, 0},
+		{"SYS_KLDUNLOADF", Const, 0},
+		{"SYS_KMQ_NOTIFY", Const, 14},
+		{"SYS_KMQ_OPEN", Const, 14},
+		{"SYS_KMQ_SETATTR", Const, 14},
+		{"SYS_KMQ_TIMEDRECEIVE", Const, 14},
+		{"SYS_KMQ_TIMEDSEND", Const, 14},
+		{"SYS_KMQ_UNLINK", Const, 14},
+		{"SYS_KQUEUE", Const, 0},
+		{"SYS_KQUEUE1", Const, 1},
+		{"SYS_KSEM_CLOSE", Const, 14},
+		{"SYS_KSEM_DESTROY", Const, 14},
+		{"SYS_KSEM_GETVALUE", Const, 14},
+		{"SYS_KSEM_INIT", Const, 14},
+		{"SYS_KSEM_OPEN", Const, 14},
+		{"SYS_KSEM_POST", Const, 14},
+		{"SYS_KSEM_TIMEDWAIT", Const, 14},
+		{"SYS_KSEM_TRYWAIT", Const, 14},
+		{"SYS_KSEM_UNLINK", Const, 14},
+		{"SYS_KSEM_WAIT", Const, 14},
+		{"SYS_KTIMER_CREATE", Const, 0},
+		{"SYS_KTIMER_DELETE", Const, 0},
+		{"SYS_KTIMER_GETOVERRUN", Const, 0},
+		{"SYS_KTIMER_GETTIME", Const, 0},
+		{"SYS_KTIMER_SETTIME", Const, 0},
+		{"SYS_KTRACE", Const, 0},
+		{"SYS_LCHFLAGS", Const, 0},
+		{"SYS_LCHMOD", Const, 0},
+		{"SYS_LCHOWN", Const, 0},
+		{"SYS_LCHOWN32", Const, 0},
+		{"SYS_LEDGER", Const, 16},
+		{"SYS_LGETFH", Const, 0},
+		{"SYS_LGETXATTR", Const, 0},
+		{"SYS_LINK", Const, 0},
+		{"SYS_LINKAT", Const, 0},
+		{"SYS_LIO_LISTIO", Const, 0},
+		{"SYS_LISTEN", Const, 0},
+		{"SYS_LISTXATTR", Const, 0},
+		{"SYS_LLISTXATTR", Const, 0},
+		{"SYS_LOCK", Const, 0},
+		{"SYS_LOOKUP_DCOOKIE", Const, 0},
+		{"SYS_LPATHCONF", Const, 0},
+		{"SYS_LREMOVEXATTR", Const, 0},
+		{"SYS_LSEEK", Const, 0},
+		{"SYS_LSETXATTR", Const, 0},
+		{"SYS_LSTAT", Const, 0},
+		{"SYS_LSTAT64", Const, 0},
+		{"SYS_LSTAT64_EXTENDED", Const, 0},
+		{"SYS_LSTATV", Const, 0},
+		{"SYS_LSTAT_EXTENDED", Const, 0},
+		{"SYS_LUTIMES", Const, 0},
+		{"SYS_MAC_SYSCALL", Const, 0},
+		{"SYS_MADVISE", Const, 0},
+		{"SYS_MADVISE1", Const, 0},
+		{"SYS_MAXSYSCALL", Const, 0},
+		{"SYS_MBIND", Const, 0},
+		{"SYS_MIGRATE_PAGES", Const, 0},
+		{"SYS_MINCORE", Const, 0},
+		{"SYS_MINHERIT", Const, 0},
+		{"SYS_MKCOMPLEX", Const, 0},
+		{"SYS_MKDIR", Const, 0},
+		{"SYS_MKDIRAT", Const, 0},
+		{"SYS_MKDIR_EXTENDED", Const, 0},
+		{"SYS_MKFIFO", Const, 0},
+		{"SYS_MKFIFOAT", Const, 0},
+		{"SYS_MKFIFO_EXTENDED", Const, 0},
+		{"SYS_MKNOD", Const, 0},
+		{"SYS_MKNODAT", Const, 0},
+		{"SYS_MLOCK", Const, 0},
+		{"SYS_MLOCKALL", Const, 0},
+		{"SYS_MMAP", Const, 0},
+		{"SYS_MMAP2", Const, 0},
+		{"SYS_MODCTL", Const, 1},
+		{"SYS_MODFIND", Const, 0},
+		{"SYS_MODFNEXT", Const, 0},
+		{"SYS_MODIFY_LDT", Const, 0},
+		{"SYS_MODNEXT", Const, 0},
+		{"SYS_MODSTAT", Const, 0},
+		{"SYS_MODWATCH", Const, 0},
+		{"SYS_MOUNT", Const, 0},
+		{"SYS_MOVE_PAGES", Const, 0},
+		{"SYS_MPROTECT", Const, 0},
+		{"SYS_MPX", Const, 0},
+		{"SYS_MQUERY", Const, 1},
+		{"SYS_MQ_GETSETATTR", Const, 0},
+		{"SYS_MQ_NOTIFY", Const, 0},
+		{"SYS_MQ_OPEN", Const, 0},
+		{"SYS_MQ_TIMEDRECEIVE", Const, 0},
+		{"SYS_MQ_TIMEDSEND", Const, 0},
+		{"SYS_MQ_UNLINK", Const, 0},
+		{"SYS_MREMAP", Const, 0},
+		{"SYS_MSGCTL", Const, 0},
+		{"SYS_MSGGET", Const, 0},
+		{"SYS_MSGRCV", Const, 0},
+		{"SYS_MSGRCV_NOCANCEL", Const, 0},
+		{"SYS_MSGSND", Const, 0},
+		{"SYS_MSGSND_NOCANCEL", Const, 0},
+		{"SYS_MSGSYS", Const, 0},
+		{"SYS_MSYNC", Const, 0},
+		{"SYS_MSYNC_NOCANCEL", Const, 0},
+		{"SYS_MUNLOCK", Const, 0},
+		{"SYS_MUNLOCKALL", Const, 0},
+		{"SYS_MUNMAP", Const, 0},
+		{"SYS_NAME_TO_HANDLE_AT", Const, 0},
+		{"SYS_NANOSLEEP", Const, 0},
+		{"SYS_NEWFSTATAT", Const, 0},
+		{"SYS_NFSCLNT", Const, 0},
+		{"SYS_NFSSERVCTL", Const, 0},
+		{"SYS_NFSSVC", Const, 0},
+		{"SYS_NFSTAT", Const, 0},
+		{"SYS_NICE", Const, 0},
+		{"SYS_NLM_SYSCALL", Const, 14},
+		{"SYS_NLSTAT", Const, 0},
+		{"SYS_NMOUNT", Const, 0},
+		{"SYS_NSTAT", Const, 0},
+		{"SYS_NTP_ADJTIME", Const, 0},
+		{"SYS_NTP_GETTIME", Const, 0},
+		{"SYS_NUMA_GETAFFINITY", Const, 14},
+		{"SYS_NUMA_SETAFFINITY", Const, 14},
+		{"SYS_OABI_SYSCALL_BASE", Const, 0},
+		{"SYS_OBREAK", Const, 0},
+		{"SYS_OLDFSTAT", Const, 0},
+		{"SYS_OLDLSTAT", Const, 0},
+		{"SYS_OLDOLDUNAME", Const, 0},
+		{"SYS_OLDSTAT", Const, 0},
+		{"SYS_OLDUNAME", Const, 0},
+		{"SYS_OPEN", Const, 0},
+		{"SYS_OPENAT", Const, 0},
+		{"SYS_OPENBSD_POLL", Const, 0},
+		{"SYS_OPEN_BY_HANDLE_AT", Const, 0},
+		{"SYS_OPEN_DPROTECTED_NP", Const, 16},
+		{"SYS_OPEN_EXTENDED", Const, 0},
+		{"SYS_OPEN_NOCANCEL", Const, 0},
+		{"SYS_OVADVISE", Const, 0},
+		{"SYS_PACCEPT", Const, 1},
+		{"SYS_PATHCONF", Const, 0},
+		{"SYS_PAUSE", Const, 0},
+		{"SYS_PCICONFIG_IOBASE", Const, 0},
+		{"SYS_PCICONFIG_READ", Const, 0},
+		{"SYS_PCICONFIG_WRITE", Const, 0},
+		{"SYS_PDFORK", Const, 0},
+		{"SYS_PDGETPID", Const, 0},
+		{"SYS_PDKILL", Const, 0},
+		{"SYS_PERF_EVENT_OPEN", Const, 0},
+		{"SYS_PERSONALITY", Const, 0},
+		{"SYS_PID_HIBERNATE", Const, 0},
+		{"SYS_PID_RESUME", Const, 0},
+		{"SYS_PID_SHUTDOWN_SOCKETS", Const, 0},
+		{"SYS_PID_SUSPEND", Const, 0},
+		{"SYS_PIPE", Const, 0},
+		{"SYS_PIPE2", Const, 0},
+		{"SYS_PIVOT_ROOT", Const, 0},
+		{"SYS_PMC_CONTROL", Const, 1},
+		{"SYS_PMC_GET_INFO", Const, 1},
+		{"SYS_POLL", Const, 0},
+		{"SYS_POLLTS", Const, 1},
+		{"SYS_POLL_NOCANCEL", Const, 0},
+		{"SYS_POSIX_FADVISE", Const, 0},
+		{"SYS_POSIX_FALLOCATE", Const, 0},
+		{"SYS_POSIX_OPENPT", Const, 0},
+		{"SYS_POSIX_SPAWN", Const, 0},
+		{"SYS_PPOLL", Const, 0},
+		{"SYS_PRCTL", Const, 0},
+		{"SYS_PREAD", Const, 0},
+		{"SYS_PREAD64", Const, 0},
+		{"SYS_PREADV", Const, 0},
+		{"SYS_PREAD_NOCANCEL", Const, 0},
+		{"SYS_PRLIMIT64", Const, 0},
+		{"SYS_PROCCTL", Const, 3},
+		{"SYS_PROCESS_POLICY", Const, 0},
+		{"SYS_PROCESS_VM_READV", Const, 0},
+		{"SYS_PROCESS_VM_WRITEV", Const, 0},
+		{"SYS_PROC_INFO", Const, 0},
+		{"SYS_PROF", Const, 0},
+		{"SYS_PROFIL", Const, 0},
+		{"SYS_PSELECT", Const, 0},
+		{"SYS_PSELECT6", Const, 0},
+		{"SYS_PSET_ASSIGN", Const, 1},
+		{"SYS_PSET_CREATE", Const, 1},
+		{"SYS_PSET_DESTROY", Const, 1},
+		{"SYS_PSYNCH_CVBROAD", Const, 0},
+		{"SYS_PSYNCH_CVCLRPREPOST", Const, 0},
+		{"SYS_PSYNCH_CVSIGNAL", Const, 0},
+		{"SYS_PSYNCH_CVWAIT", Const, 0},
+		{"SYS_PSYNCH_MUTEXDROP", Const, 0},
+		{"SYS_PSYNCH_MUTEXWAIT", Const, 0},
+		{"SYS_PSYNCH_RW_DOWNGRADE", Const, 0},
+		{"SYS_PSYNCH_RW_LONGRDLOCK", Const, 0},
+		{"SYS_PSYNCH_RW_RDLOCK", Const, 0},
+		{"SYS_PSYNCH_RW_UNLOCK", Const, 0},
+		{"SYS_PSYNCH_RW_UNLOCK2", Const, 0},
+		{"SYS_PSYNCH_RW_UPGRADE", Const, 0},
+		{"SYS_PSYNCH_RW_WRLOCK", Const, 0},
+		{"SYS_PSYNCH_RW_YIELDWRLOCK", Const, 0},
+		{"SYS_PTRACE", Const, 0},
+		{"SYS_PUTPMSG", Const, 0},
+		{"SYS_PWRITE", Const, 0},
+		{"SYS_PWRITE64", Const, 0},
+		{"SYS_PWRITEV", Const, 0},
+		{"SYS_PWRITE_NOCANCEL", Const, 0},
+		{"SYS_QUERY_MODULE", Const, 0},
+		{"SYS_QUOTACTL", Const, 0},
+		{"SYS_RASCTL", Const, 1},
+		{"SYS_RCTL_ADD_RULE", Const, 0},
+		{"SYS_RCTL_GET_LIMITS", Const, 0},
+		{"SYS_RCTL_GET_RACCT", Const, 0},
+		{"SYS_RCTL_GET_RULES", Const, 0},
+		{"SYS_RCTL_REMOVE_RULE", Const, 0},
+		{"SYS_READ", Const, 0},
+		{"SYS_READAHEAD", Const, 0},
+		{"SYS_READDIR", Const, 0},
+		{"SYS_READLINK", Const, 0},
+		{"SYS_READLINKAT", Const, 0},
+		{"SYS_READV", Const, 0},
+		{"SYS_READV_NOCANCEL", Const, 0},
+		{"SYS_READ_NOCANCEL", Const, 0},
+		{"SYS_REBOOT", Const, 0},
+		{"SYS_RECV", Const, 0},
+		{"SYS_RECVFROM", Const, 0},
+		{"SYS_RECVFROM_NOCANCEL", Const, 0},
+		{"SYS_RECVMMSG", Const, 0},
+		{"SYS_RECVMSG", Const, 0},
+		{"SYS_RECVMSG_NOCANCEL", Const, 0},
+		{"SYS_REMAP_FILE_PAGES", Const, 0},
+		{"SYS_REMOVEXATTR", Const, 0},
+		{"SYS_RENAME", Const, 0},
+		{"SYS_RENAMEAT", Const, 0},
+		{"SYS_REQUEST_KEY", Const, 0},
+		{"SYS_RESTART_SYSCALL", Const, 0},
+		{"SYS_REVOKE", Const, 0},
+		{"SYS_RFORK", Const, 0},
+		{"SYS_RMDIR", Const, 0},
+		{"SYS_RTPRIO", Const, 0},
+		{"SYS_RTPRIO_THREAD", Const, 0},
+		{"SYS_RT_SIGACTION", Const, 0},
+		{"SYS_RT_SIGPENDING", Const, 0},
+		{"SYS_RT_SIGPROCMASK", Const, 0},
+		{"SYS_RT_SIGQUEUEINFO", Const, 0},
+		{"SYS_RT_SIGRETURN", Const, 0},
+		{"SYS_RT_SIGSUSPEND", Const, 0},
+		{"SYS_RT_SIGTIMEDWAIT", Const, 0},
+		{"SYS_RT_TGSIGQUEUEINFO", Const, 0},
+		{"SYS_SBRK", Const, 0},
+		{"SYS_SCHED_GETAFFINITY", Const, 0},
+		{"SYS_SCHED_GETPARAM", Const, 0},
+		{"SYS_SCHED_GETSCHEDULER", Const, 0},
+		{"SYS_SCHED_GET_PRIORITY_MAX", Const, 0},
+		{"SYS_SCHED_GET_PRIORITY_MIN", Const, 0},
+		{"SYS_SCHED_RR_GET_INTERVAL", Const, 0},
+		{"SYS_SCHED_SETAFFINITY", Const, 0},
+		{"SYS_SCHED_SETPARAM", Const, 0},
+		{"SYS_SCHED_SETSCHEDULER", Const, 0},
+		{"SYS_SCHED_YIELD", Const, 0},
+		{"SYS_SCTP_GENERIC_RECVMSG", Const, 0},
+		{"SYS_SCTP_GENERIC_SENDMSG", Const, 0},
+		{"SYS_SCTP_GENERIC_SENDMSG_IOV", Const, 0},
+		{"SYS_SCTP_PEELOFF", Const, 0},
+		{"SYS_SEARCHFS", Const, 0},
+		{"SYS_SECURITY", Const, 0},
+		{"SYS_SELECT", Const, 0},
+		{"SYS_SELECT_NOCANCEL", Const, 0},
+		{"SYS_SEMCONFIG", Const, 1},
+		{"SYS_SEMCTL", Const, 0},
+		{"SYS_SEMGET", Const, 0},
+		{"SYS_SEMOP", Const, 0},
+		{"SYS_SEMSYS", Const, 0},
+		{"SYS_SEMTIMEDOP", Const, 0},
+		{"SYS_SEM_CLOSE", Const, 0},
+		{"SYS_SEM_DESTROY", Const, 0},
+		{"SYS_SEM_GETVALUE", Const, 0},
+		{"SYS_SEM_INIT", Const, 0},
+		{"SYS_SEM_OPEN", Const, 0},
+		{"SYS_SEM_POST", Const, 0},
+		{"SYS_SEM_TRYWAIT", Const, 0},
+		{"SYS_SEM_UNLINK", Const, 0},
+		{"SYS_SEM_WAIT", Const, 0},
+		{"SYS_SEM_WAIT_NOCANCEL", Const, 0},
+		{"SYS_SEND", Const, 0},
+		{"SYS_SENDFILE", Const, 0},
+		{"SYS_SENDFILE64", Const, 0},
+		{"SYS_SENDMMSG", Const, 0},
+		{"SYS_SENDMSG", Const, 0},
+		{"SYS_SENDMSG_NOCANCEL", Const, 0},
+		{"SYS_SENDTO", Const, 0},
+		{"SYS_SENDTO_NOCANCEL", Const, 0},
+		{"SYS_SETATTRLIST", Const, 0},
+		{"SYS_SETAUDIT", Const, 0},
+		{"SYS_SETAUDIT_ADDR", Const, 0},
+		{"SYS_SETAUID", Const, 0},
+		{"SYS_SETCONTEXT", Const, 0},
+		{"SYS_SETDOMAINNAME", Const, 0},
+		{"SYS_SETEGID", Const, 0},
+		{"SYS_SETEUID", Const, 0},
+		{"SYS_SETFIB", Const, 0},
+		{"SYS_SETFSGID", Const, 0},
+		{"SYS_SETFSGID32", Const, 0},
+		{"SYS_SETFSUID", Const, 0},
+		{"SYS_SETFSUID32", Const, 0},
+		{"SYS_SETGID", Const, 0},
+		{"SYS_SETGID32", Const, 0},
+		{"SYS_SETGROUPS", Const, 0},
+		{"SYS_SETGROUPS32", Const, 0},
+		{"SYS_SETHOSTNAME", Const, 0},
+		{"SYS_SETITIMER", Const, 0},
+		{"SYS_SETLCID", Const, 0},
+		{"SYS_SETLOGIN", Const, 0},
+		{"SYS_SETLOGINCLASS", Const, 0},
+		{"SYS_SETNS", Const, 0},
+		{"SYS_SETPGID", Const, 0},
+		{"SYS_SETPRIORITY", Const, 0},
+		{"SYS_SETPRIVEXEC", Const, 0},
+		{"SYS_SETREGID", Const, 0},
+		{"SYS_SETREGID32", Const, 0},
+		{"SYS_SETRESGID", Const, 0},
+		{"SYS_SETRESGID32", Const, 0},
+		{"SYS_SETRESUID", Const, 0},
+		{"SYS_SETRESUID32", Const, 0},
+		{"SYS_SETREUID", Const, 0},
+		{"SYS_SETREUID32", Const, 0},
+		{"SYS_SETRLIMIT", Const, 0},
+		{"SYS_SETRTABLE", Const, 1},
+		{"SYS_SETSGROUPS", Const, 0},
+		{"SYS_SETSID", Const, 0},
+		{"SYS_SETSOCKOPT", Const, 0},
+		{"SYS_SETTID", Const, 0},
+		{"SYS_SETTID_WITH_PID", Const, 0},
+		{"SYS_SETTIMEOFDAY", Const, 0},
+		{"SYS_SETUID", Const, 0},
+		{"SYS_SETUID32", Const, 0},
+		{"SYS_SETWGROUPS", Const, 0},
+		{"SYS_SETXATTR", Const, 0},
+		{"SYS_SET_MEMPOLICY", Const, 0},
+		{"SYS_SET_ROBUST_LIST", Const, 0},
+		{"SYS_SET_THREAD_AREA", Const, 0},
+		{"SYS_SET_TID_ADDRESS", Const, 0},
+		{"SYS_SGETMASK", Const, 0},
+		{"SYS_SHARED_REGION_CHECK_NP", Const, 0},
+		{"SYS_SHARED_REGION_MAP_AND_SLIDE_NP", Const, 0},
+		{"SYS_SHMAT", Const, 0},
+		{"SYS_SHMCTL", Const, 0},
+		{"SYS_SHMDT", Const, 0},
+		{"SYS_SHMGET", Const, 0},
+		{"SYS_SHMSYS", Const, 0},
+		{"SYS_SHM_OPEN", Const, 0},
+		{"SYS_SHM_UNLINK", Const, 0},
+		{"SYS_SHUTDOWN", Const, 0},
+		{"SYS_SIGACTION", Const, 0},
+		{"SYS_SIGALTSTACK", Const, 0},
+		{"SYS_SIGNAL", Const, 0},
+		{"SYS_SIGNALFD", Const, 0},
+		{"SYS_SIGNALFD4", Const, 0},
+		{"SYS_SIGPENDING", Const, 0},
+		{"SYS_SIGPROCMASK", Const, 0},
+		{"SYS_SIGQUEUE", Const, 0},
+		{"SYS_SIGQUEUEINFO", Const, 1},
+		{"SYS_SIGRETURN", Const, 0},
+		{"SYS_SIGSUSPEND", Const, 0},
+		{"SYS_SIGSUSPEND_NOCANCEL", Const, 0},
+		{"SYS_SIGTIMEDWAIT", Const, 0},
+		{"SYS_SIGWAIT", Const, 0},
+		{"SYS_SIGWAITINFO", Const, 0},
+		{"SYS_SOCKET", Const, 0},
+		{"SYS_SOCKETCALL", Const, 0},
+		{"SYS_SOCKETPAIR", Const, 0},
+		{"SYS_SPLICE", Const, 0},
+		{"SYS_SSETMASK", Const, 0},
+		{"SYS_SSTK", Const, 0},
+		{"SYS_STACK_SNAPSHOT", Const, 0},
+		{"SYS_STAT", Const, 0},
+		{"SYS_STAT64", Const, 0},
+		{"SYS_STAT64_EXTENDED", Const, 0},
+		{"SYS_STATFS", Const, 0},
+		{"SYS_STATFS64", Const, 0},
+		{"SYS_STATV", Const, 0},
+		{"SYS_STATVFS1", Const, 1},
+		{"SYS_STAT_EXTENDED", Const, 0},
+		{"SYS_STIME", Const, 0},
+		{"SYS_STTY", Const, 0},
+		{"SYS_SWAPCONTEXT", Const, 0},
+		{"SYS_SWAPCTL", Const, 1},
+		{"SYS_SWAPOFF", Const, 0},
+		{"SYS_SWAPON", Const, 0},
+		{"SYS_SYMLINK", Const, 0},
+		{"SYS_SYMLINKAT", Const, 0},
+		{"SYS_SYNC", Const, 0},
+		{"SYS_SYNCFS", Const, 0},
+		{"SYS_SYNC_FILE_RANGE", Const, 0},
+		{"SYS_SYSARCH", Const, 0},
+		{"SYS_SYSCALL", Const, 0},
+		{"SYS_SYSCALL_BASE", Const, 0},
+		{"SYS_SYSFS", Const, 0},
+		{"SYS_SYSINFO", Const, 0},
+		{"SYS_SYSLOG", Const, 0},
+		{"SYS_TEE", Const, 0},
+		{"SYS_TGKILL", Const, 0},
+		{"SYS_THREAD_SELFID", Const, 0},
+		{"SYS_THR_CREATE", Const, 0},
+		{"SYS_THR_EXIT", Const, 0},
+		{"SYS_THR_KILL", Const, 0},
+		{"SYS_THR_KILL2", Const, 0},
+		{"SYS_THR_NEW", Const, 0},
+		{"SYS_THR_SELF", Const, 0},
+		{"SYS_THR_SET_NAME", Const, 0},
+		{"SYS_THR_SUSPEND", Const, 0},
+		{"SYS_THR_WAKE", Const, 0},
+		{"SYS_TIME", Const, 0},
+		{"SYS_TIMERFD_CREATE", Const, 0},
+		{"SYS_TIMERFD_GETTIME", Const, 0},
+		{"SYS_TIMERFD_SETTIME", Const, 0},
+		{"SYS_TIMER_CREATE", Const, 0},
+		{"SYS_TIMER_DELETE", Const, 0},
+		{"SYS_TIMER_GETOVERRUN", Const, 0},
+		{"SYS_TIMER_GETTIME", Const, 0},
+		{"SYS_TIMER_SETTIME", Const, 0},
+		{"SYS_TIMES", Const, 0},
+		{"SYS_TKILL", Const, 0},
+		{"SYS_TRUNCATE", Const, 0},
+		{"SYS_TRUNCATE64", Const, 0},
+		{"SYS_TUXCALL", Const, 0},
+		{"SYS_UGETRLIMIT", Const, 0},
+		{"SYS_ULIMIT", Const, 0},
+		{"SYS_UMASK", Const, 0},
+		{"SYS_UMASK_EXTENDED", Const, 0},
+		{"SYS_UMOUNT", Const, 0},
+		{"SYS_UMOUNT2", Const, 0},
+		{"SYS_UNAME", Const, 0},
+		{"SYS_UNDELETE", Const, 0},
+		{"SYS_UNLINK", Const, 0},
+		{"SYS_UNLINKAT", Const, 0},
+		{"SYS_UNMOUNT", Const, 0},
+		{"SYS_UNSHARE", Const, 0},
+		{"SYS_USELIB", Const, 0},
+		{"SYS_USTAT", Const, 0},
+		{"SYS_UTIME", Const, 0},
+		{"SYS_UTIMENSAT", Const, 0},
+		{"SYS_UTIMES", Const, 0},
+		{"SYS_UTRACE", Const, 0},
+		{"SYS_UUIDGEN", Const, 0},
+		{"SYS_VADVISE", Const, 1},
+		{"SYS_VFORK", Const, 0},
+		{"SYS_VHANGUP", Const, 0},
+		{"SYS_VM86", Const, 0},
+		{"SYS_VM86OLD", Const, 0},
+		{"SYS_VMSPLICE", Const, 0},
+		{"SYS_VM_PRESSURE_MONITOR", Const, 0},
+		{"SYS_VSERVER", Const, 0},
+		{"SYS_WAIT4", Const, 0},
+		{"SYS_WAIT4_NOCANCEL", Const, 0},
+		{"SYS_WAIT6", Const, 1},
+		{"SYS_WAITEVENT", Const, 0},
+		{"SYS_WAITID", Const, 0},
+		{"SYS_WAITID_NOCANCEL", Const, 0},
+		{"SYS_WAITPID", Const, 0},
+		{"SYS_WATCHEVENT", Const, 0},
+		{"SYS_WORKQ_KERNRETURN", Const, 0},
+		{"SYS_WORKQ_OPEN", Const, 0},
+		{"SYS_WRITE", Const, 0},
+		{"SYS_WRITEV", Const, 0},
+		{"SYS_WRITEV_NOCANCEL", Const, 0},
+		{"SYS_WRITE_NOCANCEL", Const, 0},
+		{"SYS_YIELD", Const, 0},
+		{"SYS__LLSEEK", Const, 0},
+		{"SYS__LWP_CONTINUE", Const, 1},
+		{"SYS__LWP_CREATE", Const, 1},
+		{"SYS__LWP_CTL", Const, 1},
+		{"SYS__LWP_DETACH", Const, 1},
+		{"SYS__LWP_EXIT", Const, 1},
+		{"SYS__LWP_GETNAME", Const, 1},
+		{"SYS__LWP_GETPRIVATE", Const, 1},
+		{"SYS__LWP_KILL", Const, 1},
+		{"SYS__LWP_PARK", Const, 1},
+		{"SYS__LWP_SELF", Const, 1},
+		{"SYS__LWP_SETNAME", Const, 1},
+		{"SYS__LWP_SETPRIVATE", Const, 1},
+		{"SYS__LWP_SUSPEND", Const, 1},
+		{"SYS__LWP_UNPARK", Const, 1},
+		{"SYS__LWP_UNPARK_ALL", Const, 1},
+		{"SYS__LWP_WAIT", Const, 1},
+		{"SYS__LWP_WAKEUP", Const, 1},
+		{"SYS__NEWSELECT", Const, 0},
+		{"SYS__PSET_BIND", Const, 1},
+		{"SYS__SCHED_GETAFFINITY", Const, 1},
+		{"SYS__SCHED_GETPARAM", Const, 1},
+		{"SYS__SCHED_SETAFFINITY", Const, 1},
+		{"SYS__SCHED_SETPARAM", Const, 1},
+		{"SYS__SYSCTL", Const, 0},
+		{"SYS__UMTX_LOCK", Const, 0},
+		{"SYS__UMTX_OP", Const, 0},
+		{"SYS__UMTX_UNLOCK", Const, 0},
+		{"SYS___ACL_ACLCHECK_FD", Const, 0},
+		{"SYS___ACL_ACLCHECK_FILE", Const, 0},
+		{"SYS___ACL_ACLCHECK_LINK", Const, 0},
+		{"SYS___ACL_DELETE_FD", Const, 0},
+		{"SYS___ACL_DELETE_FILE", Const, 0},
+		{"SYS___ACL_DELETE_LINK", Const, 0},
+		{"SYS___ACL_GET_FD", Const, 0},
+		{"SYS___ACL_GET_FILE", Const, 0},
+		{"SYS___ACL_GET_LINK", Const, 0},
+		{"SYS___ACL_SET_FD", Const, 0},
+		{"SYS___ACL_SET_FILE", Const, 0},
+		{"SYS___ACL_SET_LINK", Const, 0},
+		{"SYS___CAP_RIGHTS_GET", Const, 14},
+		{"SYS___CLONE", Const, 1},
+		{"SYS___DISABLE_THREADSIGNAL", Const, 0},
+		{"SYS___GETCWD", Const, 0},
+		{"SYS___GETLOGIN", Const, 1},
+		{"SYS___GET_TCB", Const, 1},
+		{"SYS___MAC_EXECVE", Const, 0},
+		{"SYS___MAC_GETFSSTAT", Const, 0},
+		{"SYS___MAC_GET_FD", Const, 0},
+		{"SYS___MAC_GET_FILE", Const, 0},
+		{"SYS___MAC_GET_LCID", Const, 0},
+		{"SYS___MAC_GET_LCTX", Const, 0},
+		{"SYS___MAC_GET_LINK", Const, 0},
+		{"SYS___MAC_GET_MOUNT", Const, 0},
+		{"SYS___MAC_GET_PID", Const, 0},
+		{"SYS___MAC_GET_PROC", Const, 0},
+		{"SYS___MAC_MOUNT", Const, 0},
+		{"SYS___MAC_SET_FD", Const, 0},
+		{"SYS___MAC_SET_FILE", Const, 0},
+		{"SYS___MAC_SET_LCTX", Const, 0},
+		{"SYS___MAC_SET_LINK", Const, 0},
+		{"SYS___MAC_SET_PROC", Const, 0},
+		{"SYS___MAC_SYSCALL", Const, 0},
+		{"SYS___OLD_SEMWAIT_SIGNAL", Const, 0},
+		{"SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL", Const, 0},
+		{"SYS___POSIX_CHOWN", Const, 1},
+		{"SYS___POSIX_FCHOWN", Const, 1},
+		{"SYS___POSIX_LCHOWN", Const, 1},
+		{"SYS___POSIX_RENAME", Const, 1},
+		{"SYS___PTHREAD_CANCELED", Const, 0},
+		{"SYS___PTHREAD_CHDIR", Const, 0},
+		{"SYS___PTHREAD_FCHDIR", Const, 0},
+		{"SYS___PTHREAD_KILL", Const, 0},
+		{"SYS___PTHREAD_MARKCANCEL", Const, 0},
+		{"SYS___PTHREAD_SIGMASK", Const, 0},
+		{"SYS___QUOTACTL", Const, 1},
+		{"SYS___SEMCTL", Const, 1},
+		{"SYS___SEMWAIT_SIGNAL", Const, 0},
+		{"SYS___SEMWAIT_SIGNAL_NOCANCEL", Const, 0},
+		{"SYS___SETLOGIN", Const, 1},
+		{"SYS___SETUGID", Const, 0},
+		{"SYS___SET_TCB", Const, 1},
+		{"SYS___SIGACTION_SIGTRAMP", Const, 1},
+		{"SYS___SIGTIMEDWAIT", Const, 1},
+		{"SYS___SIGWAIT", Const, 0},
+		{"SYS___SIGWAIT_NOCANCEL", Const, 0},
+		{"SYS___SYSCTL", Const, 0},
+		{"SYS___TFORK", Const, 1},
+		{"SYS___THREXIT", Const, 1},
+		{"SYS___THRSIGDIVERT", Const, 1},
+		{"SYS___THRSLEEP", Const, 1},
+		{"SYS___THRWAKEUP", Const, 1},
+		{"S_ARCH1", Const, 1},
+		{"S_ARCH2", Const, 1},
+		{"S_BLKSIZE", Const, 0},
+		{"S_IEXEC", Const, 0},
+		{"S_IFBLK", Const, 0},
+		{"S_IFCHR", Const, 0},
+		{"S_IFDIR", Const, 0},
+		{"S_IFIFO", Const, 0},
+		{"S_IFLNK", Const, 0},
+		{"S_IFMT", Const, 0},
+		{"S_IFREG", Const, 0},
+		{"S_IFSOCK", Const, 0},
+		{"S_IFWHT", Const, 0},
+		{"S_IREAD", Const, 0},
+		{"S_IRGRP", Const, 0},
+		{"S_IROTH", Const, 0},
+		{"S_IRUSR", Const, 0},
+		{"S_IRWXG", Const, 0},
+		{"S_IRWXO", Const, 0},
+		{"S_IRWXU", Const, 0},
+		{"S_ISGID", Const, 0},
+		{"S_ISTXT", Const, 0},
+		{"S_ISUID", Const, 0},
+		{"S_ISVTX", Const, 0},
+		{"S_IWGRP", Const, 0},
+		{"S_IWOTH", Const, 0},
+		{"S_IWRITE", Const, 0},
+		{"S_IWUSR", Const, 0},
+		{"S_IXGRP", Const, 0},
+		{"S_IXOTH", Const, 0},
+		{"S_IXUSR", Const, 0},
+		{"S_LOGIN_SET", Const, 1},
+		{"SecurityAttributes", Type, 0},
+		{"SecurityAttributes.InheritHandle", Field, 0},
+		{"SecurityAttributes.Length", Field, 0},
+		{"SecurityAttributes.SecurityDescriptor", Field, 0},
+		{"Seek", Func, 0},
+		{"Select", Func, 0},
+		{"Sendfile", Func, 0},
+		{"Sendmsg", Func, 0},
+		{"SendmsgN", Func, 3},
+		{"Sendto", Func, 0},
+		{"Servent", Type, 0},
+		{"Servent.Aliases", Field, 0},
+		{"Servent.Name", Field, 0},
+		{"Servent.Port", Field, 0},
+		{"Servent.Proto", Field, 0},
+		{"SetBpf", Func, 0},
+		{"SetBpfBuflen", Func, 0},
+		{"SetBpfDatalink", Func, 0},
+		{"SetBpfHeadercmpl", Func, 0},
+		{"SetBpfImmediate", Func, 0},
+		{"SetBpfInterface", Func, 0},
+		{"SetBpfPromisc", Func, 0},
+		{"SetBpfTimeout", Func, 0},
+		{"SetCurrentDirectory", Func, 0},
+		{"SetEndOfFile", Func, 0},
+		{"SetEnvironmentVariable", Func, 0},
+		{"SetFileAttributes", Func, 0},
+		{"SetFileCompletionNotificationModes", Func, 2},
+		{"SetFilePointer", Func, 0},
+		{"SetFileTime", Func, 0},
+		{"SetHandleInformation", Func, 0},
+		{"SetKevent", Func, 0},
+		{"SetLsfPromisc", Func, 0},
+		{"SetNonblock", Func, 0},
+		{"Setdomainname", Func, 0},
+		{"Setegid", Func, 0},
+		{"Setenv", Func, 0},
+		{"Seteuid", Func, 0},
+		{"Setfsgid", Func, 0},
+		{"Setfsuid", Func, 0},
+		{"Setgid", Func, 0},
+		{"Setgroups", Func, 0},
+		{"Sethostname", Func, 0},
+		{"Setlogin", Func, 0},
+		{"Setpgid", Func, 0},
+		{"Setpriority", Func, 0},
+		{"Setprivexec", Func, 0},
+		{"Setregid", Func, 0},
+		{"Setresgid", Func, 0},
+		{"Setresuid", Func, 0},
+		{"Setreuid", Func, 0},
+		{"Setrlimit", Func, 0},
+		{"Setsid", Func, 0},
+		{"Setsockopt", Func, 0},
+		{"SetsockoptByte", Func, 0},
+		{"SetsockoptICMPv6Filter", Func, 2},
+		{"SetsockoptIPMreq", Func, 0},
+		{"SetsockoptIPMreqn", Func, 0},
+		{"SetsockoptIPv6Mreq", Func, 0},
+		{"SetsockoptInet4Addr", Func, 0},
+		{"SetsockoptInt", Func, 0},
+		{"SetsockoptLinger", Func, 0},
+		{"SetsockoptString", Func, 0},
+		{"SetsockoptTimeval", Func, 0},
+		{"Settimeofday", Func, 0},
+		{"Setuid", Func, 0},
+		{"Setxattr", Func, 1},
+		{"Shutdown", Func, 0},
+		{"SidTypeAlias", Const, 0},
+		{"SidTypeComputer", Const, 0},
+		{"SidTypeDeletedAccount", Const, 0},
+		{"SidTypeDomain", Const, 0},
+		{"SidTypeGroup", Const, 0},
+		{"SidTypeInvalid", Const, 0},
+		{"SidTypeLabel", Const, 0},
+		{"SidTypeUnknown", Const, 0},
+		{"SidTypeUser", Const, 0},
+		{"SidTypeWellKnownGroup", Const, 0},
+		{"Signal", Type, 0},
+		{"SizeofBpfHdr", Const, 0},
+		{"SizeofBpfInsn", Const, 0},
+		{"SizeofBpfProgram", Const, 0},
+		{"SizeofBpfStat", Const, 0},
+		{"SizeofBpfVersion", Const, 0},
+		{"SizeofBpfZbuf", Const, 0},
+		{"SizeofBpfZbufHeader", Const, 0},
+		{"SizeofCmsghdr", Const, 0},
+		{"SizeofICMPv6Filter", Const, 2},
+		{"SizeofIPMreq", Const, 0},
+		{"SizeofIPMreqn", Const, 0},
+		{"SizeofIPv6MTUInfo", Const, 2},
+		{"SizeofIPv6Mreq", Const, 0},
+		{"SizeofIfAddrmsg", Const, 0},
+		{"SizeofIfAnnounceMsghdr", Const, 1},
+		{"SizeofIfData", Const, 0},
+		{"SizeofIfInfomsg", Const, 0},
+		{"SizeofIfMsghdr", Const, 0},
+		{"SizeofIfaMsghdr", Const, 0},
+		{"SizeofIfmaMsghdr", Const, 0},
+		{"SizeofIfmaMsghdr2", Const, 0},
+		{"SizeofInet4Pktinfo", Const, 0},
+		{"SizeofInet6Pktinfo", Const, 0},
+		{"SizeofInotifyEvent", Const, 0},
+		{"SizeofLinger", Const, 0},
+		{"SizeofMsghdr", Const, 0},
+		{"SizeofNlAttr", Const, 0},
+		{"SizeofNlMsgerr", Const, 0},
+		{"SizeofNlMsghdr", Const, 0},
+		{"SizeofRtAttr", Const, 0},
+		{"SizeofRtGenmsg", Const, 0},
+		{"SizeofRtMetrics", Const, 0},
+		{"SizeofRtMsg", Const, 0},
+		{"SizeofRtMsghdr", Const, 0},
+		{"SizeofRtNexthop", Const, 0},
+		{"SizeofSockFilter", Const, 0},
+		{"SizeofSockFprog", Const, 0},
+		{"SizeofSockaddrAny", Const, 0},
+		{"SizeofSockaddrDatalink", Const, 0},
+		{"SizeofSockaddrInet4", Const, 0},
+		{"SizeofSockaddrInet6", Const, 0},
+		{"SizeofSockaddrLinklayer", Const, 0},
+		{"SizeofSockaddrNetlink", Const, 0},
+		{"SizeofSockaddrUnix", Const, 0},
+		{"SizeofTCPInfo", Const, 1},
+		{"SizeofUcred", Const, 0},
+		{"SlicePtrFromStrings", Func, 1},
+		{"SockFilter", Type, 0},
+		{"SockFilter.Code", Field, 0},
+		{"SockFilter.Jf", Field, 0},
+		{"SockFilter.Jt", Field, 0},
+		{"SockFilter.K", Field, 0},
+		{"SockFprog", Type, 0},
+		{"SockFprog.Filter", Field, 0},
+		{"SockFprog.Len", Field, 0},
+		{"SockFprog.Pad_cgo_0", Field, 0},
+		{"Sockaddr", Type, 0},
+		{"SockaddrDatalink", Type, 0},
+		{"SockaddrDatalink.Alen", Field, 0},
+		{"SockaddrDatalink.Data", Field, 0},
+		{"SockaddrDatalink.Family", Field, 0},
+		{"SockaddrDatalink.Index", Field, 0},
+		{"SockaddrDatalink.Len", Field, 0},
+		{"SockaddrDatalink.Nlen", Field, 0},
+		{"SockaddrDatalink.Slen", Field, 0},
+		{"SockaddrDatalink.Type", Field, 0},
+		{"SockaddrGen", Type, 0},
+		{"SockaddrInet4", Type, 0},
+		{"SockaddrInet4.Addr", Field, 0},
+		{"SockaddrInet4.Port", Field, 0},
+		{"SockaddrInet6", Type, 0},
+		{"SockaddrInet6.Addr", Field, 0},
+		{"SockaddrInet6.Port", Field, 0},
+		{"SockaddrInet6.ZoneId", Field, 0},
+		{"SockaddrLinklayer", Type, 0},
+		{"SockaddrLinklayer.Addr", Field, 0},
+		{"SockaddrLinklayer.Halen", Field, 0},
+		{"SockaddrLinklayer.Hatype", Field, 0},
+		{"SockaddrLinklayer.Ifindex", Field, 0},
+		{"SockaddrLinklayer.Pkttype", Field, 0},
+		{"SockaddrLinklayer.Protocol", Field, 0},
+		{"SockaddrNetlink", Type, 0},
+		{"SockaddrNetlink.Family", Field, 0},
+		{"SockaddrNetlink.Groups", Field, 0},
+		{"SockaddrNetlink.Pad", Field, 0},
+		{"SockaddrNetlink.Pid", Field, 0},
+		{"SockaddrUnix", Type, 0},
+		{"SockaddrUnix.Name", Field, 0},
+		{"Socket", Func, 0},
+		{"SocketControlMessage", Type, 0},
+		{"SocketControlMessage.Data", Field, 0},
+		{"SocketControlMessage.Header", Field, 0},
+		{"SocketDisableIPv6", Var, 0},
+		{"Socketpair", Func, 0},
+		{"Splice", Func, 0},
+		{"StartProcess", Func, 0},
+		{"StartupInfo", Type, 0},
+		{"StartupInfo.Cb", Field, 0},
+		{"StartupInfo.Desktop", Field, 0},
+		{"StartupInfo.FillAttribute", Field, 0},
+		{"StartupInfo.Flags", Field, 0},
+		{"StartupInfo.ShowWindow", Field, 0},
+		{"StartupInfo.StdErr", Field, 0},
+		{"StartupInfo.StdInput", Field, 0},
+		{"StartupInfo.StdOutput", Field, 0},
+		{"StartupInfo.Title", Field, 0},
+		{"StartupInfo.X", Field, 0},
+		{"StartupInfo.XCountChars", Field, 0},
+		{"StartupInfo.XSize", Field, 0},
+		{"StartupInfo.Y", Field, 0},
+		{"StartupInfo.YCountChars", Field, 0},
+		{"StartupInfo.YSize", Field, 0},
+		{"Stat", Func, 0},
+		{"Stat_t", Type, 0},
+		{"Stat_t.Atim", Field, 0},
+		{"Stat_t.Atim_ext", Field, 12},
+		{"Stat_t.Atimespec", Field, 0},
+		{"Stat_t.Birthtimespec", Field, 0},
+		{"Stat_t.Blksize", Field, 0},
+		{"Stat_t.Blocks", Field, 0},
+		{"Stat_t.Btim_ext", Field, 12},
+		{"Stat_t.Ctim", Field, 0},
+		{"Stat_t.Ctim_ext", Field, 12},
+		{"Stat_t.Ctimespec", Field, 0},
+		{"Stat_t.Dev", Field, 0},
+		{"Stat_t.Flags", Field, 0},
+		{"Stat_t.Gen", Field, 0},
+		{"Stat_t.Gid", Field, 0},
+		{"Stat_t.Ino", Field, 0},
+		{"Stat_t.Lspare", Field, 0},
+		{"Stat_t.Lspare0", Field, 2},
+		{"Stat_t.Lspare1", Field, 2},
+		{"Stat_t.Mode", Field, 0},
+		{"Stat_t.Mtim", Field, 0},
+		{"Stat_t.Mtim_ext", Field, 12},
+		{"Stat_t.Mtimespec", Field, 0},
+		{"Stat_t.Nlink", Field, 0},
+		{"Stat_t.Pad_cgo_0", Field, 0},
+		{"Stat_t.Pad_cgo_1", Field, 0},
+		{"Stat_t.Pad_cgo_2", Field, 0},
+		{"Stat_t.Padding0", Field, 12},
+		{"Stat_t.Padding1", Field, 12},
+		{"Stat_t.Qspare", Field, 0},
+		{"Stat_t.Rdev", Field, 0},
+		{"Stat_t.Size", Field, 0},
+		{"Stat_t.Spare", Field, 2},
+		{"Stat_t.Uid", Field, 0},
+		{"Stat_t.X__pad0", Field, 0},
+		{"Stat_t.X__pad1", Field, 0},
+		{"Stat_t.X__pad2", Field, 0},
+		{"Stat_t.X__st_birthtim", Field, 2},
+		{"Stat_t.X__st_ino", Field, 0},
+		{"Stat_t.X__unused", Field, 0},
+		{"Statfs", Func, 0},
+		{"Statfs_t", Type, 0},
+		{"Statfs_t.Asyncreads", Field, 0},
+		{"Statfs_t.Asyncwrites", Field, 0},
+		{"Statfs_t.Bavail", Field, 0},
+		{"Statfs_t.Bfree", Field, 0},
+		{"Statfs_t.Blocks", Field, 0},
+		{"Statfs_t.Bsize", Field, 0},
+		{"Statfs_t.Charspare", Field, 0},
+		{"Statfs_t.F_asyncreads", Field, 2},
+		{"Statfs_t.F_asyncwrites", Field, 2},
+		{"Statfs_t.F_bavail", Field, 2},
+		{"Statfs_t.F_bfree", Field, 2},
+		{"Statfs_t.F_blocks", Field, 2},
+		{"Statfs_t.F_bsize", Field, 2},
+		{"Statfs_t.F_ctime", Field, 2},
+		{"Statfs_t.F_favail", Field, 2},
+		{"Statfs_t.F_ffree", Field, 2},
+		{"Statfs_t.F_files", Field, 2},
+		{"Statfs_t.F_flags", Field, 2},
+		{"Statfs_t.F_fsid", Field, 2},
+		{"Statfs_t.F_fstypename", Field, 2},
+		{"Statfs_t.F_iosize", Field, 2},
+		{"Statfs_t.F_mntfromname", Field, 2},
+		{"Statfs_t.F_mntfromspec", Field, 3},
+		{"Statfs_t.F_mntonname", Field, 2},
+		{"Statfs_t.F_namemax", Field, 2},
+		{"Statfs_t.F_owner", Field, 2},
+		{"Statfs_t.F_spare", Field, 2},
+		{"Statfs_t.F_syncreads", Field, 2},
+		{"Statfs_t.F_syncwrites", Field, 2},
+		{"Statfs_t.Ffree", Field, 0},
+		{"Statfs_t.Files", Field, 0},
+		{"Statfs_t.Flags", Field, 0},
+		{"Statfs_t.Frsize", Field, 0},
+		{"Statfs_t.Fsid", Field, 0},
+		{"Statfs_t.Fssubtype", Field, 0},
+		{"Statfs_t.Fstypename", Field, 0},
+		{"Statfs_t.Iosize", Field, 0},
+		{"Statfs_t.Mntfromname", Field, 0},
+		{"Statfs_t.Mntonname", Field, 0},
+		{"Statfs_t.Mount_info", Field, 2},
+		{"Statfs_t.Namelen", Field, 0},
+		{"Statfs_t.Namemax", Field, 0},
+		{"Statfs_t.Owner", Field, 0},
+		{"Statfs_t.Pad_cgo_0", Field, 0},
+		{"Statfs_t.Pad_cgo_1", Field, 2},
+		{"Statfs_t.Reserved", Field, 0},
+		{"Statfs_t.Spare", Field, 0},
+		{"Statfs_t.Syncreads", Field, 0},
+		{"Statfs_t.Syncwrites", Field, 0},
+		{"Statfs_t.Type", Field, 0},
+		{"Statfs_t.Version", Field, 0},
+		{"Stderr", Var, 0},
+		{"Stdin", Var, 0},
+		{"Stdout", Var, 0},
+		{"StringBytePtr", Func, 0},
+		{"StringByteSlice", Func, 0},
+		{"StringSlicePtr", Func, 0},
+		{"StringToSid", Func, 0},
+		{"StringToUTF16", Func, 0},
+		{"StringToUTF16Ptr", Func, 0},
+		{"Symlink", Func, 0},
+		{"Sync", Func, 0},
+		{"SyncFileRange", Func, 0},
+		{"SysProcAttr", Type, 0},
+		{"SysProcAttr.AdditionalInheritedHandles", Field, 17},
+		{"SysProcAttr.AmbientCaps", Field, 9},
+		{"SysProcAttr.CgroupFD", Field, 20},
+		{"SysProcAttr.Chroot", Field, 0},
+		{"SysProcAttr.Cloneflags", Field, 2},
+		{"SysProcAttr.CmdLine", Field, 0},
+		{"SysProcAttr.CreationFlags", Field, 1},
+		{"SysProcAttr.Credential", Field, 0},
+		{"SysProcAttr.Ctty", Field, 1},
+		{"SysProcAttr.Foreground", Field, 5},
+		{"SysProcAttr.GidMappings", Field, 4},
+		{"SysProcAttr.GidMappingsEnableSetgroups", Field, 5},
+		{"SysProcAttr.HideWindow", Field, 0},
+		{"SysProcAttr.Jail", Field, 21},
+		{"SysProcAttr.NoInheritHandles", Field, 16},
+		{"SysProcAttr.Noctty", Field, 0},
+		{"SysProcAttr.ParentProcess", Field, 17},
+		{"SysProcAttr.Pdeathsig", Field, 0},
+		{"SysProcAttr.Pgid", Field, 5},
+		{"SysProcAttr.PidFD", Field, 22},
+		{"SysProcAttr.ProcessAttributes", Field, 13},
+		{"SysProcAttr.Ptrace", Field, 0},
+		{"SysProcAttr.Setctty", Field, 0},
+		{"SysProcAttr.Setpgid", Field, 0},
+		{"SysProcAttr.Setsid", Field, 0},
+		{"SysProcAttr.ThreadAttributes", Field, 13},
+		{"SysProcAttr.Token", Field, 10},
+		{"SysProcAttr.UidMappings", Field, 4},
+		{"SysProcAttr.Unshareflags", Field, 7},
+		{"SysProcAttr.UseCgroupFD", Field, 20},
+		{"SysProcIDMap", Type, 4},
+		{"SysProcIDMap.ContainerID", Field, 4},
+		{"SysProcIDMap.HostID", Field, 4},
+		{"SysProcIDMap.Size", Field, 4},
+		{"Syscall", Func, 0},
+		{"Syscall12", Func, 0},
+		{"Syscall15", Func, 0},
+		{"Syscall18", Func, 12},
+		{"Syscall6", Func, 0},
+		{"Syscall9", Func, 0},
+		{"SyscallN", Func, 18},
+		{"Sysctl", Func, 0},
+		{"SysctlUint32", Func, 0},
+		{"Sysctlnode", Type, 2},
+		{"Sysctlnode.Flags", Field, 2},
+		{"Sysctlnode.Name", Field, 2},
+		{"Sysctlnode.Num", Field, 2},
+		{"Sysctlnode.Un", Field, 2},
+		{"Sysctlnode.Ver", Field, 2},
+		{"Sysctlnode.X__rsvd", Field, 2},
+		{"Sysctlnode.X_sysctl_desc", Field, 2},
+		{"Sysctlnode.X_sysctl_func", Field, 2},
+		{"Sysctlnode.X_sysctl_parent", Field, 2},
+		{"Sysctlnode.X_sysctl_size", Field, 2},
+		{"Sysinfo", Func, 0},
+		{"Sysinfo_t", Type, 0},
+		{"Sysinfo_t.Bufferram", Field, 0},
+		{"Sysinfo_t.Freehigh", Field, 0},
+		{"Sysinfo_t.Freeram", Field, 0},
+		{"Sysinfo_t.Freeswap", Field, 0},
+		{"Sysinfo_t.Loads", Field, 0},
+		{"Sysinfo_t.Pad", Field, 0},
+		{"Sysinfo_t.Pad_cgo_0", Field, 0},
+		{"Sysinfo_t.Pad_cgo_1", Field, 0},
+		{"Sysinfo_t.Procs", Field, 0},
+		{"Sysinfo_t.Sharedram", Field, 0},
+		{"Sysinfo_t.Totalhigh", Field, 0},
+		{"Sysinfo_t.Totalram", Field, 0},
+		{"Sysinfo_t.Totalswap", Field, 0},
+		{"Sysinfo_t.Unit", Field, 0},
+		{"Sysinfo_t.Uptime", Field, 0},
+		{"Sysinfo_t.X_f", Field, 0},
+		{"Systemtime", Type, 0},
+		{"Systemtime.Day", Field, 0},
+		{"Systemtime.DayOfWeek", Field, 0},
+		{"Systemtime.Hour", Field, 0},
+		{"Systemtime.Milliseconds", Field, 0},
+		{"Systemtime.Minute", Field, 0},
+		{"Systemtime.Month", Field, 0},
+		{"Systemtime.Second", Field, 0},
+		{"Systemtime.Year", Field, 0},
+		{"TCGETS", Const, 0},
+		{"TCIFLUSH", Const, 1},
+		{"TCIOFLUSH", Const, 1},
+		{"TCOFLUSH", Const, 1},
+		{"TCPInfo", Type, 1},
+		{"TCPInfo.Advmss", Field, 1},
+		{"TCPInfo.Ato", Field, 1},
+		{"TCPInfo.Backoff", Field, 1},
+		{"TCPInfo.Ca_state", Field, 1},
+		{"TCPInfo.Fackets", Field, 1},
+		{"TCPInfo.Last_ack_recv", Field, 1},
+		{"TCPInfo.Last_ack_sent", Field, 1},
+		{"TCPInfo.Last_data_recv", Field, 1},
+		{"TCPInfo.Last_data_sent", Field, 1},
+		{"TCPInfo.Lost", Field, 1},
+		{"TCPInfo.Options", Field, 1},
+		{"TCPInfo.Pad_cgo_0", Field, 1},
+		{"TCPInfo.Pmtu", Field, 1},
+		{"TCPInfo.Probes", Field, 1},
+		{"TCPInfo.Rcv_mss", Field, 1},
+		{"TCPInfo.Rcv_rtt", Field, 1},
+		{"TCPInfo.Rcv_space", Field, 1},
+		{"TCPInfo.Rcv_ssthresh", Field, 1},
+		{"TCPInfo.Reordering", Field, 1},
+		{"TCPInfo.Retrans", Field, 1},
+		{"TCPInfo.Retransmits", Field, 1},
+		{"TCPInfo.Rto", Field, 1},
+		{"TCPInfo.Rtt", Field, 1},
+		{"TCPInfo.Rttvar", Field, 1},
+		{"TCPInfo.Sacked", Field, 1},
+		{"TCPInfo.Snd_cwnd", Field, 1},
+		{"TCPInfo.Snd_mss", Field, 1},
+		{"TCPInfo.Snd_ssthresh", Field, 1},
+		{"TCPInfo.State", Field, 1},
+		{"TCPInfo.Total_retrans", Field, 1},
+		{"TCPInfo.Unacked", Field, 1},
+		{"TCPKeepalive", Type, 3},
+		{"TCPKeepalive.Interval", Field, 3},
+		{"TCPKeepalive.OnOff", Field, 3},
+		{"TCPKeepalive.Time", Field, 3},
+		{"TCP_CA_NAME_MAX", Const, 0},
+		{"TCP_CONGCTL", Const, 1},
+		{"TCP_CONGESTION", Const, 0},
+		{"TCP_CONNECTIONTIMEOUT", Const, 0},
+		{"TCP_CORK", Const, 0},
+		{"TCP_DEFER_ACCEPT", Const, 0},
+		{"TCP_ENABLE_ECN", Const, 16},
+		{"TCP_INFO", Const, 0},
+		{"TCP_KEEPALIVE", Const, 0},
+		{"TCP_KEEPCNT", Const, 0},
+		{"TCP_KEEPIDLE", Const, 0},
+		{"TCP_KEEPINIT", Const, 1},
+		{"TCP_KEEPINTVL", Const, 0},
+		{"TCP_LINGER2", Const, 0},
+		{"TCP_MAXBURST", Const, 0},
+		{"TCP_MAXHLEN", Const, 0},
+		{"TCP_MAXOLEN", Const, 0},
+		{"TCP_MAXSEG", Const, 0},
+		{"TCP_MAXWIN", Const, 0},
+		{"TCP_MAX_SACK", Const, 0},
+		{"TCP_MAX_WINSHIFT", Const, 0},
+		{"TCP_MD5SIG", Const, 0},
+		{"TCP_MD5SIG_MAXKEYLEN", Const, 0},
+		{"TCP_MINMSS", Const, 0},
+		{"TCP_MINMSSOVERLOAD", Const, 0},
+		{"TCP_MSS", Const, 0},
+		{"TCP_NODELAY", Const, 0},
+		{"TCP_NOOPT", Const, 0},
+		{"TCP_NOPUSH", Const, 0},
+		{"TCP_NOTSENT_LOWAT", Const, 16},
+		{"TCP_NSTATES", Const, 1},
+		{"TCP_QUICKACK", Const, 0},
+		{"TCP_RXT_CONNDROPTIME", Const, 0},
+		{"TCP_RXT_FINDROP", Const, 0},
+		{"TCP_SACK_ENABLE", Const, 1},
+		{"TCP_SENDMOREACKS", Const, 16},
+		{"TCP_SYNCNT", Const, 0},
+		{"TCP_VENDOR", Const, 3},
+		{"TCP_WINDOW_CLAMP", Const, 0},
+		{"TCSAFLUSH", Const, 1},
+		{"TCSETS", Const, 0},
+		{"TF_DISCONNECT", Const, 0},
+		{"TF_REUSE_SOCKET", Const, 0},
+		{"TF_USE_DEFAULT_WORKER", Const, 0},
+		{"TF_USE_KERNEL_APC", Const, 0},
+		{"TF_USE_SYSTEM_THREAD", Const, 0},
+		{"TF_WRITE_BEHIND", Const, 0},
+		{"TH32CS_INHERIT", Const, 4},
+		{"TH32CS_SNAPALL", Const, 4},
+		{"TH32CS_SNAPHEAPLIST", Const, 4},
+		{"TH32CS_SNAPMODULE", Const, 4},
+		{"TH32CS_SNAPMODULE32", Const, 4},
+		{"TH32CS_SNAPPROCESS", Const, 4},
+		{"TH32CS_SNAPTHREAD", Const, 4},
+		{"TIME_ZONE_ID_DAYLIGHT", Const, 0},
+		{"TIME_ZONE_ID_STANDARD", Const, 0},
+		{"TIME_ZONE_ID_UNKNOWN", Const, 0},
+		{"TIOCCBRK", Const, 0},
+		{"TIOCCDTR", Const, 0},
+		{"TIOCCONS", Const, 0},
+		{"TIOCDCDTIMESTAMP", Const, 0},
+		{"TIOCDRAIN", Const, 0},
+		{"TIOCDSIMICROCODE", Const, 0},
+		{"TIOCEXCL", Const, 0},
+		{"TIOCEXT", Const, 0},
+		{"TIOCFLAG_CDTRCTS", Const, 1},
+		{"TIOCFLAG_CLOCAL", Const, 1},
+		{"TIOCFLAG_CRTSCTS", Const, 1},
+		{"TIOCFLAG_MDMBUF", Const, 1},
+		{"TIOCFLAG_PPS", Const, 1},
+		{"TIOCFLAG_SOFTCAR", Const, 1},
+		{"TIOCFLUSH", Const, 0},
+		{"TIOCGDEV", Const, 0},
+		{"TIOCGDRAINWAIT", Const, 0},
+		{"TIOCGETA", Const, 0},
+		{"TIOCGETD", Const, 0},
+		{"TIOCGFLAGS", Const, 1},
+		{"TIOCGICOUNT", Const, 0},
+		{"TIOCGLCKTRMIOS", Const, 0},
+		{"TIOCGLINED", Const, 1},
+		{"TIOCGPGRP", Const, 0},
+		{"TIOCGPTN", Const, 0},
+		{"TIOCGQSIZE", Const, 1},
+		{"TIOCGRANTPT", Const, 1},
+		{"TIOCGRS485", Const, 0},
+		{"TIOCGSERIAL", Const, 0},
+		{"TIOCGSID", Const, 0},
+		{"TIOCGSIZE", Const, 1},
+		{"TIOCGSOFTCAR", Const, 0},
+		{"TIOCGTSTAMP", Const, 1},
+		{"TIOCGWINSZ", Const, 0},
+		{"TIOCINQ", Const, 0},
+		{"TIOCIXOFF", Const, 0},
+		{"TIOCIXON", Const, 0},
+		{"TIOCLINUX", Const, 0},
+		{"TIOCMBIC", Const, 0},
+		{"TIOCMBIS", Const, 0},
+		{"TIOCMGDTRWAIT", Const, 0},
+		{"TIOCMGET", Const, 0},
+		{"TIOCMIWAIT", Const, 0},
+		{"TIOCMODG", Const, 0},
+		{"TIOCMODS", Const, 0},
+		{"TIOCMSDTRWAIT", Const, 0},
+		{"TIOCMSET", Const, 0},
+		{"TIOCM_CAR", Const, 0},
+		{"TIOCM_CD", Const, 0},
+		{"TIOCM_CTS", Const, 0},
+		{"TIOCM_DCD", Const, 0},
+		{"TIOCM_DSR", Const, 0},
+		{"TIOCM_DTR", Const, 0},
+		{"TIOCM_LE", Const, 0},
+		{"TIOCM_RI", Const, 0},
+		{"TIOCM_RNG", Const, 0},
+		{"TIOCM_RTS", Const, 0},
+		{"TIOCM_SR", Const, 0},
+		{"TIOCM_ST", Const, 0},
+		{"TIOCNOTTY", Const, 0},
+		{"TIOCNXCL", Const, 0},
+		{"TIOCOUTQ", Const, 0},
+		{"TIOCPKT", Const, 0},
+		{"TIOCPKT_DATA", Const, 0},
+		{"TIOCPKT_DOSTOP", Const, 0},
+		{"TIOCPKT_FLUSHREAD", Const, 0},
+		{"TIOCPKT_FLUSHWRITE", Const, 0},
+		{"TIOCPKT_IOCTL", Const, 0},
+		{"TIOCPKT_NOSTOP", Const, 0},
+		{"TIOCPKT_START", Const, 0},
+		{"TIOCPKT_STOP", Const, 0},
+		{"TIOCPTMASTER", Const, 0},
+		{"TIOCPTMGET", Const, 1},
+		{"TIOCPTSNAME", Const, 1},
+		{"TIOCPTYGNAME", Const, 0},
+		{"TIOCPTYGRANT", Const, 0},
+		{"TIOCPTYUNLK", Const, 0},
+		{"TIOCRCVFRAME", Const, 1},
+		{"TIOCREMOTE", Const, 0},
+		{"TIOCSBRK", Const, 0},
+		{"TIOCSCONS", Const, 0},
+		{"TIOCSCTTY", Const, 0},
+		{"TIOCSDRAINWAIT", Const, 0},
+		{"TIOCSDTR", Const, 0},
+		{"TIOCSERCONFIG", Const, 0},
+		{"TIOCSERGETLSR", Const, 0},
+		{"TIOCSERGETMULTI", Const, 0},
+		{"TIOCSERGSTRUCT", Const, 0},
+		{"TIOCSERGWILD", Const, 0},
+		{"TIOCSERSETMULTI", Const, 0},
+		{"TIOCSERSWILD", Const, 0},
+		{"TIOCSER_TEMT", Const, 0},
+		{"TIOCSETA", Const, 0},
+		{"TIOCSETAF", Const, 0},
+		{"TIOCSETAW", Const, 0},
+		{"TIOCSETD", Const, 0},
+		{"TIOCSFLAGS", Const, 1},
+		{"TIOCSIG", Const, 0},
+		{"TIOCSLCKTRMIOS", Const, 0},
+		{"TIOCSLINED", Const, 1},
+		{"TIOCSPGRP", Const, 0},
+		{"TIOCSPTLCK", Const, 0},
+		{"TIOCSQSIZE", Const, 1},
+		{"TIOCSRS485", Const, 0},
+		{"TIOCSSERIAL", Const, 0},
+		{"TIOCSSIZE", Const, 1},
+		{"TIOCSSOFTCAR", Const, 0},
+		{"TIOCSTART", Const, 0},
+		{"TIOCSTAT", Const, 0},
+		{"TIOCSTI", Const, 0},
+		{"TIOCSTOP", Const, 0},
+		{"TIOCSTSTAMP", Const, 1},
+		{"TIOCSWINSZ", Const, 0},
+		{"TIOCTIMESTAMP", Const, 0},
+		{"TIOCUCNTL", Const, 0},
+		{"TIOCVHANGUP", Const, 0},
+		{"TIOCXMTFRAME", Const, 1},
+		{"TOKEN_ADJUST_DEFAULT", Const, 0},
+		{"TOKEN_ADJUST_GROUPS", Const, 0},
+		{"TOKEN_ADJUST_PRIVILEGES", Const, 0},
+		{"TOKEN_ADJUST_SESSIONID", Const, 11},
+		{"TOKEN_ALL_ACCESS", Const, 0},
+		{"TOKEN_ASSIGN_PRIMARY", Const, 0},
+		{"TOKEN_DUPLICATE", Const, 0},
+		{"TOKEN_EXECUTE", Const, 0},
+		{"TOKEN_IMPERSONATE", Const, 0},
+		{"TOKEN_QUERY", Const, 0},
+		{"TOKEN_QUERY_SOURCE", Const, 0},
+		{"TOKEN_READ", Const, 0},
+		{"TOKEN_WRITE", Const, 0},
+		{"TOSTOP", Const, 0},
+		{"TRUNCATE_EXISTING", Const, 0},
+		{"TUNATTACHFILTER", Const, 0},
+		{"TUNDETACHFILTER", Const, 0},
+		{"TUNGETFEATURES", Const, 0},
+		{"TUNGETIFF", Const, 0},
+		{"TUNGETSNDBUF", Const, 0},
+		{"TUNGETVNETHDRSZ", Const, 0},
+		{"TUNSETDEBUG", Const, 0},
+		{"TUNSETGROUP", Const, 0},
+		{"TUNSETIFF", Const, 0},
+		{"TUNSETLINK", Const, 0},
+		{"TUNSETNOCSUM", Const, 0},
+		{"TUNSETOFFLOAD", Const, 0},
+		{"TUNSETOWNER", Const, 0},
+		{"TUNSETPERSIST", Const, 0},
+		{"TUNSETSNDBUF", Const, 0},
+		{"TUNSETTXFILTER", Const, 0},
+		{"TUNSETVNETHDRSZ", Const, 0},
+		{"Tee", Func, 0},
+		{"TerminateProcess", Func, 0},
+		{"Termios", Type, 0},
+		{"Termios.Cc", Field, 0},
+		{"Termios.Cflag", Field, 0},
+		{"Termios.Iflag", Field, 0},
+		{"Termios.Ispeed", Field, 0},
+		{"Termios.Lflag", Field, 0},
+		{"Termios.Line", Field, 0},
+		{"Termios.Oflag", Field, 0},
+		{"Termios.Ospeed", Field, 0},
+		{"Termios.Pad_cgo_0", Field, 0},
+		{"Tgkill", Func, 0},
+		{"Time", Func, 0},
+		{"Time_t", Type, 0},
+		{"Times", Func, 0},
+		{"Timespec", Type, 0},
+		{"Timespec.Nsec", Field, 0},
+		{"Timespec.Pad_cgo_0", Field, 2},
+		{"Timespec.Sec", Field, 0},
+		{"TimespecToNsec", Func, 0},
+		{"Timeval", Type, 0},
+		{"Timeval.Pad_cgo_0", Field, 0},
+		{"Timeval.Sec", Field, 0},
+		{"Timeval.Usec", Field, 0},
+		{"Timeval32", Type, 0},
+		{"Timeval32.Sec", Field, 0},
+		{"Timeval32.Usec", Field, 0},
+		{"TimevalToNsec", Func, 0},
+		{"Timex", Type, 0},
+		{"Timex.Calcnt", Field, 0},
+		{"Timex.Constant", Field, 0},
+		{"Timex.Errcnt", Field, 0},
+		{"Timex.Esterror", Field, 0},
+		{"Timex.Freq", Field, 0},
+		{"Timex.Jitcnt", Field, 0},
+		{"Timex.Jitter", Field, 0},
+		{"Timex.Maxerror", Field, 0},
+		{"Timex.Modes", Field, 0},
+		{"Timex.Offset", Field, 0},
+		{"Timex.Pad_cgo_0", Field, 0},
+		{"Timex.Pad_cgo_1", Field, 0},
+		{"Timex.Pad_cgo_2", Field, 0},
+		{"Timex.Pad_cgo_3", Field, 0},
+		{"Timex.Ppsfreq", Field, 0},
+		{"Timex.Precision", Field, 0},
+		{"Timex.Shift", Field, 0},
+		{"Timex.Stabil", Field, 0},
+		{"Timex.Status", Field, 0},
+		{"Timex.Stbcnt", Field, 0},
+		{"Timex.Tai", Field, 0},
+		{"Timex.Tick", Field, 0},
+		{"Timex.Time", Field, 0},
+		{"Timex.Tolerance", Field, 0},
+		{"Timezoneinformation", Type, 0},
+		{"Timezoneinformation.Bias", Field, 0},
+		{"Timezoneinformation.DaylightBias", Field, 0},
+		{"Timezoneinformation.DaylightDate", Field, 0},
+		{"Timezoneinformation.DaylightName", Field, 0},
+		{"Timezoneinformation.StandardBias", Field, 0},
+		{"Timezoneinformation.StandardDate", Field, 0},
+		{"Timezoneinformation.StandardName", Field, 0},
+		{"Tms", Type, 0},
+		{"Tms.Cstime", Field, 0},
+		{"Tms.Cutime", Field, 0},
+		{"Tms.Stime", Field, 0},
+		{"Tms.Utime", Field, 0},
+		{"Token", Type, 0},
+		{"TokenAccessInformation", Const, 0},
+		{"TokenAuditPolicy", Const, 0},
+		{"TokenDefaultDacl", Const, 0},
+		{"TokenElevation", Const, 0},
+		{"TokenElevationType", Const, 0},
+		{"TokenGroups", Const, 0},
+		{"TokenGroupsAndPrivileges", Const, 0},
+		{"TokenHasRestrictions", Const, 0},
+		{"TokenImpersonationLevel", Const, 0},
+		{"TokenIntegrityLevel", Const, 0},
+		{"TokenLinkedToken", Const, 0},
+		{"TokenLogonSid", Const, 0},
+		{"TokenMandatoryPolicy", Const, 0},
+		{"TokenOrigin", Const, 0},
+		{"TokenOwner", Const, 0},
+		{"TokenPrimaryGroup", Const, 0},
+		{"TokenPrivileges", Const, 0},
+		{"TokenRestrictedSids", Const, 0},
+		{"TokenSandBoxInert", Const, 0},
+		{"TokenSessionId", Const, 0},
+		{"TokenSessionReference", Const, 0},
+		{"TokenSource", Const, 0},
+		{"TokenStatistics", Const, 0},
+		{"TokenType", Const, 0},
+		{"TokenUIAccess", Const, 0},
+		{"TokenUser", Const, 0},
+		{"TokenVirtualizationAllowed", Const, 0},
+		{"TokenVirtualizationEnabled", Const, 0},
+		{"Tokenprimarygroup", Type, 0},
+		{"Tokenprimarygroup.PrimaryGroup", Field, 0},
+		{"Tokenuser", Type, 0},
+		{"Tokenuser.User", Field, 0},
+		{"TranslateAccountName", Func, 0},
+		{"TranslateName", Func, 0},
+		{"TransmitFile", Func, 0},
+		{"TransmitFileBuffers", Type, 0},
+		{"TransmitFileBuffers.Head", Field, 0},
+		{"TransmitFileBuffers.HeadLength", Field, 0},
+		{"TransmitFileBuffers.Tail", Field, 0},
+		{"TransmitFileBuffers.TailLength", Field, 0},
+		{"Truncate", Func, 0},
+		{"UNIX_PATH_MAX", Const, 12},
+		{"USAGE_MATCH_TYPE_AND", Const, 0},
+		{"USAGE_MATCH_TYPE_OR", Const, 0},
+		{"UTF16FromString", Func, 1},
+		{"UTF16PtrFromString", Func, 1},
+		{"UTF16ToString", Func, 0},
+		{"Ucred", Type, 0},
+		{"Ucred.Gid", Field, 0},
+		{"Ucred.Pid", Field, 0},
+		{"Ucred.Uid", Field, 0},
+		{"Umask", Func, 0},
+		{"Uname", Func, 0},
+		{"Undelete", Func, 0},
+		{"UnixCredentials", Func, 0},
+		{"UnixRights", Func, 0},
+		{"Unlink", Func, 0},
+		{"Unlinkat", Func, 0},
+		{"UnmapViewOfFile", Func, 0},
+		{"Unmount", Func, 0},
+		{"Unsetenv", Func, 4},
+		{"Unshare", Func, 0},
+		{"UserInfo10", Type, 0},
+		{"UserInfo10.Comment", Field, 0},
+		{"UserInfo10.FullName", Field, 0},
+		{"UserInfo10.Name", Field, 0},
+		{"UserInfo10.UsrComment", Field, 0},
+		{"Ustat", Func, 0},
+		{"Ustat_t", Type, 0},
+		{"Ustat_t.Fname", Field, 0},
+		{"Ustat_t.Fpack", Field, 0},
+		{"Ustat_t.Pad_cgo_0", Field, 0},
+		{"Ustat_t.Pad_cgo_1", Field, 0},
+		{"Ustat_t.Tfree", Field, 0},
+		{"Ustat_t.Tinode", Field, 0},
+		{"Utimbuf", Type, 0},
+		{"Utimbuf.Actime", Field, 0},
+		{"Utimbuf.Modtime", Field, 0},
+		{"Utime", Func, 0},
+		{"Utimes", Func, 0},
+		{"UtimesNano", Func, 1},
+		{"Utsname", Type, 0},
+		{"Utsname.Domainname", Field, 0},
+		{"Utsname.Machine", Field, 0},
+		{"Utsname.Nodename", Field, 0},
+		{"Utsname.Release", Field, 0},
+		{"Utsname.Sysname", Field, 0},
+		{"Utsname.Version", Field, 0},
+		{"VDISCARD", Const, 0},
+		{"VDSUSP", Const, 1},
+		{"VEOF", Const, 0},
+		{"VEOL", Const, 0},
+		{"VEOL2", Const, 0},
+		{"VERASE", Const, 0},
+		{"VERASE2", Const, 1},
+		{"VINTR", Const, 0},
+		{"VKILL", Const, 0},
+		{"VLNEXT", Const, 0},
+		{"VMIN", Const, 0},
+		{"VQUIT", Const, 0},
+		{"VREPRINT", Const, 0},
+		{"VSTART", Const, 0},
+		{"VSTATUS", Const, 1},
+		{"VSTOP", Const, 0},
+		{"VSUSP", Const, 0},
+		{"VSWTC", Const, 0},
+		{"VT0", Const, 1},
+		{"VT1", Const, 1},
+		{"VTDLY", Const, 1},
+		{"VTIME", Const, 0},
+		{"VWERASE", Const, 0},
+		{"VirtualLock", Func, 0},
+		{"VirtualUnlock", Func, 0},
+		{"WAIT_ABANDONED", Const, 0},
+		{"WAIT_FAILED", Const, 0},
+		{"WAIT_OBJECT_0", Const, 0},
+		{"WAIT_TIMEOUT", Const, 0},
+		{"WALL", Const, 0},
+		{"WALLSIG", Const, 1},
+		{"WALTSIG", Const, 1},
+		{"WCLONE", Const, 0},
+		{"WCONTINUED", Const, 0},
+		{"WCOREFLAG", Const, 0},
+		{"WEXITED", Const, 0},
+		{"WLINUXCLONE", Const, 0},
+		{"WNOHANG", Const, 0},
+		{"WNOTHREAD", Const, 0},
+		{"WNOWAIT", Const, 0},
+		{"WNOZOMBIE", Const, 1},
+		{"WOPTSCHECKED", Const, 1},
+		{"WORDSIZE", Const, 0},
+		{"WSABuf", Type, 0},
+		{"WSABuf.Buf", Field, 0},
+		{"WSABuf.Len", Field, 0},
+		{"WSACleanup", Func, 0},
+		{"WSADESCRIPTION_LEN", Const, 0},
+		{"WSAData", Type, 0},
+		{"WSAData.Description", Field, 0},
+		{"WSAData.HighVersion", Field, 0},
+		{"WSAData.MaxSockets", Field, 0},
+		{"WSAData.MaxUdpDg", Field, 0},
+		{"WSAData.SystemStatus", Field, 0},
+		{"WSAData.VendorInfo", Field, 0},
+		{"WSAData.Version", Field, 0},
+		{"WSAEACCES", Const, 2},
+		{"WSAECONNABORTED", Const, 9},
+		{"WSAECONNRESET", Const, 3},
+		{"WSAENOPROTOOPT", Const, 23},
+		{"WSAEnumProtocols", Func, 2},
+		{"WSAID_CONNECTEX", Var, 1},
+		{"WSAIoctl", Func, 0},
+		{"WSAPROTOCOL_LEN", Const, 2},
+		{"WSAProtocolChain", Type, 2},
+		{"WSAProtocolChain.ChainEntries", Field, 2},
+		{"WSAProtocolChain.ChainLen", Field, 2},
+		{"WSAProtocolInfo", Type, 2},
+		{"WSAProtocolInfo.AddressFamily", Field, 2},
+		{"WSAProtocolInfo.CatalogEntryId", Field, 2},
+		{"WSAProtocolInfo.MaxSockAddr", Field, 2},
+		{"WSAProtocolInfo.MessageSize", Field, 2},
+		{"WSAProtocolInfo.MinSockAddr", Field, 2},
+		{"WSAProtocolInfo.NetworkByteOrder", Field, 2},
+		{"WSAProtocolInfo.Protocol", Field, 2},
+		{"WSAProtocolInfo.ProtocolChain", Field, 2},
+		{"WSAProtocolInfo.ProtocolMaxOffset", Field, 2},
+		{"WSAProtocolInfo.ProtocolName", Field, 2},
+		{"WSAProtocolInfo.ProviderFlags", Field, 2},
+		{"WSAProtocolInfo.ProviderId", Field, 2},
+		{"WSAProtocolInfo.ProviderReserved", Field, 2},
+		{"WSAProtocolInfo.SecurityScheme", Field, 2},
+		{"WSAProtocolInfo.ServiceFlags1", Field, 2},
+		{"WSAProtocolInfo.ServiceFlags2", Field, 2},
+		{"WSAProtocolInfo.ServiceFlags3", Field, 2},
+		{"WSAProtocolInfo.ServiceFlags4", Field, 2},
+		{"WSAProtocolInfo.SocketType", Field, 2},
+		{"WSAProtocolInfo.Version", Field, 2},
+		{"WSARecv", Func, 0},
+		{"WSARecvFrom", Func, 0},
+		{"WSASYS_STATUS_LEN", Const, 0},
+		{"WSASend", Func, 0},
+		{"WSASendTo", Func, 0},
+		{"WSASendto", Func, 0},
+		{"WSAStartup", Func, 0},
+		{"WSTOPPED", Const, 0},
+		{"WTRAPPED", Const, 1},
+		{"WUNTRACED", Const, 0},
+		{"Wait4", Func, 0},
+		{"WaitForSingleObject", Func, 0},
+		{"WaitStatus", Type, 0},
+		{"WaitStatus.ExitCode", Field, 0},
+		{"Win32FileAttributeData", Type, 0},
+		{"Win32FileAttributeData.CreationTime", Field, 0},
+		{"Win32FileAttributeData.FileAttributes", Field, 0},
+		{"Win32FileAttributeData.FileSizeHigh", Field, 0},
+		{"Win32FileAttributeData.FileSizeLow", Field, 0},
+		{"Win32FileAttributeData.LastAccessTime", Field, 0},
+		{"Win32FileAttributeData.LastWriteTime", Field, 0},
+		{"Win32finddata", Type, 0},
+		{"Win32finddata.AlternateFileName", Field, 0},
+		{"Win32finddata.CreationTime", Field, 0},
+		{"Win32finddata.FileAttributes", Field, 0},
+		{"Win32finddata.FileName", Field, 0},
+		{"Win32finddata.FileSizeHigh", Field, 0},
+		{"Win32finddata.FileSizeLow", Field, 0},
+		{"Win32finddata.LastAccessTime", Field, 0},
+		{"Win32finddata.LastWriteTime", Field, 0},
+		{"Win32finddata.Reserved0", Field, 0},
+		{"Win32finddata.Reserved1", Field, 0},
+		{"Write", Func, 0},
+		{"WriteConsole", Func, 1},
+		{"WriteFile", Func, 0},
+		{"X509_ASN_ENCODING", Const, 0},
+		{"XCASE", Const, 0},
+		{"XP1_CONNECTIONLESS", Const, 2},
+		{"XP1_CONNECT_DATA", Const, 2},
+		{"XP1_DISCONNECT_DATA", Const, 2},
+		{"XP1_EXPEDITED_DATA", Const, 2},
+		{"XP1_GRACEFUL_CLOSE", Const, 2},
+		{"XP1_GUARANTEED_DELIVERY", Const, 2},
+		{"XP1_GUARANTEED_ORDER", Const, 2},
+		{"XP1_IFS_HANDLES", Const, 2},
+		{"XP1_MESSAGE_ORIENTED", Const, 2},
+		{"XP1_MULTIPOINT_CONTROL_PLANE", Const, 2},
+		{"XP1_MULTIPOINT_DATA_PLANE", Const, 2},
+		{"XP1_PARTIAL_MESSAGE", Const, 2},
+		{"XP1_PSEUDO_STREAM", Const, 2},
+		{"XP1_QOS_SUPPORTED", Const, 2},
+		{"XP1_SAN_SUPPORT_SDP", Const, 2},
+		{"XP1_SUPPORT_BROADCAST", Const, 2},
+		{"XP1_SUPPORT_MULTIPOINT", Const, 2},
+		{"XP1_UNI_RECV", Const, 2},
+		{"XP1_UNI_SEND", Const, 2},
+	},
+	"syscall/js": {
+		{"CopyBytesToGo", Func, 0},
+		{"CopyBytesToJS", Func, 0},
+		{"Error", Type, 0},
+		{"Func", Type, 0},
+		{"FuncOf", Func, 0},
+		{"Global", Func, 0},
+		{"Null", Func, 0},
+		{"Type", Type, 0},
+		{"TypeBoolean", Const, 0},
+		{"TypeFunction", Const, 0},
+		{"TypeNull", Const, 0},
+		{"TypeNumber", Const, 0},
+		{"TypeObject", Const, 0},
+		{"TypeString", Const, 0},
+		{"TypeSymbol", Const, 0},
+		{"TypeUndefined", Const, 0},
+		{"Undefined", Func, 0},
+		{"Value", Type, 0},
+		{"ValueError", Type, 0},
+		{"ValueOf", Func, 0},
+	},
+	"testing": {
+		{"(*B).Chdir", Method, 24},
+		{"(*B).Cleanup", Method, 14},
+		{"(*B).Context", Method, 24},
+		{"(*B).Elapsed", Method, 20},
+		{"(*B).Error", Method, 0},
+		{"(*B).Errorf", Method, 0},
+		{"(*B).Fail", Method, 0},
+		{"(*B).FailNow", Method, 0},
+		{"(*B).Failed", Method, 0},
+		{"(*B).Fatal", Method, 0},
+		{"(*B).Fatalf", Method, 0},
+		{"(*B).Helper", Method, 9},
+		{"(*B).Log", Method, 0},
+		{"(*B).Logf", Method, 0},
+		{"(*B).Loop", Method, 24},
+		{"(*B).Name", Method, 8},
+		{"(*B).ReportAllocs", Method, 1},
+		{"(*B).ReportMetric", Method, 13},
+		{"(*B).ResetTimer", Method, 0},
+		{"(*B).Run", Method, 7},
+		{"(*B).RunParallel", Method, 3},
+		{"(*B).SetBytes", Method, 0},
+		{"(*B).SetParallelism", Method, 3},
+		{"(*B).Setenv", Method, 17},
+		{"(*B).Skip", Method, 1},
+		{"(*B).SkipNow", Method, 1},
+		{"(*B).Skipf", Method, 1},
+		{"(*B).Skipped", Method, 1},
+		{"(*B).StartTimer", Method, 0},
+		{"(*B).StopTimer", Method, 0},
+		{"(*B).TempDir", Method, 15},
+		{"(*F).Add", Method, 18},
+		{"(*F).Chdir", Method, 24},
+		{"(*F).Cleanup", Method, 18},
+		{"(*F).Context", Method, 24},
+		{"(*F).Error", Method, 18},
+		{"(*F).Errorf", Method, 18},
+		{"(*F).Fail", Method, 18},
+		{"(*F).FailNow", Method, 18},
+		{"(*F).Failed", Method, 18},
+		{"(*F).Fatal", Method, 18},
+		{"(*F).Fatalf", Method, 18},
+		{"(*F).Fuzz", Method, 18},
+		{"(*F).Helper", Method, 18},
+		{"(*F).Log", Method, 18},
+		{"(*F).Logf", Method, 18},
+		{"(*F).Name", Method, 18},
+		{"(*F).Setenv", Method, 18},
+		{"(*F).Skip", Method, 18},
+		{"(*F).SkipNow", Method, 18},
+		{"(*F).Skipf", Method, 18},
+		{"(*F).Skipped", Method, 18},
+		{"(*F).TempDir", Method, 18},
+		{"(*M).Run", Method, 4},
+		{"(*PB).Next", Method, 3},
+		{"(*T).Chdir", Method, 24},
+		{"(*T).Cleanup", Method, 14},
+		{"(*T).Context", Method, 24},
+		{"(*T).Deadline", Method, 15},
+		{"(*T).Error", Method, 0},
+		{"(*T).Errorf", Method, 0},
+		{"(*T).Fail", Method, 0},
+		{"(*T).FailNow", Method, 0},
+		{"(*T).Failed", Method, 0},
+		{"(*T).Fatal", Method, 0},
+		{"(*T).Fatalf", Method, 0},
+		{"(*T).Helper", Method, 9},
+		{"(*T).Log", Method, 0},
+		{"(*T).Logf", Method, 0},
+		{"(*T).Name", Method, 8},
+		{"(*T).Parallel", Method, 0},
+		{"(*T).Run", Method, 7},
+		{"(*T).Setenv", Method, 17},
+		{"(*T).Skip", Method, 1},
+		{"(*T).SkipNow", Method, 1},
+		{"(*T).Skipf", Method, 1},
+		{"(*T).Skipped", Method, 1},
+		{"(*T).TempDir", Method, 15},
+		{"(BenchmarkResult).AllocedBytesPerOp", Method, 1},
+		{"(BenchmarkResult).AllocsPerOp", Method, 1},
+		{"(BenchmarkResult).MemString", Method, 1},
+		{"(BenchmarkResult).NsPerOp", Method, 0},
+		{"(BenchmarkResult).String", Method, 0},
+		{"AllocsPerRun", Func, 1},
+		{"B", Type, 0},
+		{"B.N", Field, 0},
+		{"Benchmark", Func, 0},
+		{"BenchmarkResult", Type, 0},
+		{"BenchmarkResult.Bytes", Field, 0},
+		{"BenchmarkResult.Extra", Field, 13},
+		{"BenchmarkResult.MemAllocs", Field, 1},
+		{"BenchmarkResult.MemBytes", Field, 1},
+		{"BenchmarkResult.N", Field, 0},
+		{"BenchmarkResult.T", Field, 0},
+		{"Cover", Type, 2},
+		{"Cover.Blocks", Field, 2},
+		{"Cover.Counters", Field, 2},
+		{"Cover.CoveredPackages", Field, 2},
+		{"Cover.Mode", Field, 2},
+		{"CoverBlock", Type, 2},
+		{"CoverBlock.Col0", Field, 2},
+		{"CoverBlock.Col1", Field, 2},
+		{"CoverBlock.Line0", Field, 2},
+		{"CoverBlock.Line1", Field, 2},
+		{"CoverBlock.Stmts", Field, 2},
+		{"CoverMode", Func, 8},
+		{"Coverage", Func, 4},
+		{"F", Type, 18},
+		{"Init", Func, 13},
+		{"InternalBenchmark", Type, 0},
+		{"InternalBenchmark.F", Field, 0},
+		{"InternalBenchmark.Name", Field, 0},
+		{"InternalExample", Type, 0},
+		{"InternalExample.F", Field, 0},
+		{"InternalExample.Name", Field, 0},
+		{"InternalExample.Output", Field, 0},
+		{"InternalExample.Unordered", Field, 7},
+		{"InternalFuzzTarget", Type, 18},
+		{"InternalFuzzTarget.Fn", Field, 18},
+		{"InternalFuzzTarget.Name", Field, 18},
+		{"InternalTest", Type, 0},
+		{"InternalTest.F", Field, 0},
+		{"InternalTest.Name", Field, 0},
+		{"M", Type, 4},
+		{"Main", Func, 0},
+		{"MainStart", Func, 4},
+		{"PB", Type, 3},
+		{"RegisterCover", Func, 2},
+		{"RunBenchmarks", Func, 0},
+		{"RunExamples", Func, 0},
+		{"RunTests", Func, 0},
+		{"Short", Func, 0},
+		{"T", Type, 0},
+		{"TB", Type, 2},
+		{"Testing", Func, 21},
+		{"Verbose", Func, 1},
+	},
+	"testing/fstest": {
+		{"(MapFS).Glob", Method, 16},
+		{"(MapFS).Open", Method, 16},
+		{"(MapFS).ReadDir", Method, 16},
+		{"(MapFS).ReadFile", Method, 16},
+		{"(MapFS).Stat", Method, 16},
+		{"(MapFS).Sub", Method, 16},
+		{"MapFS", Type, 16},
+		{"MapFile", Type, 16},
+		{"MapFile.Data", Field, 16},
+		{"MapFile.ModTime", Field, 16},
+		{"MapFile.Mode", Field, 16},
+		{"MapFile.Sys", Field, 16},
+		{"TestFS", Func, 16},
+	},
+	"testing/iotest": {
+		{"DataErrReader", Func, 0},
+		{"ErrReader", Func, 16},
+		{"ErrTimeout", Var, 0},
+		{"HalfReader", Func, 0},
+		{"NewReadLogger", Func, 0},
+		{"NewWriteLogger", Func, 0},
+		{"OneByteReader", Func, 0},
+		{"TestReader", Func, 16},
+		{"TimeoutReader", Func, 0},
+		{"TruncateWriter", Func, 0},
+	},
+	"testing/quick": {
+		{"(*CheckEqualError).Error", Method, 0},
+		{"(*CheckError).Error", Method, 0},
+		{"(SetupError).Error", Method, 0},
+		{"Check", Func, 0},
+		{"CheckEqual", Func, 0},
+		{"CheckEqualError", Type, 0},
+		{"CheckEqualError.CheckError", Field, 0},
+		{"CheckEqualError.Out1", Field, 0},
+		{"CheckEqualError.Out2", Field, 0},
+		{"CheckError", Type, 0},
+		{"CheckError.Count", Field, 0},
+		{"CheckError.In", Field, 0},
+		{"Config", Type, 0},
+		{"Config.MaxCount", Field, 0},
+		{"Config.MaxCountScale", Field, 0},
+		{"Config.Rand", Field, 0},
+		{"Config.Values", Field, 0},
+		{"Generator", Type, 0},
+		{"SetupError", Type, 0},
+		{"Value", Func, 0},
+	},
+	"testing/slogtest": {
+		{"Run", Func, 22},
+		{"TestHandler", Func, 21},
+	},
+	"text/scanner": {
+		{"(*Position).IsValid", Method, 0},
+		{"(*Scanner).Init", Method, 0},
+		{"(*Scanner).IsValid", Method, 0},
+		{"(*Scanner).Next", Method, 0},
+		{"(*Scanner).Peek", Method, 0},
+		{"(*Scanner).Pos", Method, 0},
+		{"(*Scanner).Scan", Method, 0},
+		{"(*Scanner).TokenText", Method, 0},
+		{"(Position).String", Method, 0},
+		{"(Scanner).String", Method, 0},
+		{"Char", Const, 0},
+		{"Comment", Const, 0},
+		{"EOF", Const, 0},
+		{"Float", Const, 0},
+		{"GoTokens", Const, 0},
+		{"GoWhitespace", Const, 0},
+		{"Ident", Const, 0},
+		{"Int", Const, 0},
+		{"Position", Type, 0},
+		{"Position.Column", Field, 0},
+		{"Position.Filename", Field, 0},
+		{"Position.Line", Field, 0},
+		{"Position.Offset", Field, 0},
+		{"RawString", Const, 0},
+		{"ScanChars", Const, 0},
+		{"ScanComments", Const, 0},
+		{"ScanFloats", Const, 0},
+		{"ScanIdents", Const, 0},
+		{"ScanInts", Const, 0},
+		{"ScanRawStrings", Const, 0},
+		{"ScanStrings", Const, 0},
+		{"Scanner", Type, 0},
+		{"Scanner.Error", Field, 0},
+		{"Scanner.ErrorCount", Field, 0},
+		{"Scanner.IsIdentRune", Field, 4},
+		{"Scanner.Mode", Field, 0},
+		{"Scanner.Position", Field, 0},
+		{"Scanner.Whitespace", Field, 0},
+		{"SkipComments", Const, 0},
+		{"String", Const, 0},
+		{"TokenString", Func, 0},
+	},
+	"text/tabwriter": {
+		{"(*Writer).Flush", Method, 0},
+		{"(*Writer).Init", Method, 0},
+		{"(*Writer).Write", Method, 0},
+		{"AlignRight", Const, 0},
+		{"Debug", Const, 0},
+		{"DiscardEmptyColumns", Const, 0},
+		{"Escape", Const, 0},
+		{"FilterHTML", Const, 0},
+		{"NewWriter", Func, 0},
+		{"StripEscape", Const, 0},
+		{"TabIndent", Const, 0},
+		{"Writer", Type, 0},
+	},
+	"text/template": {
+		{"(*Template).AddParseTree", Method, 0},
+		{"(*Template).Clone", Method, 0},
+		{"(*Template).DefinedTemplates", Method, 5},
+		{"(*Template).Delims", Method, 0},
+		{"(*Template).Execute", Method, 0},
+		{"(*Template).ExecuteTemplate", Method, 0},
+		{"(*Template).Funcs", Method, 0},
+		{"(*Template).Lookup", Method, 0},
+		{"(*Template).Name", Method, 0},
+		{"(*Template).New", Method, 0},
+		{"(*Template).Option", Method, 5},
+		{"(*Template).Parse", Method, 0},
+		{"(*Template).ParseFS", Method, 16},
+		{"(*Template).ParseFiles", Method, 0},
+		{"(*Template).ParseGlob", Method, 0},
+		{"(*Template).Templates", Method, 0},
+		{"(ExecError).Error", Method, 6},
+		{"(ExecError).Unwrap", Method, 13},
+		{"(Template).Copy", Method, 2},
+		{"(Template).ErrorContext", Method, 1},
+		{"ExecError", Type, 6},
+		{"ExecError.Err", Field, 6},
+		{"ExecError.Name", Field, 6},
+		{"FuncMap", Type, 0},
+		{"HTMLEscape", Func, 0},
+		{"HTMLEscapeString", Func, 0},
+		{"HTMLEscaper", Func, 0},
+		{"IsTrue", Func, 6},
+		{"JSEscape", Func, 0},
+		{"JSEscapeString", Func, 0},
+		{"JSEscaper", Func, 0},
+		{"Must", Func, 0},
+		{"New", Func, 0},
+		{"ParseFS", Func, 16},
+		{"ParseFiles", Func, 0},
+		{"ParseGlob", Func, 0},
+		{"Template", Type, 0},
+		{"Template.Tree", Field, 0},
+		{"URLQueryEscaper", Func, 0},
+	},
+	"text/template/parse": {
+		{"(*ActionNode).Copy", Method, 0},
+		{"(*ActionNode).String", Method, 0},
+		{"(*BoolNode).Copy", Method, 0},
+		{"(*BoolNode).String", Method, 0},
+		{"(*BranchNode).Copy", Method, 4},
+		{"(*BranchNode).String", Method, 0},
+		{"(*BreakNode).Copy", Method, 18},
+		{"(*BreakNode).String", Method, 18},
+		{"(*ChainNode).Add", Method, 1},
+		{"(*ChainNode).Copy", Method, 1},
+		{"(*ChainNode).String", Method, 1},
+		{"(*CommandNode).Copy", Method, 0},
+		{"(*CommandNode).String", Method, 0},
+		{"(*CommentNode).Copy", Method, 16},
+		{"(*CommentNode).String", Method, 16},
+		{"(*ContinueNode).Copy", Method, 18},
+		{"(*ContinueNode).String", Method, 18},
+		{"(*DotNode).Copy", Method, 0},
+		{"(*DotNode).String", Method, 0},
+		{"(*DotNode).Type", Method, 0},
+		{"(*FieldNode).Copy", Method, 0},
+		{"(*FieldNode).String", Method, 0},
+		{"(*IdentifierNode).Copy", Method, 0},
+		{"(*IdentifierNode).SetPos", Method, 1},
+		{"(*IdentifierNode).SetTree", Method, 4},
+		{"(*IdentifierNode).String", Method, 0},
+		{"(*IfNode).Copy", Method, 0},
+		{"(*IfNode).String", Method, 0},
+		{"(*ListNode).Copy", Method, 0},
+		{"(*ListNode).CopyList", Method, 0},
+		{"(*ListNode).String", Method, 0},
+		{"(*NilNode).Copy", Method, 1},
+		{"(*NilNode).String", Method, 1},
+		{"(*NilNode).Type", Method, 1},
+		{"(*NumberNode).Copy", Method, 0},
+		{"(*NumberNode).String", Method, 0},
+		{"(*PipeNode).Copy", Method, 0},
+		{"(*PipeNode).CopyPipe", Method, 0},
+		{"(*PipeNode).String", Method, 0},
+		{"(*RangeNode).Copy", Method, 0},
+		{"(*RangeNode).String", Method, 0},
+		{"(*StringNode).Copy", Method, 0},
+		{"(*StringNode).String", Method, 0},
+		{"(*TemplateNode).Copy", Method, 0},
+		{"(*TemplateNode).String", Method, 0},
+		{"(*TextNode).Copy", Method, 0},
+		{"(*TextNode).String", Method, 0},
+		{"(*Tree).Copy", Method, 2},
+		{"(*Tree).ErrorContext", Method, 1},
+		{"(*Tree).Parse", Method, 0},
+		{"(*VariableNode).Copy", Method, 0},
+		{"(*VariableNode).String", Method, 0},
+		{"(*WithNode).Copy", Method, 0},
+		{"(*WithNode).String", Method, 0},
+		{"(ActionNode).Position", Method, 1},
+		{"(ActionNode).Type", Method, 0},
+		{"(BoolNode).Position", Method, 1},
+		{"(BoolNode).Type", Method, 0},
+		{"(BranchNode).Position", Method, 1},
+		{"(BranchNode).Type", Method, 0},
+		{"(BreakNode).Position", Method, 18},
+		{"(BreakNode).Type", Method, 18},
+		{"(ChainNode).Position", Method, 1},
+		{"(ChainNode).Type", Method, 1},
+		{"(CommandNode).Position", Method, 1},
+		{"(CommandNode).Type", Method, 0},
+		{"(CommentNode).Position", Method, 16},
+		{"(CommentNode).Type", Method, 16},
+		{"(ContinueNode).Position", Method, 18},
+		{"(ContinueNode).Type", Method, 18},
+		{"(DotNode).Position", Method, 1},
+		{"(FieldNode).Position", Method, 1},
+		{"(FieldNode).Type", Method, 0},
+		{"(IdentifierNode).Position", Method, 1},
+		{"(IdentifierNode).Type", Method, 0},
+		{"(IfNode).Position", Method, 1},
+		{"(IfNode).Type", Method, 0},
+		{"(ListNode).Position", Method, 1},
+		{"(ListNode).Type", Method, 0},
+		{"(NilNode).Position", Method, 1},
+		{"(NodeType).Type", Method, 0},
+		{"(NumberNode).Position", Method, 1},
+		{"(NumberNode).Type", Method, 0},
+		{"(PipeNode).Position", Method, 1},
+		{"(PipeNode).Type", Method, 0},
+		{"(Pos).Position", Method, 1},
+		{"(RangeNode).Position", Method, 1},
+		{"(RangeNode).Type", Method, 0},
+		{"(StringNode).Position", Method, 1},
+		{"(StringNode).Type", Method, 0},
+		{"(TemplateNode).Position", Method, 1},
+		{"(TemplateNode).Type", Method, 0},
+		{"(TextNode).Position", Method, 1},
+		{"(TextNode).Type", Method, 0},
+		{"(VariableNode).Position", Method, 1},
+		{"(VariableNode).Type", Method, 0},
+		{"(WithNode).Position", Method, 1},
+		{"(WithNode).Type", Method, 0},
+		{"ActionNode", Type, 0},
+		{"ActionNode.Line", Field, 0},
+		{"ActionNode.NodeType", Field, 0},
+		{"ActionNode.Pipe", Field, 0},
+		{"ActionNode.Pos", Field, 1},
+		{"BoolNode", Type, 0},
+		{"BoolNode.NodeType", Field, 0},
+		{"BoolNode.Pos", Field, 1},
+		{"BoolNode.True", Field, 0},
+		{"BranchNode", Type, 0},
+		{"BranchNode.ElseList", Field, 0},
+		{"BranchNode.Line", Field, 0},
+		{"BranchNode.List", Field, 0},
+		{"BranchNode.NodeType", Field, 0},
+		{"BranchNode.Pipe", Field, 0},
+		{"BranchNode.Pos", Field, 1},
+		{"BreakNode", Type, 18},
+		{"BreakNode.Line", Field, 18},
+		{"BreakNode.NodeType", Field, 18},
+		{"BreakNode.Pos", Field, 18},
+		{"ChainNode", Type, 1},
+		{"ChainNode.Field", Field, 1},
+		{"ChainNode.Node", Field, 1},
+		{"ChainNode.NodeType", Field, 1},
+		{"ChainNode.Pos", Field, 1},
+		{"CommandNode", Type, 0},
+		{"CommandNode.Args", Field, 0},
+		{"CommandNode.NodeType", Field, 0},
+		{"CommandNode.Pos", Field, 1},
+		{"CommentNode", Type, 16},
+		{"CommentNode.NodeType", Field, 16},
+		{"CommentNode.Pos", Field, 16},
+		{"CommentNode.Text", Field, 16},
+		{"ContinueNode", Type, 18},
+		{"ContinueNode.Line", Field, 18},
+		{"ContinueNode.NodeType", Field, 18},
+		{"ContinueNode.Pos", Field, 18},
+		{"DotNode", Type, 0},
+		{"DotNode.NodeType", Field, 4},
+		{"DotNode.Pos", Field, 1},
+		{"FieldNode", Type, 0},
+		{"FieldNode.Ident", Field, 0},
+		{"FieldNode.NodeType", Field, 0},
+		{"FieldNode.Pos", Field, 1},
+		{"IdentifierNode", Type, 0},
+		{"IdentifierNode.Ident", Field, 0},
+		{"IdentifierNode.NodeType", Field, 0},
+		{"IdentifierNode.Pos", Field, 1},
+		{"IfNode", Type, 0},
+		{"IfNode.BranchNode", Field, 0},
+		{"IsEmptyTree", Func, 0},
+		{"ListNode", Type, 0},
+		{"ListNode.NodeType", Field, 0},
+		{"ListNode.Nodes", Field, 0},
+		{"ListNode.Pos", Field, 1},
+		{"Mode", Type, 16},
+		{"New", Func, 0},
+		{"NewIdentifier", Func, 0},
+		{"NilNode", Type, 1},
+		{"NilNode.NodeType", Field, 4},
+		{"NilNode.Pos", Field, 1},
+		{"Node", Type, 0},
+		{"NodeAction", Const, 0},
+		{"NodeBool", Const, 0},
+		{"NodeBreak", Const, 18},
+		{"NodeChain", Const, 1},
+		{"NodeCommand", Const, 0},
+		{"NodeComment", Const, 16},
+		{"NodeContinue", Const, 18},
+		{"NodeDot", Const, 0},
+		{"NodeField", Const, 0},
+		{"NodeIdentifier", Const, 0},
+		{"NodeIf", Const, 0},
+		{"NodeList", Const, 0},
+		{"NodeNil", Const, 1},
+		{"NodeNumber", Const, 0},
+		{"NodePipe", Const, 0},
+		{"NodeRange", Const, 0},
+		{"NodeString", Const, 0},
+		{"NodeTemplate", Const, 0},
+		{"NodeText", Const, 0},
+		{"NodeType", Type, 0},
+		{"NodeVariable", Const, 0},
+		{"NodeWith", Const, 0},
+		{"NumberNode", Type, 0},
+		{"NumberNode.Complex128", Field, 0},
+		{"NumberNode.Float64", Field, 0},
+		{"NumberNode.Int64", Field, 0},
+		{"NumberNode.IsComplex", Field, 0},
+		{"NumberNode.IsFloat", Field, 0},
+		{"NumberNode.IsInt", Field, 0},
+		{"NumberNode.IsUint", Field, 0},
+		{"NumberNode.NodeType", Field, 0},
+		{"NumberNode.Pos", Field, 1},
+		{"NumberNode.Text", Field, 0},
+		{"NumberNode.Uint64", Field, 0},
+		{"Parse", Func, 0},
+		{"ParseComments", Const, 16},
+		{"PipeNode", Type, 0},
+		{"PipeNode.Cmds", Field, 0},
+		{"PipeNode.Decl", Field, 0},
+		{"PipeNode.IsAssign", Field, 11},
+		{"PipeNode.Line", Field, 0},
+		{"PipeNode.NodeType", Field, 0},
+		{"PipeNode.Pos", Field, 1},
+		{"Pos", Type, 1},
+		{"RangeNode", Type, 0},
+		{"RangeNode.BranchNode", Field, 0},
+		{"SkipFuncCheck", Const, 17},
+		{"StringNode", Type, 0},
+		{"StringNode.NodeType", Field, 0},
+		{"StringNode.Pos", Field, 1},
+		{"StringNode.Quoted", Field, 0},
+		{"StringNode.Text", Field, 0},
+		{"TemplateNode", Type, 0},
+		{"TemplateNode.Line", Field, 0},
+		{"TemplateNode.Name", Field, 0},
+		{"TemplateNode.NodeType", Field, 0},
+		{"TemplateNode.Pipe", Field, 0},
+		{"TemplateNode.Pos", Field, 1},
+		{"TextNode", Type, 0},
+		{"TextNode.NodeType", Field, 0},
+		{"TextNode.Pos", Field, 1},
+		{"TextNode.Text", Field, 0},
+		{"Tree", Type, 0},
+		{"Tree.Mode", Field, 16},
+		{"Tree.Name", Field, 0},
+		{"Tree.ParseName", Field, 1},
+		{"Tree.Root", Field, 0},
+		{"VariableNode", Type, 0},
+		{"VariableNode.Ident", Field, 0},
+		{"VariableNode.NodeType", Field, 0},
+		{"VariableNode.Pos", Field, 1},
+		{"WithNode", Type, 0},
+		{"WithNode.BranchNode", Field, 0},
+	},
+	"time": {
+		{"(*Location).String", Method, 0},
+		{"(*ParseError).Error", Method, 0},
+		{"(*Ticker).Reset", Method, 15},
+		{"(*Ticker).Stop", Method, 0},
+		{"(*Time).GobDecode", Method, 0},
+		{"(*Time).UnmarshalBinary", Method, 2},
+		{"(*Time).UnmarshalJSON", Method, 0},
+		{"(*Time).UnmarshalText", Method, 2},
+		{"(*Timer).Reset", Method, 1},
+		{"(*Timer).Stop", Method, 0},
+		{"(Duration).Abs", Method, 19},
+		{"(Duration).Hours", Method, 0},
+		{"(Duration).Microseconds", Method, 13},
+		{"(Duration).Milliseconds", Method, 13},
+		{"(Duration).Minutes", Method, 0},
+		{"(Duration).Nanoseconds", Method, 0},
+		{"(Duration).Round", Method, 9},
+		{"(Duration).Seconds", Method, 0},
+		{"(Duration).String", Method, 0},
+		{"(Duration).Truncate", Method, 9},
+		{"(Month).String", Method, 0},
+		{"(Time).Add", Method, 0},
+		{"(Time).AddDate", Method, 0},
+		{"(Time).After", Method, 0},
+		{"(Time).AppendBinary", Method, 24},
+		{"(Time).AppendFormat", Method, 5},
+		{"(Time).AppendText", Method, 24},
+		{"(Time).Before", Method, 0},
+		{"(Time).Clock", Method, 0},
+		{"(Time).Compare", Method, 20},
+		{"(Time).Date", Method, 0},
+		{"(Time).Day", Method, 0},
+		{"(Time).Equal", Method, 0},
+		{"(Time).Format", Method, 0},
+		{"(Time).GoString", Method, 17},
+		{"(Time).GobEncode", Method, 0},
+		{"(Time).Hour", Method, 0},
+		{"(Time).ISOWeek", Method, 0},
+		{"(Time).In", Method, 0},
+		{"(Time).IsDST", Method, 17},
+		{"(Time).IsZero", Method, 0},
+		{"(Time).Local", Method, 0},
+		{"(Time).Location", Method, 0},
+		{"(Time).MarshalBinary", Method, 2},
+		{"(Time).MarshalJSON", Method, 0},
+		{"(Time).MarshalText", Method, 2},
+		{"(Time).Minute", Method, 0},
+		{"(Time).Month", Method, 0},
+		{"(Time).Nanosecond", Method, 0},
+		{"(Time).Round", Method, 1},
+		{"(Time).Second", Method, 0},
+		{"(Time).String", Method, 0},
+		{"(Time).Sub", Method, 0},
+		{"(Time).Truncate", Method, 1},
+		{"(Time).UTC", Method, 0},
+		{"(Time).Unix", Method, 0},
+		{"(Time).UnixMicro", Method, 17},
+		{"(Time).UnixMilli", Method, 17},
+		{"(Time).UnixNano", Method, 0},
+		{"(Time).Weekday", Method, 0},
+		{"(Time).Year", Method, 0},
+		{"(Time).YearDay", Method, 1},
+		{"(Time).Zone", Method, 0},
+		{"(Time).ZoneBounds", Method, 19},
+		{"(Weekday).String", Method, 0},
+		{"ANSIC", Const, 0},
+		{"After", Func, 0},
+		{"AfterFunc", Func, 0},
+		{"April", Const, 0},
+		{"August", Const, 0},
+		{"Date", Func, 0},
+		{"DateOnly", Const, 20},
+		{"DateTime", Const, 20},
+		{"December", Const, 0},
+		{"Duration", Type, 0},
+		{"February", Const, 0},
+		{"FixedZone", Func, 0},
+		{"Friday", Const, 0},
+		{"Hour", Const, 0},
+		{"January", Const, 0},
+		{"July", Const, 0},
+		{"June", Const, 0},
+		{"Kitchen", Const, 0},
+		{"Layout", Const, 17},
+		{"LoadLocation", Func, 0},
+		{"LoadLocationFromTZData", Func, 10},
+		{"Local", Var, 0},
+		{"Location", Type, 0},
+		{"March", Const, 0},
+		{"May", Const, 0},
+		{"Microsecond", Const, 0},
+		{"Millisecond", Const, 0},
+		{"Minute", Const, 0},
+		{"Monday", Const, 0},
+		{"Month", Type, 0},
+		{"Nanosecond", Const, 0},
+		{"NewTicker", Func, 0},
+		{"NewTimer", Func, 0},
+		{"November", Const, 0},
+		{"Now", Func, 0},
+		{"October", Const, 0},
+		{"Parse", Func, 0},
+		{"ParseDuration", Func, 0},
+		{"ParseError", Type, 0},
+		{"ParseError.Layout", Field, 0},
+		{"ParseError.LayoutElem", Field, 0},
+		{"ParseError.Message", Field, 0},
+		{"ParseError.Value", Field, 0},
+		{"ParseError.ValueElem", Field, 0},
+		{"ParseInLocation", Func, 1},
+		{"RFC1123", Const, 0},
+		{"RFC1123Z", Const, 0},
+		{"RFC3339", Const, 0},
+		{"RFC3339Nano", Const, 0},
+		{"RFC822", Const, 0},
+		{"RFC822Z", Const, 0},
+		{"RFC850", Const, 0},
+		{"RubyDate", Const, 0},
+		{"Saturday", Const, 0},
+		{"Second", Const, 0},
+		{"September", Const, 0},
+		{"Since", Func, 0},
+		{"Sleep", Func, 0},
+		{"Stamp", Const, 0},
+		{"StampMicro", Const, 0},
+		{"StampMilli", Const, 0},
+		{"StampNano", Const, 0},
+		{"Sunday", Const, 0},
+		{"Thursday", Const, 0},
+		{"Tick", Func, 0},
+		{"Ticker", Type, 0},
+		{"Ticker.C", Field, 0},
+		{"Time", Type, 0},
+		{"TimeOnly", Const, 20},
+		{"Timer", Type, 0},
+		{"Timer.C", Field, 0},
+		{"Tuesday", Const, 0},
+		{"UTC", Var, 0},
+		{"Unix", Func, 0},
+		{"UnixDate", Const, 0},
+		{"UnixMicro", Func, 17},
+		{"UnixMilli", Func, 17},
+		{"Until", Func, 8},
+		{"Wednesday", Const, 0},
+		{"Weekday", Type, 0},
+	},
+	"unicode": {
+		{"(SpecialCase).ToLower", Method, 0},
+		{"(SpecialCase).ToTitle", Method, 0},
+		{"(SpecialCase).ToUpper", Method, 0},
+		{"ASCII_Hex_Digit", Var, 0},
+		{"Adlam", Var, 7},
+		{"Ahom", Var, 5},
+		{"Anatolian_Hieroglyphs", Var, 5},
+		{"Arabic", Var, 0},
+		{"Armenian", Var, 0},
+		{"Avestan", Var, 0},
+		{"AzeriCase", Var, 0},
+		{"Balinese", Var, 0},
+		{"Bamum", Var, 0},
+		{"Bassa_Vah", Var, 4},
+		{"Batak", Var, 0},
+		{"Bengali", Var, 0},
+		{"Bhaiksuki", Var, 7},
+		{"Bidi_Control", Var, 0},
+		{"Bopomofo", Var, 0},
+		{"Brahmi", Var, 0},
+		{"Braille", Var, 0},
+		{"Buginese", Var, 0},
+		{"Buhid", Var, 0},
+		{"C", Var, 0},
+		{"Canadian_Aboriginal", Var, 0},
+		{"Carian", Var, 0},
+		{"CaseRange", Type, 0},
+		{"CaseRange.Delta", Field, 0},
+		{"CaseRange.Hi", Field, 0},
+		{"CaseRange.Lo", Field, 0},
+		{"CaseRanges", Var, 0},
+		{"Categories", Var, 0},
+		{"Caucasian_Albanian", Var, 4},
+		{"Cc", Var, 0},
+		{"Cf", Var, 0},
+		{"Chakma", Var, 1},
+		{"Cham", Var, 0},
+		{"Cherokee", Var, 0},
+		{"Chorasmian", Var, 16},
+		{"Co", Var, 0},
+		{"Common", Var, 0},
+		{"Coptic", Var, 0},
+		{"Cs", Var, 0},
+		{"Cuneiform", Var, 0},
+		{"Cypriot", Var, 0},
+		{"Cypro_Minoan", Var, 21},
+		{"Cyrillic", Var, 0},
+		{"Dash", Var, 0},
+		{"Deprecated", Var, 0},
+		{"Deseret", Var, 0},
+		{"Devanagari", Var, 0},
+		{"Diacritic", Var, 0},
+		{"Digit", Var, 0},
+		{"Dives_Akuru", Var, 16},
+		{"Dogra", Var, 13},
+		{"Duployan", Var, 4},
+		{"Egyptian_Hieroglyphs", Var, 0},
+		{"Elbasan", Var, 4},
+		{"Elymaic", Var, 14},
+		{"Ethiopic", Var, 0},
+		{"Extender", Var, 0},
+		{"FoldCategory", Var, 0},
+		{"FoldScript", Var, 0},
+		{"Georgian", Var, 0},
+		{"Glagolitic", Var, 0},
+		{"Gothic", Var, 0},
+		{"Grantha", Var, 4},
+		{"GraphicRanges", Var, 0},
+		{"Greek", Var, 0},
+		{"Gujarati", Var, 0},
+		{"Gunjala_Gondi", Var, 13},
+		{"Gurmukhi", Var, 0},
+		{"Han", Var, 0},
+		{"Hangul", Var, 0},
+		{"Hanifi_Rohingya", Var, 13},
+		{"Hanunoo", Var, 0},
+		{"Hatran", Var, 5},
+		{"Hebrew", Var, 0},
+		{"Hex_Digit", Var, 0},
+		{"Hiragana", Var, 0},
+		{"Hyphen", Var, 0},
+		{"IDS_Binary_Operator", Var, 0},
+		{"IDS_Trinary_Operator", Var, 0},
+		{"Ideographic", Var, 0},
+		{"Imperial_Aramaic", Var, 0},
+		{"In", Func, 2},
+		{"Inherited", Var, 0},
+		{"Inscriptional_Pahlavi", Var, 0},
+		{"Inscriptional_Parthian", Var, 0},
+		{"Is", Func, 0},
+		{"IsControl", Func, 0},
+		{"IsDigit", Func, 0},
+		{"IsGraphic", Func, 0},
+		{"IsLetter", Func, 0},
+		{"IsLower", Func, 0},
+		{"IsMark", Func, 0},
+		{"IsNumber", Func, 0},
+		{"IsOneOf", Func, 0},
+		{"IsPrint", Func, 0},
+		{"IsPunct", Func, 0},
+		{"IsSpace", Func, 0},
+		{"IsSymbol", Func, 0},
+		{"IsTitle", Func, 0},
+		{"IsUpper", Func, 0},
+		{"Javanese", Var, 0},
+		{"Join_Control", Var, 0},
+		{"Kaithi", Var, 0},
+		{"Kannada", Var, 0},
+		{"Katakana", Var, 0},
+		{"Kawi", Var, 21},
+		{"Kayah_Li", Var, 0},
+		{"Kharoshthi", Var, 0},
+		{"Khitan_Small_Script", Var, 16},
+		{"Khmer", Var, 0},
+		{"Khojki", Var, 4},
+		{"Khudawadi", Var, 4},
+		{"L", Var, 0},
+		{"Lao", Var, 0},
+		{"Latin", Var, 0},
+		{"Lepcha", Var, 0},
+		{"Letter", Var, 0},
+		{"Limbu", Var, 0},
+		{"Linear_A", Var, 4},
+		{"Linear_B", Var, 0},
+		{"Lisu", Var, 0},
+		{"Ll", Var, 0},
+		{"Lm", Var, 0},
+		{"Lo", Var, 0},
+		{"Logical_Order_Exception", Var, 0},
+		{"Lower", Var, 0},
+		{"LowerCase", Const, 0},
+		{"Lt", Var, 0},
+		{"Lu", Var, 0},
+		{"Lycian", Var, 0},
+		{"Lydian", Var, 0},
+		{"M", Var, 0},
+		{"Mahajani", Var, 4},
+		{"Makasar", Var, 13},
+		{"Malayalam", Var, 0},
+		{"Mandaic", Var, 0},
+		{"Manichaean", Var, 4},
+		{"Marchen", Var, 7},
+		{"Mark", Var, 0},
+		{"Masaram_Gondi", Var, 10},
+		{"MaxASCII", Const, 0},
+		{"MaxCase", Const, 0},
+		{"MaxLatin1", Const, 0},
+		{"MaxRune", Const, 0},
+		{"Mc", Var, 0},
+		{"Me", Var, 0},
+		{"Medefaidrin", Var, 13},
+		{"Meetei_Mayek", Var, 0},
+		{"Mende_Kikakui", Var, 4},
+		{"Meroitic_Cursive", Var, 1},
+		{"Meroitic_Hieroglyphs", Var, 1},
+		{"Miao", Var, 1},
+		{"Mn", Var, 0},
+		{"Modi", Var, 4},
+		{"Mongolian", Var, 0},
+		{"Mro", Var, 4},
+		{"Multani", Var, 5},
+		{"Myanmar", Var, 0},
+		{"N", Var, 0},
+		{"Nabataean", Var, 4},
+		{"Nag_Mundari", Var, 21},
+		{"Nandinagari", Var, 14},
+		{"Nd", Var, 0},
+		{"New_Tai_Lue", Var, 0},
+		{"Newa", Var, 7},
+		{"Nko", Var, 0},
+		{"Nl", Var, 0},
+		{"No", Var, 0},
+		{"Noncharacter_Code_Point", Var, 0},
+		{"Number", Var, 0},
+		{"Nushu", Var, 10},
+		{"Nyiakeng_Puachue_Hmong", Var, 14},
+		{"Ogham", Var, 0},
+		{"Ol_Chiki", Var, 0},
+		{"Old_Hungarian", Var, 5},
+		{"Old_Italic", Var, 0},
+		{"Old_North_Arabian", Var, 4},
+		{"Old_Permic", Var, 4},
+		{"Old_Persian", Var, 0},
+		{"Old_Sogdian", Var, 13},
+		{"Old_South_Arabian", Var, 0},
+		{"Old_Turkic", Var, 0},
+		{"Old_Uyghur", Var, 21},
+		{"Oriya", Var, 0},
+		{"Osage", Var, 7},
+		{"Osmanya", Var, 0},
+		{"Other", Var, 0},
+		{"Other_Alphabetic", Var, 0},
+		{"Other_Default_Ignorable_Code_Point", Var, 0},
+		{"Other_Grapheme_Extend", Var, 0},
+		{"Other_ID_Continue", Var, 0},
+		{"Other_ID_Start", Var, 0},
+		{"Other_Lowercase", Var, 0},
+		{"Other_Math", Var, 0},
+		{"Other_Uppercase", Var, 0},
+		{"P", Var, 0},
+		{"Pahawh_Hmong", Var, 4},
+		{"Palmyrene", Var, 4},
+		{"Pattern_Syntax", Var, 0},
+		{"Pattern_White_Space", Var, 0},
+		{"Pau_Cin_Hau", Var, 4},
+		{"Pc", Var, 0},
+		{"Pd", Var, 0},
+		{"Pe", Var, 0},
+		{"Pf", Var, 0},
+		{"Phags_Pa", Var, 0},
+		{"Phoenician", Var, 0},
+		{"Pi", Var, 0},
+		{"Po", Var, 0},
+		{"Prepended_Concatenation_Mark", Var, 7},
+		{"PrintRanges", Var, 0},
+		{"Properties", Var, 0},
+		{"Ps", Var, 0},
+		{"Psalter_Pahlavi", Var, 4},
+		{"Punct", Var, 0},
+		{"Quotation_Mark", Var, 0},
+		{"Radical", Var, 0},
+		{"Range16", Type, 0},
+		{"Range16.Hi", Field, 0},
+		{"Range16.Lo", Field, 0},
+		{"Range16.Stride", Field, 0},
+		{"Range32", Type, 0},
+		{"Range32.Hi", Field, 0},
+		{"Range32.Lo", Field, 0},
+		{"Range32.Stride", Field, 0},
+		{"RangeTable", Type, 0},
+		{"RangeTable.LatinOffset", Field, 1},
+		{"RangeTable.R16", Field, 0},
+		{"RangeTable.R32", Field, 0},
+		{"Regional_Indicator", Var, 10},
+		{"Rejang", Var, 0},
+		{"ReplacementChar", Const, 0},
+		{"Runic", Var, 0},
+		{"S", Var, 0},
+		{"STerm", Var, 0},
+		{"Samaritan", Var, 0},
+		{"Saurashtra", Var, 0},
+		{"Sc", Var, 0},
+		{"Scripts", Var, 0},
+		{"Sentence_Terminal", Var, 7},
+		{"Sharada", Var, 1},
+		{"Shavian", Var, 0},
+		{"Siddham", Var, 4},
+		{"SignWriting", Var, 5},
+		{"SimpleFold", Func, 0},
+		{"Sinhala", Var, 0},
+		{"Sk", Var, 0},
+		{"Sm", Var, 0},
+		{"So", Var, 0},
+		{"Soft_Dotted", Var, 0},
+		{"Sogdian", Var, 13},
+		{"Sora_Sompeng", Var, 1},
+		{"Soyombo", Var, 10},
+		{"Space", Var, 0},
+		{"SpecialCase", Type, 0},
+		{"Sundanese", Var, 0},
+		{"Syloti_Nagri", Var, 0},
+		{"Symbol", Var, 0},
+		{"Syriac", Var, 0},
+		{"Tagalog", Var, 0},
+		{"Tagbanwa", Var, 0},
+		{"Tai_Le", Var, 0},
+		{"Tai_Tham", Var, 0},
+		{"Tai_Viet", Var, 0},
+		{"Takri", Var, 1},
+		{"Tamil", Var, 0},
+		{"Tangsa", Var, 21},
+		{"Tangut", Var, 7},
+		{"Telugu", Var, 0},
+		{"Terminal_Punctuation", Var, 0},
+		{"Thaana", Var, 0},
+		{"Thai", Var, 0},
+		{"Tibetan", Var, 0},
+		{"Tifinagh", Var, 0},
+		{"Tirhuta", Var, 4},
+		{"Title", Var, 0},
+		{"TitleCase", Const, 0},
+		{"To", Func, 0},
+		{"ToLower", Func, 0},
+		{"ToTitle", Func, 0},
+		{"ToUpper", Func, 0},
+		{"Toto", Var, 21},
+		{"TurkishCase", Var, 0},
+		{"Ugaritic", Var, 0},
+		{"Unified_Ideograph", Var, 0},
+		{"Upper", Var, 0},
+		{"UpperCase", Const, 0},
+		{"UpperLower", Const, 0},
+		{"Vai", Var, 0},
+		{"Variation_Selector", Var, 0},
+		{"Version", Const, 0},
+		{"Vithkuqi", Var, 21},
+		{"Wancho", Var, 14},
+		{"Warang_Citi", Var, 4},
+		{"White_Space", Var, 0},
+		{"Yezidi", Var, 16},
+		{"Yi", Var, 0},
+		{"Z", Var, 0},
+		{"Zanabazar_Square", Var, 10},
+		{"Zl", Var, 0},
+		{"Zp", Var, 0},
+		{"Zs", Var, 0},
+	},
+	"unicode/utf16": {
+		{"AppendRune", Func, 20},
+		{"Decode", Func, 0},
+		{"DecodeRune", Func, 0},
+		{"Encode", Func, 0},
+		{"EncodeRune", Func, 0},
+		{"IsSurrogate", Func, 0},
+		{"RuneLen", Func, 23},
+	},
+	"unicode/utf8": {
+		{"AppendRune", Func, 18},
+		{"DecodeLastRune", Func, 0},
+		{"DecodeLastRuneInString", Func, 0},
+		{"DecodeRune", Func, 0},
+		{"DecodeRuneInString", Func, 0},
+		{"EncodeRune", Func, 0},
+		{"FullRune", Func, 0},
+		{"FullRuneInString", Func, 0},
+		{"MaxRune", Const, 0},
+		{"RuneCount", Func, 0},
+		{"RuneCountInString", Func, 0},
+		{"RuneError", Const, 0},
+		{"RuneLen", Func, 0},
+		{"RuneSelf", Const, 0},
+		{"RuneStart", Func, 0},
+		{"UTFMax", Const, 0},
+		{"Valid", Func, 0},
+		{"ValidRune", Func, 1},
+		{"ValidString", Func, 0},
+	},
+	"unique": {
+		{"(Handle).Value", Method, 23},
+		{"Handle", Type, 23},
+		{"Make", Func, 23},
+	},
+	"unsafe": {
+		{"Add", Func, 0},
+		{"Alignof", Func, 0},
+		{"Offsetof", Func, 0},
+		{"Pointer", Type, 0},
+		{"Sizeof", Func, 0},
+		{"Slice", Func, 0},
+		{"SliceData", Func, 0},
+		{"String", Func, 0},
+		{"StringData", Func, 0},
+	},
+	"weak": {
+		{"(Pointer).Value", Method, 24},
+		{"Make", Func, 24},
+		{"Pointer", Type, 24},
+	},
+}
diff --git a/vendor/golang.org/x/tools/internal/stdlib/stdlib.go b/vendor/golang.org/x/tools/internal/stdlib/stdlib.go
new file mode 100644
index 000000000..3d96d3bf6
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/stdlib/stdlib.go
@@ -0,0 +1,97 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:generate go run generate.go
+
+// Package stdlib provides a table of all exported symbols in the
+// standard library, along with the version at which they first
+// appeared. It also provides the import graph of std packages.
+package stdlib
+
+import (
+	"fmt"
+	"strings"
+)
+
+type Symbol struct {
+	Name    string
+	Kind    Kind
+	Version Version // Go version that first included the symbol
+}
+
+// A Kind indicates the kind of a symbol:
+// function, variable, constant, type, and so on.
+type Kind int8
+
+const (
+	Invalid Kind = iota // Example name:
+	Type                // "Buffer"
+	Func                // "Println"
+	Var                 // "EOF"
+	Const               // "Pi"
+	Field               // "Point.X"
+	Method              // "(*Buffer).Grow"
+)
+
+func (kind Kind) String() string {
+	return [...]string{
+		Invalid: "invalid",
+		Type:    "type",
+		Func:    "func",
+		Var:     "var",
+		Const:   "const",
+		Field:   "field",
+		Method:  "method",
+	}[kind]
+}
+
+// A Version represents a version of Go of the form "go1.%d".
+type Version int8
+
+// String returns a version string of the form "go1.23", without allocating.
+func (v Version) String() string { return versions[v] }
+
+var versions [30]string // (increase constant as needed)
+
+func init() {
+	for i := range versions {
+		versions[i] = fmt.Sprintf("go1.%d", i)
+	}
+}
+
+// HasPackage reports whether the specified package path is part of
+// the standard library's public API.
+func HasPackage(path string) bool {
+	_, ok := PackageSymbols[path]
+	return ok
+}
+
+// SplitField splits the field symbol name into type and field
+// components. It must be called only on Field symbols.
+//
+// Example: "File.Package" -> ("File", "Package")
+func (sym *Symbol) SplitField() (typename, name string) {
+	if sym.Kind != Field {
+		panic("not a field")
+	}
+	typename, name, _ = strings.Cut(sym.Name, ".")
+	return
+}
+
+// SplitMethod splits the method symbol name into pointer, receiver,
+// and method components. It must be called only on Method symbols.
+//
+// Example: "(*Buffer).Grow" -> (true, "Buffer", "Grow")
+func (sym *Symbol) SplitMethod() (ptr bool, recv, name string) {
+	if sym.Kind != Method {
+		panic("not a method")
+	}
+	recv, name, _ = strings.Cut(sym.Name, ".")
+	recv = recv[len("(") : len(recv)-len(")")]
+	ptr = recv[0] == '*'
+	if ptr {
+		recv = recv[len("*"):]
+	}
+	return
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/common.go b/vendor/golang.org/x/tools/internal/typeparams/common.go
new file mode 100644
index 000000000..cdae2b8e8
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/common.go
@@ -0,0 +1,68 @@
+// Copyright 2021 The Go 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 typeparams contains common utilities for writing tools that
+// interact with generic Go code, as introduced with Go 1.18. It
+// supplements the standard library APIs. Notably, the StructuralTerms
+// API computes a minimal representation of the structural
+// restrictions on a type parameter.
+//
+// An external version of these APIs is available in the
+// golang.org/x/exp/typeparams module.
+package typeparams
+
+import (
+	"go/ast"
+	"go/token"
+	"go/types"
+)
+
+// UnpackIndexExpr extracts data from AST nodes that represent index
+// expressions.
+//
+// For an ast.IndexExpr, the resulting indices slice will contain exactly one
+// index expression. For an ast.IndexListExpr (go1.18+), it may have a variable
+// number of index expressions.
+//
+// For nodes that don't represent index expressions, the first return value of
+// UnpackIndexExpr will be nil.
+func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) {
+	switch e := n.(type) {
+	case *ast.IndexExpr:
+		return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack
+	case *ast.IndexListExpr:
+		return e.X, e.Lbrack, e.Indices, e.Rbrack
+	}
+	return nil, token.NoPos, nil, token.NoPos
+}
+
+// PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on
+// the cardinality of indices. Calling PackIndexExpr with len(indices) == 0
+// will panic.
+func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr {
+	switch len(indices) {
+	case 0:
+		panic("empty indices")
+	case 1:
+		return &ast.IndexExpr{
+			X:      x,
+			Lbrack: lbrack,
+			Index:  indices[0],
+			Rbrack: rbrack,
+		}
+	default:
+		return &ast.IndexListExpr{
+			X:       x,
+			Lbrack:  lbrack,
+			Indices: indices,
+			Rbrack:  rbrack,
+		}
+	}
+}
+
+// IsTypeParam reports whether t is a type parameter (or an alias of one).
+func IsTypeParam(t types.Type) bool {
+	_, ok := types.Unalias(t).(*types.TypeParam)
+	return ok
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/coretype.go b/vendor/golang.org/x/tools/internal/typeparams/coretype.go
new file mode 100644
index 000000000..27a2b1792
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/coretype.go
@@ -0,0 +1,155 @@
+// Copyright 2022 The Go 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 typeparams
+
+import (
+	"fmt"
+	"go/types"
+)
+
+// CoreType returns the core type of T or nil if T does not have a core type.
+//
+// See https://go.dev/ref/spec#Core_types for the definition of a core type.
+func CoreType(T types.Type) types.Type {
+	U := T.Underlying()
+	if _, ok := U.(*types.Interface); !ok {
+		return U // for non-interface types,
+	}
+
+	terms, err := NormalTerms(U)
+	if len(terms) == 0 || err != nil {
+		// len(terms) -> empty type set of interface.
+		// err != nil => U is invalid, exceeds complexity bounds, or has an empty type set.
+		return nil // no core type.
+	}
+
+	U = terms[0].Type().Underlying()
+	var identical int // i in [0,identical) => Identical(U, terms[i].Type().Underlying())
+	for identical = 1; identical < len(terms); identical++ {
+		if !types.Identical(U, terms[identical].Type().Underlying()) {
+			break
+		}
+	}
+
+	if identical == len(terms) {
+		// https://go.dev/ref/spec#Core_types
+		// "There is a single type U which is the underlying type of all types in the type set of T"
+		return U
+	}
+	ch, ok := U.(*types.Chan)
+	if !ok {
+		return nil // no core type as identical < len(terms) and U is not a channel.
+	}
+	// https://go.dev/ref/spec#Core_types
+	// "the type chan E if T contains only bidirectional channels, or the type chan<- E or
+	// <-chan E depending on the direction of the directional channels present."
+	for chans := identical; chans < len(terms); chans++ {
+		curr, ok := terms[chans].Type().Underlying().(*types.Chan)
+		if !ok {
+			return nil
+		}
+		if !types.Identical(ch.Elem(), curr.Elem()) {
+			return nil // channel elements are not identical.
+		}
+		if ch.Dir() == types.SendRecv {
+			// ch is bidirectional. We can safely always use curr's direction.
+			ch = curr
+		} else if curr.Dir() != types.SendRecv && ch.Dir() != curr.Dir() {
+			// ch and curr are not bidirectional and not the same direction.
+			return nil
+		}
+	}
+	return ch
+}
+
+// NormalTerms returns a slice of terms representing the normalized structural
+// type restrictions of a type, if any.
+//
+// For all types other than *types.TypeParam, *types.Interface, and
+// *types.Union, this is just a single term with Tilde() == false and
+// Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see
+// below.
+//
+// Structural type restrictions of a type parameter are created via
+// non-interface types embedded in its constraint interface (directly, or via a
+// chain of interface embeddings). For example, in the declaration type
+// T[P interface{~int; m()}] int the structural restriction of the type
+// parameter P is ~int.
+//
+// With interface embedding and unions, the specification of structural type
+// restrictions may be arbitrarily complex. For example, consider the
+// following:
+//
+//	type A interface{ ~string|~[]byte }
+//
+//	type B interface{ int|string }
+//
+//	type C interface { ~string|~int }
+//
+//	type T[P interface{ A|B; C }] int
+//
+// In this example, the structural type restriction of P is ~string|int: A|B
+// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int,
+// which when intersected with C (~string|~int) yields ~string|int.
+//
+// NormalTerms computes these expansions and reductions, producing a
+// "normalized" form of the embeddings. A structural restriction is normalized
+// if it is a single union containing no interface terms, and is minimal in the
+// sense that removing any term changes the set of types satisfying the
+// constraint. It is left as a proof for the reader that, modulo sorting, there
+// is exactly one such normalized form.
+//
+// Because the minimal representation always takes this form, NormalTerms
+// returns a slice of tilde terms corresponding to the terms of the union in
+// the normalized structural restriction. An error is returned if the type is
+// invalid, exceeds complexity bounds, or has an empty type set. In the latter
+// case, NormalTerms returns ErrEmptyTypeSet.
+//
+// NormalTerms makes no guarantees about the order of terms, except that it
+// is deterministic.
+func NormalTerms(T types.Type) ([]*types.Term, error) {
+	// typeSetOf(T) == typeSetOf(Unalias(T))
+	typ := types.Unalias(T)
+	if named, ok := typ.(*types.Named); ok {
+		typ = named.Underlying()
+	}
+	switch typ := typ.(type) {
+	case *types.TypeParam:
+		return StructuralTerms(typ)
+	case *types.Union:
+		return UnionTermSet(typ)
+	case *types.Interface:
+		return InterfaceTermSet(typ)
+	default:
+		return []*types.Term{types.NewTerm(false, T)}, nil
+	}
+}
+
+// Deref returns the type of the variable pointed to by t,
+// if t's core type is a pointer; otherwise it returns t.
+//
+// Do not assume that Deref(T)==T implies T is not a pointer:
+// consider "type T *T", for example.
+//
+// TODO(adonovan): ideally this would live in typesinternal, but that
+// creates an import cycle. Move there when we melt this package down.
+func Deref(t types.Type) types.Type {
+	if ptr, ok := CoreType(t).(*types.Pointer); ok {
+		return ptr.Elem()
+	}
+	return t
+}
+
+// MustDeref returns the type of the variable pointed to by t.
+// It panics if t's core type is not a pointer.
+//
+// TODO(adonovan): ideally this would live in typesinternal, but that
+// creates an import cycle. Move there when we melt this package down.
+func MustDeref(t types.Type) types.Type {
+	if ptr, ok := CoreType(t).(*types.Pointer); ok {
+		return ptr.Elem()
+	}
+	panic(fmt.Sprintf("%v is not a pointer", t))
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/free.go b/vendor/golang.org/x/tools/internal/typeparams/free.go
new file mode 100644
index 000000000..709d2fc14
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/free.go
@@ -0,0 +1,131 @@
+// Copyright 2024 The Go 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 typeparams
+
+import (
+	"go/types"
+
+	"golang.org/x/tools/internal/aliases"
+)
+
+// Free is a memoization of the set of free type parameters within a
+// type. It makes a sequence of calls to [Free.Has] for overlapping
+// types more efficient. The zero value is ready for use.
+//
+// NOTE: Adapted from go/types/infer.go. If it is later exported, factor.
+type Free struct {
+	seen map[types.Type]bool
+}
+
+// Has reports whether the specified type has a free type parameter.
+func (w *Free) Has(typ types.Type) (res bool) {
+	// detect cycles
+	if x, ok := w.seen[typ]; ok {
+		return x
+	}
+	if w.seen == nil {
+		w.seen = make(map[types.Type]bool)
+	}
+	w.seen[typ] = false
+	defer func() {
+		w.seen[typ] = res
+	}()
+
+	switch t := typ.(type) {
+	case nil, *types.Basic: // TODO(gri) should nil be handled here?
+		break
+
+	case *types.Alias:
+		if aliases.TypeParams(t).Len() > aliases.TypeArgs(t).Len() {
+			return true // This is an uninstantiated Alias.
+		}
+		// The expansion of an alias can have free type parameters,
+		// whether or not the alias itself has type parameters:
+		//
+		//   func _[K comparable]() {
+		//     type Set      = map[K]bool // free(Set)      = {K}
+		//     type MapTo[V] = map[K]V    // free(Map[foo]) = {V}
+		//   }
+		//
+		// So, we must Unalias.
+		return w.Has(types.Unalias(t))
+
+	case *types.Array:
+		return w.Has(t.Elem())
+
+	case *types.Slice:
+		return w.Has(t.Elem())
+
+	case *types.Struct:
+		for i, n := 0, t.NumFields(); i < n; i++ {
+			if w.Has(t.Field(i).Type()) {
+				return true
+			}
+		}
+
+	case *types.Pointer:
+		return w.Has(t.Elem())
+
+	case *types.Tuple:
+		n := t.Len()
+		for i := range n {
+			if w.Has(t.At(i).Type()) {
+				return true
+			}
+		}
+
+	case *types.Signature:
+		// t.tparams may not be nil if we are looking at a signature
+		// of a generic function type (or an interface method) that is
+		// part of the type we're testing. We don't care about these type
+		// parameters.
+		// Similarly, the receiver of a method may declare (rather than
+		// use) type parameters, we don't care about those either.
+		// Thus, we only need to look at the input and result parameters.
+		return w.Has(t.Params()) || w.Has(t.Results())
+
+	case *types.Interface:
+		for i, n := 0, t.NumMethods(); i < n; i++ {
+			if w.Has(t.Method(i).Type()) {
+				return true
+			}
+		}
+		terms, err := InterfaceTermSet(t)
+		if err != nil {
+			return false // ill typed
+		}
+		for _, term := range terms {
+			if w.Has(term.Type()) {
+				return true
+			}
+		}
+
+	case *types.Map:
+		return w.Has(t.Key()) || w.Has(t.Elem())
+
+	case *types.Chan:
+		return w.Has(t.Elem())
+
+	case *types.Named:
+		args := t.TypeArgs()
+		if params := t.TypeParams(); params.Len() > args.Len() {
+			return true // this is an uninstantiated named type.
+		}
+		for i, n := 0, args.Len(); i < n; i++ {
+			if w.Has(args.At(i)) {
+				return true
+			}
+		}
+		return w.Has(t.Underlying()) // recurse for types local to parameterized functions
+
+	case *types.TypeParam:
+		return true
+
+	default:
+		panic(t) // unreachable
+	}
+
+	return false
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/normalize.go b/vendor/golang.org/x/tools/internal/typeparams/normalize.go
new file mode 100644
index 000000000..f49802b8e
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/normalize.go
@@ -0,0 +1,218 @@
+// Copyright 2021 The Go 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 typeparams
+
+import (
+	"errors"
+	"fmt"
+	"go/types"
+	"os"
+	"strings"
+)
+
+//go:generate go run copytermlist.go
+
+const debug = false
+
+var ErrEmptyTypeSet = errors.New("empty type set")
+
+// StructuralTerms returns a slice of terms representing the normalized
+// structural type restrictions of a type parameter, if any.
+//
+// Structural type restrictions of a type parameter are created via
+// non-interface types embedded in its constraint interface (directly, or via a
+// chain of interface embeddings). For example, in the declaration
+//
+//	type T[P interface{~int; m()}] int
+//
+// the structural restriction of the type parameter P is ~int.
+//
+// With interface embedding and unions, the specification of structural type
+// restrictions may be arbitrarily complex. For example, consider the
+// following:
+//
+//	type A interface{ ~string|~[]byte }
+//
+//	type B interface{ int|string }
+//
+//	type C interface { ~string|~int }
+//
+//	type T[P interface{ A|B; C }] int
+//
+// In this example, the structural type restriction of P is ~string|int: A|B
+// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int,
+// which when intersected with C (~string|~int) yields ~string|int.
+//
+// StructuralTerms computes these expansions and reductions, producing a
+// "normalized" form of the embeddings. A structural restriction is normalized
+// if it is a single union containing no interface terms, and is minimal in the
+// sense that removing any term changes the set of types satisfying the
+// constraint. It is left as a proof for the reader that, modulo sorting, there
+// is exactly one such normalized form.
+//
+// Because the minimal representation always takes this form, StructuralTerms
+// returns a slice of tilde terms corresponding to the terms of the union in
+// the normalized structural restriction. An error is returned if the
+// constraint interface is invalid, exceeds complexity bounds, or has an empty
+// type set. In the latter case, StructuralTerms returns ErrEmptyTypeSet.
+//
+// StructuralTerms makes no guarantees about the order of terms, except that it
+// is deterministic.
+func StructuralTerms(tparam *types.TypeParam) ([]*types.Term, error) {
+	constraint := tparam.Constraint()
+	if constraint == nil {
+		return nil, fmt.Errorf("%s has nil constraint", tparam)
+	}
+	iface, _ := constraint.Underlying().(*types.Interface)
+	if iface == nil {
+		return nil, fmt.Errorf("constraint is %T, not *types.Interface", constraint.Underlying())
+	}
+	return InterfaceTermSet(iface)
+}
+
+// InterfaceTermSet computes the normalized terms for a constraint interface,
+// returning an error if the term set cannot be computed or is empty. In the
+// latter case, the error will be ErrEmptyTypeSet.
+//
+// See the documentation of StructuralTerms for more information on
+// normalization.
+func InterfaceTermSet(iface *types.Interface) ([]*types.Term, error) {
+	return computeTermSet(iface)
+}
+
+// UnionTermSet computes the normalized terms for a union, returning an error
+// if the term set cannot be computed or is empty. In the latter case, the
+// error will be ErrEmptyTypeSet.
+//
+// See the documentation of StructuralTerms for more information on
+// normalization.
+func UnionTermSet(union *types.Union) ([]*types.Term, error) {
+	return computeTermSet(union)
+}
+
+func computeTermSet(typ types.Type) ([]*types.Term, error) {
+	tset, err := computeTermSetInternal(typ, make(map[types.Type]*termSet), 0)
+	if err != nil {
+		return nil, err
+	}
+	if tset.terms.isEmpty() {
+		return nil, ErrEmptyTypeSet
+	}
+	if tset.terms.isAll() {
+		return nil, nil
+	}
+	var terms []*types.Term
+	for _, term := range tset.terms {
+		terms = append(terms, types.NewTerm(term.tilde, term.typ))
+	}
+	return terms, nil
+}
+
+// A termSet holds the normalized set of terms for a given type.
+//
+// The name termSet is intentionally distinct from 'type set': a type set is
+// all types that implement a type (and includes method restrictions), whereas
+// a term set just represents the structural restrictions on a type.
+type termSet struct {
+	complete bool
+	terms    termlist
+}
+
+func indentf(depth int, format string, args ...any) {
+	fmt.Fprintf(os.Stderr, strings.Repeat(".", depth)+format+"\n", args...)
+}
+
+func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth int) (res *termSet, err error) {
+	if t == nil {
+		panic("nil type")
+	}
+
+	if debug {
+		indentf(depth, "%s", t.String())
+		defer func() {
+			if err != nil {
+				indentf(depth, "=> %s", err)
+			} else {
+				indentf(depth, "=> %s", res.terms.String())
+			}
+		}()
+	}
+
+	const maxTermCount = 100
+	if tset, ok := seen[t]; ok {
+		if !tset.complete {
+			return nil, fmt.Errorf("cycle detected in the declaration of %s", t)
+		}
+		return tset, nil
+	}
+
+	// Mark the current type as seen to avoid infinite recursion.
+	tset := new(termSet)
+	defer func() {
+		tset.complete = true
+	}()
+	seen[t] = tset
+
+	switch u := t.Underlying().(type) {
+	case *types.Interface:
+		// The term set of an interface is the intersection of the term sets of its
+		// embedded types.
+		tset.terms = allTermlist
+		for i := 0; i < u.NumEmbeddeds(); i++ {
+			embedded := u.EmbeddedType(i)
+			if _, ok := embedded.Underlying().(*types.TypeParam); ok {
+				return nil, fmt.Errorf("invalid embedded type %T", embedded)
+			}
+			tset2, err := computeTermSetInternal(embedded, seen, depth+1)
+			if err != nil {
+				return nil, err
+			}
+			tset.terms = tset.terms.intersect(tset2.terms)
+		}
+	case *types.Union:
+		// The term set of a union is the union of term sets of its terms.
+		tset.terms = nil
+		for i := 0; i < u.Len(); i++ {
+			t := u.Term(i)
+			var terms termlist
+			switch t.Type().Underlying().(type) {
+			case *types.Interface:
+				tset2, err := computeTermSetInternal(t.Type(), seen, depth+1)
+				if err != nil {
+					return nil, err
+				}
+				terms = tset2.terms
+			case *types.TypeParam, *types.Union:
+				// A stand-alone type parameter or union is not permitted as union
+				// term.
+				return nil, fmt.Errorf("invalid union term %T", t)
+			default:
+				if t.Type() == types.Typ[types.Invalid] {
+					continue
+				}
+				terms = termlist{{t.Tilde(), t.Type()}}
+			}
+			tset.terms = tset.terms.union(terms)
+			if len(tset.terms) > maxTermCount {
+				return nil, fmt.Errorf("exceeded max term count %d", maxTermCount)
+			}
+		}
+	case *types.TypeParam:
+		panic("unreachable")
+	default:
+		// For all other types, the term set is just a single non-tilde term
+		// holding the type itself.
+		if u != types.Typ[types.Invalid] {
+			tset.terms = termlist{{false, t}}
+		}
+	}
+	return tset, nil
+}
+
+// under is a facade for the go/types internal function of the same name. It is
+// used by typeterm.go.
+func under(t types.Type) types.Type {
+	return t.Underlying()
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/termlist.go b/vendor/golang.org/x/tools/internal/typeparams/termlist.go
new file mode 100644
index 000000000..9bc29143f
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/termlist.go
@@ -0,0 +1,169 @@
+// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
+// Source: ../../cmd/compile/internal/types2/termlist.go
+
+// Copyright 2021 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Code generated by copytermlist.go DO NOT EDIT.
+
+package typeparams
+
+import (
+	"go/types"
+	"strings"
+)
+
+// A termlist represents the type set represented by the union
+// t1 ∪ y2 ∪ ... tn of the type sets of the terms t1 to tn.
+// A termlist is in normal form if all terms are disjoint.
+// termlist operations don't require the operands to be in
+// normal form.
+type termlist []*term
+
+// allTermlist represents the set of all types.
+// It is in normal form.
+var allTermlist = termlist{new(term)}
+
+// termSep is the separator used between individual terms.
+const termSep = " | "
+
+// String prints the termlist exactly (without normalization).
+func (xl termlist) String() string {
+	if len(xl) == 0 {
+		return "∅"
+	}
+	var buf strings.Builder
+	for i, x := range xl {
+		if i > 0 {
+			buf.WriteString(termSep)
+		}
+		buf.WriteString(x.String())
+	}
+	return buf.String()
+}
+
+// isEmpty reports whether the termlist xl represents the empty set of types.
+func (xl termlist) isEmpty() bool {
+	// If there's a non-nil term, the entire list is not empty.
+	// If the termlist is in normal form, this requires at most
+	// one iteration.
+	for _, x := range xl {
+		if x != nil {
+			return false
+		}
+	}
+	return true
+}
+
+// isAll reports whether the termlist xl represents the set of all types.
+func (xl termlist) isAll() bool {
+	// If there's a 𝓤 term, the entire list is 𝓤.
+	// If the termlist is in normal form, this requires at most
+	// one iteration.
+	for _, x := range xl {
+		if x != nil && x.typ == nil {
+			return true
+		}
+	}
+	return false
+}
+
+// norm returns the normal form of xl.
+func (xl termlist) norm() termlist {
+	// Quadratic algorithm, but good enough for now.
+	// TODO(gri) fix asymptotic performance
+	used := make([]bool, len(xl))
+	var rl termlist
+	for i, xi := range xl {
+		if xi == nil || used[i] {
+			continue
+		}
+		for j := i + 1; j < len(xl); j++ {
+			xj := xl[j]
+			if xj == nil || used[j] {
+				continue
+			}
+			if u1, u2 := xi.union(xj); u2 == nil {
+				// If we encounter a 𝓤 term, the entire list is 𝓤.
+				// Exit early.
+				// (Note that this is not just an optimization;
+				// if we continue, we may end up with a 𝓤 term
+				// and other terms and the result would not be
+				// in normal form.)
+				if u1.typ == nil {
+					return allTermlist
+				}
+				xi = u1
+				used[j] = true // xj is now unioned into xi - ignore it in future iterations
+			}
+		}
+		rl = append(rl, xi)
+	}
+	return rl
+}
+
+// union returns the union xl ∪ yl.
+func (xl termlist) union(yl termlist) termlist {
+	return append(xl, yl...).norm()
+}
+
+// intersect returns the intersection xl ∩ yl.
+func (xl termlist) intersect(yl termlist) termlist {
+	if xl.isEmpty() || yl.isEmpty() {
+		return nil
+	}
+
+	// Quadratic algorithm, but good enough for now.
+	// TODO(gri) fix asymptotic performance
+	var rl termlist
+	for _, x := range xl {
+		for _, y := range yl {
+			if r := x.intersect(y); r != nil {
+				rl = append(rl, r)
+			}
+		}
+	}
+	return rl.norm()
+}
+
+// equal reports whether xl and yl represent the same type set.
+func (xl termlist) equal(yl termlist) bool {
+	// TODO(gri) this should be more efficient
+	return xl.subsetOf(yl) && yl.subsetOf(xl)
+}
+
+// includes reports whether t ∈ xl.
+func (xl termlist) includes(t types.Type) bool {
+	for _, x := range xl {
+		if x.includes(t) {
+			return true
+		}
+	}
+	return false
+}
+
+// supersetOf reports whether y ⊆ xl.
+func (xl termlist) supersetOf(y *term) bool {
+	for _, x := range xl {
+		if y.subsetOf(x) {
+			return true
+		}
+	}
+	return false
+}
+
+// subsetOf reports whether xl ⊆ yl.
+func (xl termlist) subsetOf(yl termlist) bool {
+	if yl.isEmpty() {
+		return xl.isEmpty()
+	}
+
+	// each term x of xl must be a subset of yl
+	for _, x := range xl {
+		if !yl.supersetOf(x) {
+			return false // x is not a subset yl
+		}
+	}
+	return true
+}
diff --git a/vendor/golang.org/x/tools/internal/typeparams/typeterm.go b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go
new file mode 100644
index 000000000..fa758cdc9
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go
@@ -0,0 +1,172 @@
+// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
+// Source: ../../cmd/compile/internal/types2/typeterm.go
+
+// Copyright 2021 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Code generated by copytermlist.go DO NOT EDIT.
+
+package typeparams
+
+import "go/types"
+
+// A term describes elementary type sets:
+//
+//	 ∅:  (*term)(nil)     == ∅                      // set of no types (empty set)
+//	 𝓤:  &term{}          == 𝓤                      // set of all types (𝓤niverse)
+//	 T:  &term{false, T}  == {T}                    // set of type T
+//	~t:  &term{true, t}   == {t' | under(t') == t}  // set of types with underlying type t
+type term struct {
+	tilde bool // valid if typ != nil
+	typ   types.Type
+}
+
+func (x *term) String() string {
+	switch {
+	case x == nil:
+		return "∅"
+	case x.typ == nil:
+		return "𝓤"
+	case x.tilde:
+		return "~" + x.typ.String()
+	default:
+		return x.typ.String()
+	}
+}
+
+// equal reports whether x and y represent the same type set.
+func (x *term) equal(y *term) bool {
+	// easy cases
+	switch {
+	case x == nil || y == nil:
+		return x == y
+	case x.typ == nil || y.typ == nil:
+		return x.typ == y.typ
+	}
+	// ∅ ⊂ x, y ⊂ 𝓤
+
+	return x.tilde == y.tilde && types.Identical(x.typ, y.typ)
+}
+
+// union returns the union x ∪ y: zero, one, or two non-nil terms.
+func (x *term) union(y *term) (_, _ *term) {
+	// easy cases
+	switch {
+	case x == nil && y == nil:
+		return nil, nil // ∅ ∪ ∅ == ∅
+	case x == nil:
+		return y, nil // ∅ ∪ y == y
+	case y == nil:
+		return x, nil // x ∪ ∅ == x
+	case x.typ == nil:
+		return x, nil // 𝓤 ∪ y == 𝓤
+	case y.typ == nil:
+		return y, nil // x ∪ 𝓤 == 𝓤
+	}
+	// ∅ ⊂ x, y ⊂ 𝓤
+
+	if x.disjoint(y) {
+		return x, y // x ∪ y == (x, y) if x ∩ y == ∅
+	}
+	// x.typ == y.typ
+
+	// ~t ∪ ~t == ~t
+	// ~t ∪  T == ~t
+	//  T ∪ ~t == ~t
+	//  T ∪  T ==  T
+	if x.tilde || !y.tilde {
+		return x, nil
+	}
+	return y, nil
+}
+
+// intersect returns the intersection x ∩ y.
+func (x *term) intersect(y *term) *term {
+	// easy cases
+	switch {
+	case x == nil || y == nil:
+		return nil // ∅ ∩ y == ∅ and ∩ ∅ == ∅
+	case x.typ == nil:
+		return y // 𝓤 ∩ y == y
+	case y.typ == nil:
+		return x // x ∩ 𝓤 == x
+	}
+	// ∅ ⊂ x, y ⊂ 𝓤
+
+	if x.disjoint(y) {
+		return nil // x ∩ y == ∅ if x ∩ y == ∅
+	}
+	// x.typ == y.typ
+
+	// ~t ∩ ~t == ~t
+	// ~t ∩  T ==  T
+	//  T ∩ ~t ==  T
+	//  T ∩  T ==  T
+	if !x.tilde || y.tilde {
+		return x
+	}
+	return y
+}
+
+// includes reports whether t ∈ x.
+func (x *term) includes(t types.Type) bool {
+	// easy cases
+	switch {
+	case x == nil:
+		return false // t ∈ ∅ == false
+	case x.typ == nil:
+		return true // t ∈ 𝓤 == true
+	}
+	// ∅ ⊂ x ⊂ 𝓤
+
+	u := t
+	if x.tilde {
+		u = under(u)
+	}
+	return types.Identical(x.typ, u)
+}
+
+// subsetOf reports whether x ⊆ y.
+func (x *term) subsetOf(y *term) bool {
+	// easy cases
+	switch {
+	case x == nil:
+		return true // ∅ ⊆ y == true
+	case y == nil:
+		return false // x ⊆ ∅ == false since x != ∅
+	case y.typ == nil:
+		return true // x ⊆ 𝓤 == true
+	case x.typ == nil:
+		return false // 𝓤 ⊆ y == false since y != 𝓤
+	}
+	// ∅ ⊂ x, y ⊂ 𝓤
+
+	if x.disjoint(y) {
+		return false // x ⊆ y == false if x ∩ y == ∅
+	}
+	// x.typ == y.typ
+
+	// ~t ⊆ ~t == true
+	// ~t ⊆ T == false
+	//  T ⊆ ~t == true
+	//  T ⊆  T == true
+	return !x.tilde || y.tilde
+}
+
+// disjoint reports whether x ∩ y == ∅.
+// x.typ and y.typ must not be nil.
+func (x *term) disjoint(y *term) bool {
+	if debug && (x.typ == nil || y.typ == nil) {
+		panic("invalid argument(s)")
+	}
+	ux := x.typ
+	if y.tilde {
+		ux = under(ux)
+	}
+	uy := y.typ
+	if x.tilde {
+		uy = under(uy)
+	}
+	return !types.Identical(ux, uy)
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/classify_call.go b/vendor/golang.org/x/tools/internal/typesinternal/classify_call.go
new file mode 100644
index 000000000..649c82b6b
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/classify_call.go
@@ -0,0 +1,135 @@
+// Copyright 2018 The Go 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 typesinternal
+
+import (
+	"fmt"
+	"go/ast"
+	"go/types"
+	_ "unsafe"
+)
+
+// CallKind describes the function position of an [*ast.CallExpr].
+type CallKind int
+
+const (
+	CallStatic     CallKind = iota // static call to known function
+	CallInterface                  // dynamic call through an interface method
+	CallDynamic                    // dynamic call of a func value
+	CallBuiltin                    // call to a builtin function
+	CallConversion                 // a conversion (not a call)
+)
+
+var callKindNames = []string{
+	"CallStatic",
+	"CallInterface",
+	"CallDynamic",
+	"CallBuiltin",
+	"CallConversion",
+}
+
+func (k CallKind) String() string {
+	if i := int(k); i >= 0 && i < len(callKindNames) {
+		return callKindNames[i]
+	}
+	return fmt.Sprintf("typeutil.CallKind(%d)", k)
+}
+
+// ClassifyCall classifies the function position of a call expression ([*ast.CallExpr]).
+// It distinguishes among true function calls, calls to builtins, and type conversions,
+// and further classifies function calls as static calls (where the function is known),
+// dynamic interface calls, and other dynamic calls.
+//
+// For the declarations:
+//
+//	func f() {}
+//	func g[T any]() {}
+//	var v func()
+//	var s []func()
+//	type I interface { M() }
+//	var i I
+//
+// ClassifyCall returns the following:
+//
+//	f()           CallStatic
+//	g[int]()      CallStatic
+//	i.M()         CallInterface
+//	min(1, 2)     CallBuiltin
+//	v()           CallDynamic
+//	s[0]()        CallDynamic
+//	int(x)        CallConversion
+//	[]byte("")    CallConversion
+func ClassifyCall(info *types.Info, call *ast.CallExpr) CallKind {
+	if info.Types == nil {
+		panic("ClassifyCall: info.Types is nil")
+	}
+	if info.Types[call.Fun].IsType() {
+		return CallConversion
+	}
+	obj := info.Uses[UsedIdent(info, call.Fun)]
+	// Classify the call by the type of the object, if any.
+	switch obj := obj.(type) {
+	case *types.Builtin:
+		return CallBuiltin
+	case *types.Func:
+		if interfaceMethod(obj) {
+			return CallInterface
+		}
+		return CallStatic
+	default:
+		return CallDynamic
+	}
+}
+
+// UsedIdent returns the identifier such that info.Uses[UsedIdent(info, e)]
+// is the [types.Object] used by e, if any.
+//
+// If e is one of various forms of reference:
+//
+//	f, c, v, T           lexical reference
+//	pkg.X                qualified identifier
+//	f[T] or pkg.F[K,V]   instantiations of the above kinds
+//	expr.f               field or method value selector
+//	T.f                  method expression selector
+//
+// UsedIdent returns the identifier whose is associated value in [types.Info.Uses]
+// is the object to which it refers.
+//
+// For the declarations:
+//
+//	func F[T any] {...}
+//	type I interface { M() }
+//	var (
+//	  x int
+//	  s struct { f  int }
+//	  a []int
+//	  i I
+//	)
+//
+// UsedIdent returns the following:
+//
+//	Expr          UsedIdent
+//	x             x
+//	s.f           f
+//	F[int]        F
+//	i.M           M
+//	I.M           M
+//	min           min
+//	int           int
+//	1             nil
+//	a[0]          nil
+//	[]byte        nil
+//
+// Note: if e is an instantiated function or method, UsedIdent returns
+// the corresponding generic function or method on the generic type.
+func UsedIdent(info *types.Info, e ast.Expr) *ast.Ident {
+	return usedIdent(info, e)
+}
+
+//go:linkname usedIdent golang.org/x/tools/go/types/typeutil.usedIdent
+func usedIdent(info *types.Info, e ast.Expr) *ast.Ident
+
+//go:linkname interfaceMethod golang.org/x/tools/go/types/typeutil.interfaceMethod
+func interfaceMethod(f *types.Func) bool
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/element.go b/vendor/golang.org/x/tools/internal/typesinternal/element.go
new file mode 100644
index 000000000..4957f0216
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/element.go
@@ -0,0 +1,133 @@
+// Copyright 2024 The Go 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 typesinternal
+
+import (
+	"fmt"
+	"go/types"
+
+	"golang.org/x/tools/go/types/typeutil"
+)
+
+// ForEachElement calls f for type T and each type reachable from its
+// type through reflection. It does this by recursively stripping off
+// type constructors; in addition, for each named type N, the type *N
+// is added to the result as it may have additional methods.
+//
+// The caller must provide an initially empty set used to de-duplicate
+// identical types, potentially across multiple calls to ForEachElement.
+// (Its final value holds all the elements seen, matching the arguments
+// passed to f.)
+//
+// TODO(adonovan): share/harmonize with go/callgraph/rta.
+func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T types.Type, f func(types.Type)) {
+	var visit func(T types.Type, skip bool)
+	visit = func(T types.Type, skip bool) {
+		if !skip {
+			if seen, _ := rtypes.Set(T, true).(bool); seen {
+				return // de-dup
+			}
+
+			f(T) // notify caller of new element type
+		}
+
+		// Recursion over signatures of each method.
+		tmset := msets.MethodSet(T)
+		for i := 0; i < tmset.Len(); i++ {
+			sig := tmset.At(i).Type().(*types.Signature)
+			// It is tempting to call visit(sig, false)
+			// but, as noted in golang.org/cl/65450043,
+			// the Signature.Recv field is ignored by
+			// types.Identical and typeutil.Map, which
+			// is confusing at best.
+			//
+			// More importantly, the true signature rtype
+			// reachable from a method using reflection
+			// has no receiver but an extra ordinary parameter.
+			// For the Read method of io.Reader we want:
+			//   func(Reader, []byte) (int, error)
+			// but here sig is:
+			//   func([]byte) (int, error)
+			// with .Recv = Reader (though it is hard to
+			// notice because it doesn't affect Signature.String
+			// or types.Identical).
+			//
+			// TODO(adonovan): construct and visit the correct
+			// non-method signature with an extra parameter
+			// (though since unnamed func types have no methods
+			// there is essentially no actual demand for this).
+			//
+			// TODO(adonovan): document whether or not it is
+			// safe to skip non-exported methods (as RTA does).
+			visit(sig.Params(), true)  // skip the Tuple
+			visit(sig.Results(), true) // skip the Tuple
+		}
+
+		switch T := T.(type) {
+		case *types.Alias:
+			visit(types.Unalias(T), skip) // emulates the pre-Alias behavior
+
+		case *types.Basic:
+			// nop
+
+		case *types.Interface:
+			// nop---handled by recursion over method set.
+
+		case *types.Pointer:
+			visit(T.Elem(), false)
+
+		case *types.Slice:
+			visit(T.Elem(), false)
+
+		case *types.Chan:
+			visit(T.Elem(), false)
+
+		case *types.Map:
+			visit(T.Key(), false)
+			visit(T.Elem(), false)
+
+		case *types.Signature:
+			if T.Recv() != nil {
+				panic(fmt.Sprintf("Signature %s has Recv %s", T, T.Recv()))
+			}
+			visit(T.Params(), true)  // skip the Tuple
+			visit(T.Results(), true) // skip the Tuple
+
+		case *types.Named:
+			// A pointer-to-named type can be derived from a named
+			// type via reflection.  It may have methods too.
+			visit(types.NewPointer(T), false)
+
+			// Consider 'type T struct{S}' where S has methods.
+			// Reflection provides no way to get from T to struct{S},
+			// only to S, so the method set of struct{S} is unwanted,
+			// so set 'skip' flag during recursion.
+			visit(T.Underlying(), true) // skip the unnamed type
+
+		case *types.Array:
+			visit(T.Elem(), false)
+
+		case *types.Struct:
+			for i, n := 0, T.NumFields(); i < n; i++ {
+				// TODO(adonovan): document whether or not
+				// it is safe to skip non-exported fields.
+				visit(T.Field(i).Type(), false)
+			}
+
+		case *types.Tuple:
+			for i, n := 0, T.Len(); i < n; i++ {
+				visit(T.At(i).Type(), false)
+			}
+
+		case *types.TypeParam, *types.Union:
+			// forEachReachable must not be called on parameterized types.
+			panic(T)
+
+		default:
+			panic(T)
+		}
+	}
+	visit(T, false)
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go
new file mode 100644
index 000000000..235a6defc
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go
@@ -0,0 +1,1560 @@
+// Copyright 2020 The Go 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 typesinternal
+
+//go:generate stringer -type=ErrorCode
+
+type ErrorCode int
+
+// This file defines the error codes that can be produced during type-checking.
+// Collectively, these codes provide an identifier that may be used to
+// implement special handling for certain types of errors.
+//
+// Error codes should be fine-grained enough that the exact nature of the error
+// can be easily determined, but coarse enough that they are not an
+// implementation detail of the type checking algorithm. As a rule-of-thumb,
+// errors should be considered equivalent if there is a theoretical refactoring
+// of the type checker in which they are emitted in exactly one place. For
+// example, the type checker emits different error messages for "too many
+// arguments" and "too few arguments", but one can imagine an alternative type
+// checker where this check instead just emits a single "wrong number of
+// arguments", so these errors should have the same code.
+//
+// Error code names should be as brief as possible while retaining accuracy and
+// distinctiveness. In most cases names should start with an adjective
+// describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
+// and end with a noun identifying the relevant language object. For example,
+// "DuplicateDecl" or "InvalidSliceExpr". For brevity, naming follows the
+// convention that "bad" implies a problem with syntax, and "invalid" implies a
+// problem with types.
+
+const (
+	// InvalidSyntaxTree occurs if an invalid syntax tree is provided
+	// to the type checker. It should never happen.
+	InvalidSyntaxTree ErrorCode = -1
+)
+
+const (
+	_ ErrorCode = iota
+
+	// Test is reserved for errors that only apply while in self-test mode.
+	Test
+
+	/* package names */
+
+	// BlankPkgName occurs when a package name is the blank identifier "_".
+	//
+	// Per the spec:
+	//  "The PackageName must not be the blank identifier."
+	BlankPkgName
+
+	// MismatchedPkgName occurs when a file's package name doesn't match the
+	// package name already established by other files.
+	MismatchedPkgName
+
+	// InvalidPkgUse occurs when a package identifier is used outside of a
+	// selector expression.
+	//
+	// Example:
+	//  import "fmt"
+	//
+	//  var _ = fmt
+	InvalidPkgUse
+
+	/* imports */
+
+	// BadImportPath occurs when an import path is not valid.
+	BadImportPath
+
+	// BrokenImport occurs when importing a package fails.
+	//
+	// Example:
+	//  import "amissingpackage"
+	BrokenImport
+
+	// ImportCRenamed occurs when the special import "C" is renamed. "C" is a
+	// pseudo-package, and must not be renamed.
+	//
+	// Example:
+	//  import _ "C"
+	ImportCRenamed
+
+	// UnusedImport occurs when an import is unused.
+	//
+	// Example:
+	//  import "fmt"
+	//
+	//  func main() {}
+	UnusedImport
+
+	/* initialization */
+
+	// InvalidInitCycle occurs when an invalid cycle is detected within the
+	// initialization graph.
+	//
+	// Example:
+	//  var x int = f()
+	//
+	//  func f() int { return x }
+	InvalidInitCycle
+
+	/* decls */
+
+	// DuplicateDecl occurs when an identifier is declared multiple times.
+	//
+	// Example:
+	//  var x = 1
+	//  var x = 2
+	DuplicateDecl
+
+	// InvalidDeclCycle occurs when a declaration cycle is not valid.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  type T struct {
+	//  	a [n]int
+	//  }
+	//
+	//  var n = unsafe.Sizeof(T{})
+	InvalidDeclCycle
+
+	// InvalidTypeCycle occurs when a cycle in type definitions results in a
+	// type that is not well-defined.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  type T [unsafe.Sizeof(T{})]int
+	InvalidTypeCycle
+
+	/* decls > const */
+
+	// InvalidConstInit occurs when a const declaration has a non-constant
+	// initializer.
+	//
+	// Example:
+	//  var x int
+	//  const _ = x
+	InvalidConstInit
+
+	// InvalidConstVal occurs when a const value cannot be converted to its
+	// target type.
+	//
+	// TODO(findleyr): this error code and example are not very clear. Consider
+	// removing it.
+	//
+	// Example:
+	//  const _ = 1 << "hello"
+	InvalidConstVal
+
+	// InvalidConstType occurs when the underlying type in a const declaration
+	// is not a valid constant type.
+	//
+	// Example:
+	//  const c *int = 4
+	InvalidConstType
+
+	/* decls > var (+ other variable assignment codes) */
+
+	// UntypedNilUse occurs when the predeclared (untyped) value nil is used to
+	// initialize a variable declared without an explicit type.
+	//
+	// Example:
+	//  var x = nil
+	UntypedNilUse
+
+	// WrongAssignCount occurs when the number of values on the right-hand side
+	// of an assignment or initialization expression does not match the number
+	// of variables on the left-hand side.
+	//
+	// Example:
+	//  var x = 1, 2
+	WrongAssignCount
+
+	// UnassignableOperand occurs when the left-hand side of an assignment is
+	// not assignable.
+	//
+	// Example:
+	//  func f() {
+	//  	const c = 1
+	//  	c = 2
+	//  }
+	UnassignableOperand
+
+	// NoNewVar occurs when a short variable declaration (':=') does not declare
+	// new variables.
+	//
+	// Example:
+	//  func f() {
+	//  	x := 1
+	//  	x := 2
+	//  }
+	NoNewVar
+
+	// MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
+	// not have single-valued left-hand or right-hand side.
+	//
+	// Per the spec:
+	//  "In assignment operations, both the left- and right-hand expression lists
+	//  must contain exactly one single-valued expression"
+	//
+	// Example:
+	//  func f() int {
+	//  	x, y := 1, 2
+	//  	x, y += 1
+	//  	return x + y
+	//  }
+	MultiValAssignOp
+
+	// InvalidIfaceAssign occurs when a value of type T is used as an
+	// interface, but T does not implement a method of the expected interface.
+	//
+	// Example:
+	//  type I interface {
+	//  	f()
+	//  }
+	//
+	//  type T int
+	//
+	//  var x I = T(1)
+	InvalidIfaceAssign
+
+	// InvalidChanAssign occurs when a chan assignment is invalid.
+	//
+	// Per the spec, a value x is assignable to a channel type T if:
+	//  "x is a bidirectional channel value, T is a channel type, x's type V and
+	//  T have identical element types, and at least one of V or T is not a
+	//  defined type."
+	//
+	// Example:
+	//  type T1 chan int
+	//  type T2 chan int
+	//
+	//  var x T1
+	//  // Invalid assignment because both types are named
+	//  var _ T2 = x
+	InvalidChanAssign
+
+	// IncompatibleAssign occurs when the type of the right-hand side expression
+	// in an assignment cannot be assigned to the type of the variable being
+	// assigned.
+	//
+	// Example:
+	//  var x []int
+	//  var _ int = x
+	IncompatibleAssign
+
+	// UnaddressableFieldAssign occurs when trying to assign to a struct field
+	// in a map value.
+	//
+	// Example:
+	//  func f() {
+	//  	m := make(map[string]struct{i int})
+	//  	m["foo"].i = 42
+	//  }
+	UnaddressableFieldAssign
+
+	/* decls > type (+ other type expression codes) */
+
+	// NotAType occurs when the identifier used as the underlying type in a type
+	// declaration or the right-hand side of a type alias does not denote a type.
+	//
+	// Example:
+	//  var S = 2
+	//
+	//  type T S
+	NotAType
+
+	// InvalidArrayLen occurs when an array length is not a constant value.
+	//
+	// Example:
+	//  var n = 3
+	//  var _ = [n]int{}
+	InvalidArrayLen
+
+	// BlankIfaceMethod occurs when a method name is '_'.
+	//
+	// Per the spec:
+	//  "The name of each explicitly specified method must be unique and not
+	//  blank."
+	//
+	// Example:
+	//  type T interface {
+	//  	_(int)
+	//  }
+	BlankIfaceMethod
+
+	// IncomparableMapKey occurs when a map key type does not support the == and
+	// != operators.
+	//
+	// Per the spec:
+	//  "The comparison operators == and != must be fully defined for operands of
+	//  the key type; thus the key type must not be a function, map, or slice."
+	//
+	// Example:
+	//  var x map[T]int
+	//
+	//  type T []int
+	IncomparableMapKey
+
+	// InvalidIfaceEmbed occurs when a non-interface type is embedded in an
+	// interface.
+	//
+	// Example:
+	//  type T struct {}
+	//
+	//  func (T) m()
+	//
+	//  type I interface {
+	//  	T
+	//  }
+	InvalidIfaceEmbed
+
+	// InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
+	// and T itself is itself a pointer, an unsafe.Pointer, or an interface.
+	//
+	// Per the spec:
+	//  "An embedded field must be specified as a type name T or as a pointer to
+	//  a non-interface type name *T, and T itself may not be a pointer type."
+	//
+	// Example:
+	//  type T *int
+	//
+	//  type S struct {
+	//  	*T
+	//  }
+	InvalidPtrEmbed
+
+	/* decls > func and method */
+
+	// BadRecv occurs when a method declaration does not have exactly one
+	// receiver parameter.
+	//
+	// Example:
+	//  func () _() {}
+	BadRecv
+
+	// InvalidRecv occurs when a receiver type expression is not of the form T
+	// or *T, or T is a pointer type.
+	//
+	// Example:
+	//  type T struct {}
+	//
+	//  func (**T) m() {}
+	InvalidRecv
+
+	// DuplicateFieldAndMethod occurs when an identifier appears as both a field
+	// and method name.
+	//
+	// Example:
+	//  type T struct {
+	//  	m int
+	//  }
+	//
+	//  func (T) m() {}
+	DuplicateFieldAndMethod
+
+	// DuplicateMethod occurs when two methods on the same receiver type have
+	// the same name.
+	//
+	// Example:
+	//  type T struct {}
+	//  func (T) m() {}
+	//  func (T) m(i int) int { return i }
+	DuplicateMethod
+
+	/* decls > special */
+
+	// InvalidBlank occurs when a blank identifier is used as a value or type.
+	//
+	// Per the spec:
+	//  "The blank identifier may appear as an operand only on the left-hand side
+	//  of an assignment."
+	//
+	// Example:
+	//  var x = _
+	InvalidBlank
+
+	// InvalidIota occurs when the predeclared identifier iota is used outside
+	// of a constant declaration.
+	//
+	// Example:
+	//  var x = iota
+	InvalidIota
+
+	// MissingInitBody occurs when an init function is missing its body.
+	//
+	// Example:
+	//  func init()
+	MissingInitBody
+
+	// InvalidInitSig occurs when an init function declares parameters or
+	// results.
+	//
+	// Example:
+	//  func init() int { return 1 }
+	InvalidInitSig
+
+	// InvalidInitDecl occurs when init is declared as anything other than a
+	// function.
+	//
+	// Example:
+	//  var init = 1
+	InvalidInitDecl
+
+	// InvalidMainDecl occurs when main is declared as anything other than a
+	// function, in a main package.
+	InvalidMainDecl
+
+	/* exprs */
+
+	// TooManyValues occurs when a function returns too many values for the
+	// expression context in which it is used.
+	//
+	// Example:
+	//  func ReturnTwo() (int, int) {
+	//  	return 1, 2
+	//  }
+	//
+	//  var x = ReturnTwo()
+	TooManyValues
+
+	// NotAnExpr occurs when a type expression is used where a value expression
+	// is expected.
+	//
+	// Example:
+	//  type T struct {}
+	//
+	//  func f() {
+	//  	T
+	//  }
+	NotAnExpr
+
+	/* exprs > const */
+
+	// TruncatedFloat occurs when a float constant is truncated to an integer
+	// value.
+	//
+	// Example:
+	//  var _ int = 98.6
+	TruncatedFloat
+
+	// NumericOverflow occurs when a numeric constant overflows its target type.
+	//
+	// Example:
+	//  var x int8 = 1000
+	NumericOverflow
+
+	/* exprs > operation */
+
+	// UndefinedOp occurs when an operator is not defined for the type(s) used
+	// in an operation.
+	//
+	// Example:
+	//  var c = "a" - "b"
+	UndefinedOp
+
+	// MismatchedTypes occurs when operand types are incompatible in a binary
+	// operation.
+	//
+	// Example:
+	//  var a = "hello"
+	//  var b = 1
+	//  var c = a - b
+	MismatchedTypes
+
+	// DivByZero occurs when a division operation is provable at compile
+	// time to be a division by zero.
+	//
+	// Example:
+	//  const divisor = 0
+	//  var x int = 1/divisor
+	DivByZero
+
+	// NonNumericIncDec occurs when an increment or decrement operator is
+	// applied to a non-numeric value.
+	//
+	// Example:
+	//  func f() {
+	//  	var c = "c"
+	//  	c++
+	//  }
+	NonNumericIncDec
+
+	/* exprs > ptr */
+
+	// UnaddressableOperand occurs when the & operator is applied to an
+	// unaddressable expression.
+	//
+	// Example:
+	//  var x = &1
+	UnaddressableOperand
+
+	// InvalidIndirection occurs when a non-pointer value is indirected via the
+	// '*' operator.
+	//
+	// Example:
+	//  var x int
+	//  var y = *x
+	InvalidIndirection
+
+	/* exprs > [] */
+
+	// NonIndexableOperand occurs when an index operation is applied to a value
+	// that cannot be indexed.
+	//
+	// Example:
+	//  var x = 1
+	//  var y = x[1]
+	NonIndexableOperand
+
+	// InvalidIndex occurs when an index argument is not of integer type,
+	// negative, or out-of-bounds.
+	//
+	// Example:
+	//  var s = [...]int{1,2,3}
+	//  var x = s[5]
+	//
+	// Example:
+	//  var s = []int{1,2,3}
+	//  var _ = s[-1]
+	//
+	// Example:
+	//  var s = []int{1,2,3}
+	//  var i string
+	//  var _ = s[i]
+	InvalidIndex
+
+	// SwappedSliceIndices occurs when constant indices in a slice expression
+	// are decreasing in value.
+	//
+	// Example:
+	//  var _ = []int{1,2,3}[2:1]
+	SwappedSliceIndices
+
+	/* operators > slice */
+
+	// NonSliceableOperand occurs when a slice operation is applied to a value
+	// whose type is not sliceable, or is unaddressable.
+	//
+	// Example:
+	//  var x = [...]int{1, 2, 3}[:1]
+	//
+	// Example:
+	//  var x = 1
+	//  var y = 1[:1]
+	NonSliceableOperand
+
+	// InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
+	// applied to a string.
+	//
+	// Example:
+	//  var s = "hello"
+	//  var x = s[1:2:3]
+	InvalidSliceExpr
+
+	/* exprs > shift */
+
+	// InvalidShiftCount occurs when the right-hand side of a shift operation is
+	// either non-integer, negative, or too large.
+	//
+	// Example:
+	//  var (
+	//  	x string
+	//  	y int = 1 << x
+	//  )
+	InvalidShiftCount
+
+	// InvalidShiftOperand occurs when the shifted operand is not an integer.
+	//
+	// Example:
+	//  var s = "hello"
+	//  var x = s << 2
+	InvalidShiftOperand
+
+	/* exprs > chan */
+
+	// InvalidReceive occurs when there is a channel receive from a value that
+	// is either not a channel, or is a send-only channel.
+	//
+	// Example:
+	//  func f() {
+	//  	var x = 1
+	//  	<-x
+	//  }
+	InvalidReceive
+
+	// InvalidSend occurs when there is a channel send to a value that is not a
+	// channel, or is a receive-only channel.
+	//
+	// Example:
+	//  func f() {
+	//  	var x = 1
+	//  	x <- "hello!"
+	//  }
+	InvalidSend
+
+	/* exprs > literal */
+
+	// DuplicateLitKey occurs when an index is duplicated in a slice, array, or
+	// map literal.
+	//
+	// Example:
+	//  var _ = []int{0:1, 0:2}
+	//
+	// Example:
+	//  var _ = map[string]int{"a": 1, "a": 2}
+	DuplicateLitKey
+
+	// MissingLitKey occurs when a map literal is missing a key expression.
+	//
+	// Example:
+	//  var _ = map[string]int{1}
+	MissingLitKey
+
+	// InvalidLitIndex occurs when the key in a key-value element of a slice or
+	// array literal is not an integer constant.
+	//
+	// Example:
+	//  var i = 0
+	//  var x = []string{i: "world"}
+	InvalidLitIndex
+
+	// OversizeArrayLit occurs when an array literal exceeds its length.
+	//
+	// Example:
+	//  var _ = [2]int{1,2,3}
+	OversizeArrayLit
+
+	// MixedStructLit occurs when a struct literal contains a mix of positional
+	// and named elements.
+	//
+	// Example:
+	//  var _ = struct{i, j int}{i: 1, 2}
+	MixedStructLit
+
+	// InvalidStructLit occurs when a positional struct literal has an incorrect
+	// number of values.
+	//
+	// Example:
+	//  var _ = struct{i, j int}{1,2,3}
+	InvalidStructLit
+
+	// MissingLitField occurs when a struct literal refers to a field that does
+	// not exist on the struct type.
+	//
+	// Example:
+	//  var _ = struct{i int}{j: 2}
+	MissingLitField
+
+	// DuplicateLitField occurs when a struct literal contains duplicated
+	// fields.
+	//
+	// Example:
+	//  var _ = struct{i int}{i: 1, i: 2}
+	DuplicateLitField
+
+	// UnexportedLitField occurs when a positional struct literal implicitly
+	// assigns an unexported field of an imported type.
+	UnexportedLitField
+
+	// InvalidLitField occurs when a field name is not a valid identifier.
+	//
+	// Example:
+	//  var _ = struct{i int}{1: 1}
+	InvalidLitField
+
+	// UntypedLit occurs when a composite literal omits a required type
+	// identifier.
+	//
+	// Example:
+	//  type outer struct{
+	//  	inner struct { i int }
+	//  }
+	//
+	//  var _ = outer{inner: {1}}
+	UntypedLit
+
+	// InvalidLit occurs when a composite literal expression does not match its
+	// type.
+	//
+	// Example:
+	//  type P *struct{
+	//  	x int
+	//  }
+	//  var _ = P {}
+	InvalidLit
+
+	/* exprs > selector */
+
+	// AmbiguousSelector occurs when a selector is ambiguous.
+	//
+	// Example:
+	//  type E1 struct { i int }
+	//  type E2 struct { i int }
+	//  type T struct { E1; E2 }
+	//
+	//  var x T
+	//  var _ = x.i
+	AmbiguousSelector
+
+	// UndeclaredImportedName occurs when a package-qualified identifier is
+	// undeclared by the imported package.
+	//
+	// Example:
+	//  import "go/types"
+	//
+	//  var _ = types.NotAnActualIdentifier
+	UndeclaredImportedName
+
+	// UnexportedName occurs when a selector refers to an unexported identifier
+	// of an imported package.
+	//
+	// Example:
+	//  import "reflect"
+	//
+	//  type _ reflect.flag
+	UnexportedName
+
+	// UndeclaredName occurs when an identifier is not declared in the current
+	// scope.
+	//
+	// Example:
+	//  var x T
+	UndeclaredName
+
+	// MissingFieldOrMethod occurs when a selector references a field or method
+	// that does not exist.
+	//
+	// Example:
+	//  type T struct {}
+	//
+	//  var x = T{}.f
+	MissingFieldOrMethod
+
+	/* exprs > ... */
+
+	// BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
+	// not valid.
+	//
+	// Example:
+	//  var _ = map[int][...]int{0: {}}
+	BadDotDotDotSyntax
+
+	// NonVariadicDotDotDot occurs when a "..." is used on the final argument to
+	// a non-variadic function.
+	//
+	// Example:
+	//  func printArgs(s []string) {
+	//  	for _, a := range s {
+	//  		println(a)
+	//  	}
+	//  }
+	//
+	//  func f() {
+	//  	s := []string{"a", "b", "c"}
+	//  	printArgs(s...)
+	//  }
+	NonVariadicDotDotDot
+
+	// MisplacedDotDotDot occurs when a "..." is used somewhere other than the
+	// final argument to a function call.
+	//
+	// Example:
+	//  func printArgs(args ...int) {
+	//  	for _, a := range args {
+	//  		println(a)
+	//  	}
+	//  }
+	//
+	//  func f() {
+	//  	a := []int{1,2,3}
+	//  	printArgs(0, a...)
+	//  }
+	MisplacedDotDotDot
+
+	// InvalidDotDotDotOperand occurs when a "..." operator is applied to a
+	// single-valued operand.
+	//
+	// Example:
+	//  func printArgs(args ...int) {
+	//  	for _, a := range args {
+	//  		println(a)
+	//  	}
+	//  }
+	//
+	//  func f() {
+	//  	a := 1
+	//  	printArgs(a...)
+	//  }
+	//
+	// Example:
+	//  func args() (int, int) {
+	//  	return 1, 2
+	//  }
+	//
+	//  func printArgs(args ...int) {
+	//  	for _, a := range args {
+	//  		println(a)
+	//  	}
+	//  }
+	//
+	//  func g() {
+	//  	printArgs(args()...)
+	//  }
+	InvalidDotDotDotOperand
+
+	// InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
+	// function.
+	//
+	// Example:
+	//  var s = []int{1, 2, 3}
+	//  var l = len(s...)
+	InvalidDotDotDot
+
+	/* exprs > built-in */
+
+	// UncalledBuiltin occurs when a built-in function is used as a
+	// function-valued expression, instead of being called.
+	//
+	// Per the spec:
+	//  "The built-in functions do not have standard Go types, so they can only
+	//  appear in call expressions; they cannot be used as function values."
+	//
+	// Example:
+	//  var _ = copy
+	UncalledBuiltin
+
+	// InvalidAppend occurs when append is called with a first argument that is
+	// not a slice.
+	//
+	// Example:
+	//  var _ = append(1, 2)
+	InvalidAppend
+
+	// InvalidCap occurs when an argument to the cap built-in function is not of
+	// supported type.
+	//
+	// See https://golang.org/ref/spec#Length_and_capacity for information on
+	// which underlying types are supported as arguments to cap and len.
+	//
+	// Example:
+	//  var s = 2
+	//  var x = cap(s)
+	InvalidCap
+
+	// InvalidClose occurs when close(...) is called with an argument that is
+	// not of channel type, or that is a receive-only channel.
+	//
+	// Example:
+	//  func f() {
+	//  	var x int
+	//  	close(x)
+	//  }
+	InvalidClose
+
+	// InvalidCopy occurs when the arguments are not of slice type or do not
+	// have compatible type.
+	//
+	// See https://golang.org/ref/spec#Appending_and_copying_slices for more
+	// information on the type requirements for the copy built-in.
+	//
+	// Example:
+	//  func f() {
+	//  	var x []int
+	//  	y := []int64{1,2,3}
+	//  	copy(x, y)
+	//  }
+	InvalidCopy
+
+	// InvalidComplex occurs when the complex built-in function is called with
+	// arguments with incompatible types.
+	//
+	// Example:
+	//  var _ = complex(float32(1), float64(2))
+	InvalidComplex
+
+	// InvalidDelete occurs when the delete built-in function is called with a
+	// first argument that is not a map.
+	//
+	// Example:
+	//  func f() {
+	//  	m := "hello"
+	//  	delete(m, "e")
+	//  }
+	InvalidDelete
+
+	// InvalidImag occurs when the imag built-in function is called with an
+	// argument that does not have complex type.
+	//
+	// Example:
+	//  var _ = imag(int(1))
+	InvalidImag
+
+	// InvalidLen occurs when an argument to the len built-in function is not of
+	// supported type.
+	//
+	// See https://golang.org/ref/spec#Length_and_capacity for information on
+	// which underlying types are supported as arguments to cap and len.
+	//
+	// Example:
+	//  var s = 2
+	//  var x = len(s)
+	InvalidLen
+
+	// SwappedMakeArgs occurs when make is called with three arguments, and its
+	// length argument is larger than its capacity argument.
+	//
+	// Example:
+	//  var x = make([]int, 3, 2)
+	SwappedMakeArgs
+
+	// InvalidMake occurs when make is called with an unsupported type argument.
+	//
+	// See https://golang.org/ref/spec#Making_slices_maps_and_channels for
+	// information on the types that may be created using make.
+	//
+	// Example:
+	//  var x = make(int)
+	InvalidMake
+
+	// InvalidReal occurs when the real built-in function is called with an
+	// argument that does not have complex type.
+	//
+	// Example:
+	//  var _ = real(int(1))
+	InvalidReal
+
+	/* exprs > assertion */
+
+	// InvalidAssert occurs when a type assertion is applied to a
+	// value that is not of interface type.
+	//
+	// Example:
+	//  var x = 1
+	//  var _ = x.(float64)
+	InvalidAssert
+
+	// ImpossibleAssert occurs for a type assertion x.(T) when the value x of
+	// interface cannot have dynamic type T, due to a missing or mismatching
+	// method on T.
+	//
+	// Example:
+	//  type T int
+	//
+	//  func (t *T) m() int { return int(*t) }
+	//
+	//  type I interface { m() int }
+	//
+	//  var x I
+	//  var _ = x.(T)
+	ImpossibleAssert
+
+	/* exprs > conversion */
+
+	// InvalidConversion occurs when the argument type cannot be converted to the
+	// target.
+	//
+	// See https://golang.org/ref/spec#Conversions for the rules of
+	// convertibility.
+	//
+	// Example:
+	//  var x float64
+	//  var _ = string(x)
+	InvalidConversion
+
+	// InvalidUntypedConversion occurs when there is no valid implicit
+	// conversion from an untyped value satisfying the type constraints of the
+	// context in which it is used.
+	//
+	// Example:
+	//  var _ = 1 + ""
+	InvalidUntypedConversion
+
+	/* offsetof */
+
+	// BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
+	// that is not a selector expression.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.Offsetof(x)
+	BadOffsetofSyntax
+
+	// InvalidOffsetof occurs when unsafe.Offsetof is called with a method
+	// selector, rather than a field selector, or when the field is embedded via
+	// a pointer.
+	//
+	// Per the spec:
+	//
+	//  "If f is an embedded field, it must be reachable without pointer
+	//  indirections through fields of the struct. "
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  type T struct { f int }
+	//  type S struct { *T }
+	//  var s S
+	//  var _ = unsafe.Offsetof(s.f)
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  type S struct{}
+	//
+	//  func (S) m() {}
+	//
+	//  var s S
+	//  var _ = unsafe.Offsetof(s.m)
+	InvalidOffsetof
+
+	/* control flow > scope */
+
+	// UnusedExpr occurs when a side-effect free expression is used as a
+	// statement. Such a statement has no effect.
+	//
+	// Example:
+	//  func f(i int) {
+	//  	i*i
+	//  }
+	UnusedExpr
+
+	// UnusedVar occurs when a variable is declared but unused.
+	//
+	// Example:
+	//  func f() {
+	//  	x := 1
+	//  }
+	UnusedVar
+
+	// MissingReturn occurs when a function with results is missing a return
+	// statement.
+	//
+	// Example:
+	//  func f() int {}
+	MissingReturn
+
+	// WrongResultCount occurs when a return statement returns an incorrect
+	// number of values.
+	//
+	// Example:
+	//  func ReturnOne() int {
+	//  	return 1, 2
+	//  }
+	WrongResultCount
+
+	// OutOfScopeResult occurs when the name of a value implicitly returned by
+	// an empty return statement is shadowed in a nested scope.
+	//
+	// Example:
+	//  func factor(n int) (i int) {
+	//  	for i := 2; i < n; i++ {
+	//  		if n%i == 0 {
+	//  			return
+	//  		}
+	//  	}
+	//  	return 0
+	//  }
+	OutOfScopeResult
+
+	/* control flow > if */
+
+	// InvalidCond occurs when an if condition is not a boolean expression.
+	//
+	// Example:
+	//  func checkReturn(i int) {
+	//  	if i {
+	//  		panic("non-zero return")
+	//  	}
+	//  }
+	InvalidCond
+
+	/* control flow > for */
+
+	// InvalidPostDecl occurs when there is a declaration in a for-loop post
+	// statement.
+	//
+	// Example:
+	//  func f() {
+	//  	for i := 0; i < 10; j := 0 {}
+	//  }
+	InvalidPostDecl
+
+	// InvalidChanRange occurs when a send-only channel used in a range
+	// expression.
+	//
+	// Example:
+	//  func sum(c chan<- int) {
+	//  	s := 0
+	//  	for i := range c {
+	//  		s += i
+	//  	}
+	//  }
+	InvalidChanRange
+
+	// InvalidIterVar occurs when two iteration variables are used while ranging
+	// over a channel.
+	//
+	// Example:
+	//  func f(c chan int) {
+	//  	for k, v := range c {
+	//  		println(k, v)
+	//  	}
+	//  }
+	InvalidIterVar
+
+	// InvalidRangeExpr occurs when the type of a range expression is not array,
+	// slice, string, map, or channel.
+	//
+	// Example:
+	//  func f(i int) {
+	//  	for j := range i {
+	//  		println(j)
+	//  	}
+	//  }
+	InvalidRangeExpr
+
+	/* control flow > switch */
+
+	// MisplacedBreak occurs when a break statement is not within a for, switch,
+	// or select statement of the innermost function definition.
+	//
+	// Example:
+	//  func f() {
+	//  	break
+	//  }
+	MisplacedBreak
+
+	// MisplacedContinue occurs when a continue statement is not within a for
+	// loop of the innermost function definition.
+	//
+	// Example:
+	//  func sumeven(n int) int {
+	//  	proceed := func() {
+	//  		continue
+	//  	}
+	//  	sum := 0
+	//  	for i := 1; i <= n; i++ {
+	//  		if i % 2 != 0 {
+	//  			proceed()
+	//  		}
+	//  		sum += i
+	//  	}
+	//  	return sum
+	//  }
+	MisplacedContinue
+
+	// MisplacedFallthrough occurs when a fallthrough statement is not within an
+	// expression switch.
+	//
+	// Example:
+	//  func typename(i interface{}) string {
+	//  	switch i.(type) {
+	//  	case int64:
+	//  		fallthrough
+	//  	case int:
+	//  		return "int"
+	//  	}
+	//  	return "unsupported"
+	//  }
+	MisplacedFallthrough
+
+	// DuplicateCase occurs when a type or expression switch has duplicate
+	// cases.
+	//
+	// Example:
+	//  func printInt(i int) {
+	//  	switch i {
+	//  	case 1:
+	//  		println("one")
+	//  	case 1:
+	//  		println("One")
+	//  	}
+	//  }
+	DuplicateCase
+
+	// DuplicateDefault occurs when a type or expression switch has multiple
+	// default clauses.
+	//
+	// Example:
+	//  func printInt(i int) {
+	//  	switch i {
+	//  	case 1:
+	//  		println("one")
+	//  	default:
+	//  		println("One")
+	//  	default:
+	//  		println("1")
+	//  	}
+	//  }
+	DuplicateDefault
+
+	// BadTypeKeyword occurs when a .(type) expression is used anywhere other
+	// than a type switch.
+	//
+	// Example:
+	//  type I interface {
+	//  	m()
+	//  }
+	//  var t I
+	//  var _ = t.(type)
+	BadTypeKeyword
+
+	// InvalidTypeSwitch occurs when .(type) is used on an expression that is
+	// not of interface type.
+	//
+	// Example:
+	//  func f(i int) {
+	//  	switch x := i.(type) {}
+	//  }
+	InvalidTypeSwitch
+
+	// InvalidExprSwitch occurs when a switch expression is not comparable.
+	//
+	// Example:
+	//  func _() {
+	//  	var a struct{ _ func() }
+	//  	switch a /* ERROR cannot switch on a */ {
+	//  	}
+	//  }
+	InvalidExprSwitch
+
+	/* control flow > select */
+
+	// InvalidSelectCase occurs when a select case is not a channel send or
+	// receive.
+	//
+	// Example:
+	//  func checkChan(c <-chan int) bool {
+	//  	select {
+	//  	case c:
+	//  		return true
+	//  	default:
+	//  		return false
+	//  	}
+	//  }
+	InvalidSelectCase
+
+	/* control flow > labels and jumps */
+
+	// UndeclaredLabel occurs when an undeclared label is jumped to.
+	//
+	// Example:
+	//  func f() {
+	//  	goto L
+	//  }
+	UndeclaredLabel
+
+	// DuplicateLabel occurs when a label is declared more than once.
+	//
+	// Example:
+	//  func f() int {
+	//  L:
+	//  L:
+	//  	return 1
+	//  }
+	DuplicateLabel
+
+	// MisplacedLabel occurs when a break or continue label is not on a for,
+	// switch, or select statement.
+	//
+	// Example:
+	//  func f() {
+	//  L:
+	//  	a := []int{1,2,3}
+	//  	for _, e := range a {
+	//  		if e > 10 {
+	//  			break L
+	//  		}
+	//  		println(a)
+	//  	}
+	//  }
+	MisplacedLabel
+
+	// UnusedLabel occurs when a label is declared but not used.
+	//
+	// Example:
+	//  func f() {
+	//  L:
+	//  }
+	UnusedLabel
+
+	// JumpOverDecl occurs when a label jumps over a variable declaration.
+	//
+	// Example:
+	//  func f() int {
+	//  	goto L
+	//  	x := 2
+	//  L:
+	//  	x++
+	//  	return x
+	//  }
+	JumpOverDecl
+
+	// JumpIntoBlock occurs when a forward jump goes to a label inside a nested
+	// block.
+	//
+	// Example:
+	//  func f(x int) {
+	//  	goto L
+	//  	if x > 0 {
+	//  	L:
+	//  		print("inside block")
+	//  	}
+	// }
+	JumpIntoBlock
+
+	/* control flow > calls */
+
+	// InvalidMethodExpr occurs when a pointer method is called but the argument
+	// is not addressable.
+	//
+	// Example:
+	//  type T struct {}
+	//
+	//  func (*T) m() int { return 1 }
+	//
+	//  var _ = T.m(T{})
+	InvalidMethodExpr
+
+	// WrongArgCount occurs when too few or too many arguments are passed by a
+	// function call.
+	//
+	// Example:
+	//  func f(i int) {}
+	//  var x = f()
+	WrongArgCount
+
+	// InvalidCall occurs when an expression is called that is not of function
+	// type.
+	//
+	// Example:
+	//  var x = "x"
+	//  var y = x()
+	InvalidCall
+
+	/* control flow > suspended */
+
+	// UnusedResults occurs when a restricted expression-only built-in function
+	// is suspended via go or defer. Such a suspension discards the results of
+	// these side-effect free built-in functions, and therefore is ineffectual.
+	//
+	// Example:
+	//  func f(a []int) int {
+	//  	defer len(a)
+	//  	return i
+	//  }
+	UnusedResults
+
+	// InvalidDefer occurs when a deferred expression is not a function call,
+	// for example if the expression is a type conversion.
+	//
+	// Example:
+	//  func f(i int) int {
+	//  	defer int32(i)
+	//  	return i
+	//  }
+	InvalidDefer
+
+	// InvalidGo occurs when a go expression is not a function call, for example
+	// if the expression is a type conversion.
+	//
+	// Example:
+	//  func f(i int) int {
+	//  	go int32(i)
+	//  	return i
+	//  }
+	InvalidGo
+
+	// All codes below were added in Go 1.17.
+
+	/* decl */
+
+	// BadDecl occurs when a declaration has invalid syntax.
+	BadDecl
+
+	// RepeatedDecl occurs when an identifier occurs more than once on the left
+	// hand side of a short variable declaration.
+	//
+	// Example:
+	//  func _() {
+	//  	x, y, y := 1, 2, 3
+	//  }
+	RepeatedDecl
+
+	/* unsafe */
+
+	// InvalidUnsafeAdd occurs when unsafe.Add is called with a
+	// length argument that is not of integer type.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var p unsafe.Pointer
+	//  var _ = unsafe.Add(p, float64(1))
+	InvalidUnsafeAdd
+
+	// InvalidUnsafeSlice occurs when unsafe.Slice is called with a
+	// pointer argument that is not of pointer type or a length argument
+	// that is not of integer type, negative, or out of bounds.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.Slice(x, 1)
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.Slice(&x, float64(1))
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.Slice(&x, -1)
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.Slice(&x, uint64(1) << 63)
+	InvalidUnsafeSlice
+
+	// All codes below were added in Go 1.18.
+
+	/* features */
+
+	// UnsupportedFeature occurs when a language feature is used that is not
+	// supported at this Go version.
+	UnsupportedFeature
+
+	/* type params */
+
+	// NotAGenericType occurs when a non-generic type is used where a generic
+	// type is expected: in type or function instantiation.
+	//
+	// Example:
+	//  type T int
+	//
+	//  var _ T[int]
+	NotAGenericType
+
+	// WrongTypeArgCount occurs when a type or function is instantiated with an
+	// incorrect number of type arguments, including when a generic type or
+	// function is used without instantiation.
+	//
+	// Errors involving failed type inference are assigned other error codes.
+	//
+	// Example:
+	//  type T[p any] int
+	//
+	//  var _ T[int, string]
+	//
+	// Example:
+	//  func f[T any]() {}
+	//
+	//  var x = f
+	WrongTypeArgCount
+
+	// CannotInferTypeArgs occurs when type or function type argument inference
+	// fails to infer all type arguments.
+	//
+	// Example:
+	//  func f[T any]() {}
+	//
+	//  func _() {
+	//  	f()
+	//  }
+	//
+	// Example:
+	//   type N[P, Q any] struct{}
+	//
+	//   var _ N[int]
+	CannotInferTypeArgs
+
+	// InvalidTypeArg occurs when a type argument does not satisfy its
+	// corresponding type parameter constraints.
+	//
+	// Example:
+	//  type T[P ~int] struct{}
+	//
+	//  var _ T[string]
+	InvalidTypeArg // arguments? InferenceFailed
+
+	// InvalidInstanceCycle occurs when an invalid cycle is detected
+	// within the instantiation graph.
+	//
+	// Example:
+	//  func f[T any]() { f[*T]() }
+	InvalidInstanceCycle
+
+	// InvalidUnion occurs when an embedded union or approximation element is
+	// not valid.
+	//
+	// Example:
+	//  type _ interface {
+	//   	~int | interface{ m() }
+	//  }
+	InvalidUnion
+
+	// MisplacedConstraintIface occurs when a constraint-type interface is used
+	// outside of constraint position.
+	//
+	// Example:
+	//   type I interface { ~int }
+	//
+	//   var _ I
+	MisplacedConstraintIface
+
+	// InvalidMethodTypeParams occurs when methods have type parameters.
+	//
+	// It cannot be encountered with an AST parsed using go/parser.
+	InvalidMethodTypeParams
+
+	// MisplacedTypeParam occurs when a type parameter is used in a place where
+	// it is not permitted.
+	//
+	// Example:
+	//  type T[P any] P
+	//
+	// Example:
+	//  type T[P any] struct{ *P }
+	MisplacedTypeParam
+
+	// InvalidUnsafeSliceData occurs when unsafe.SliceData is called with
+	// an argument that is not of slice type. It also occurs if it is used
+	// in a package compiled for a language version before go1.20.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var x int
+	//  var _ = unsafe.SliceData(x)
+	InvalidUnsafeSliceData
+
+	// InvalidUnsafeString occurs when unsafe.String is called with
+	// a length argument that is not of integer type, negative, or
+	// out of bounds. It also occurs if it is used in a package
+	// compiled for a language version before go1.20.
+	//
+	// Example:
+	//  import "unsafe"
+	//
+	//  var b [10]byte
+	//  var _ = unsafe.String(&b[0], -1)
+	InvalidUnsafeString
+
+	// InvalidUnsafeStringData occurs if it is used in a package
+	// compiled for a language version before go1.20.
+	_ // not used anymore
+
+)
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go b/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go
new file mode 100644
index 000000000..15ecf7c5d
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go
@@ -0,0 +1,179 @@
+// Code generated by "stringer -type=ErrorCode"; DO NOT EDIT.
+
+package typesinternal
+
+import "strconv"
+
+func _() {
+	// An "invalid array index" compiler error signifies that the constant values have changed.
+	// Re-run the stringer command to generate them again.
+	var x [1]struct{}
+	_ = x[InvalidSyntaxTree - -1]
+	_ = x[Test-1]
+	_ = x[BlankPkgName-2]
+	_ = x[MismatchedPkgName-3]
+	_ = x[InvalidPkgUse-4]
+	_ = x[BadImportPath-5]
+	_ = x[BrokenImport-6]
+	_ = x[ImportCRenamed-7]
+	_ = x[UnusedImport-8]
+	_ = x[InvalidInitCycle-9]
+	_ = x[DuplicateDecl-10]
+	_ = x[InvalidDeclCycle-11]
+	_ = x[InvalidTypeCycle-12]
+	_ = x[InvalidConstInit-13]
+	_ = x[InvalidConstVal-14]
+	_ = x[InvalidConstType-15]
+	_ = x[UntypedNilUse-16]
+	_ = x[WrongAssignCount-17]
+	_ = x[UnassignableOperand-18]
+	_ = x[NoNewVar-19]
+	_ = x[MultiValAssignOp-20]
+	_ = x[InvalidIfaceAssign-21]
+	_ = x[InvalidChanAssign-22]
+	_ = x[IncompatibleAssign-23]
+	_ = x[UnaddressableFieldAssign-24]
+	_ = x[NotAType-25]
+	_ = x[InvalidArrayLen-26]
+	_ = x[BlankIfaceMethod-27]
+	_ = x[IncomparableMapKey-28]
+	_ = x[InvalidIfaceEmbed-29]
+	_ = x[InvalidPtrEmbed-30]
+	_ = x[BadRecv-31]
+	_ = x[InvalidRecv-32]
+	_ = x[DuplicateFieldAndMethod-33]
+	_ = x[DuplicateMethod-34]
+	_ = x[InvalidBlank-35]
+	_ = x[InvalidIota-36]
+	_ = x[MissingInitBody-37]
+	_ = x[InvalidInitSig-38]
+	_ = x[InvalidInitDecl-39]
+	_ = x[InvalidMainDecl-40]
+	_ = x[TooManyValues-41]
+	_ = x[NotAnExpr-42]
+	_ = x[TruncatedFloat-43]
+	_ = x[NumericOverflow-44]
+	_ = x[UndefinedOp-45]
+	_ = x[MismatchedTypes-46]
+	_ = x[DivByZero-47]
+	_ = x[NonNumericIncDec-48]
+	_ = x[UnaddressableOperand-49]
+	_ = x[InvalidIndirection-50]
+	_ = x[NonIndexableOperand-51]
+	_ = x[InvalidIndex-52]
+	_ = x[SwappedSliceIndices-53]
+	_ = x[NonSliceableOperand-54]
+	_ = x[InvalidSliceExpr-55]
+	_ = x[InvalidShiftCount-56]
+	_ = x[InvalidShiftOperand-57]
+	_ = x[InvalidReceive-58]
+	_ = x[InvalidSend-59]
+	_ = x[DuplicateLitKey-60]
+	_ = x[MissingLitKey-61]
+	_ = x[InvalidLitIndex-62]
+	_ = x[OversizeArrayLit-63]
+	_ = x[MixedStructLit-64]
+	_ = x[InvalidStructLit-65]
+	_ = x[MissingLitField-66]
+	_ = x[DuplicateLitField-67]
+	_ = x[UnexportedLitField-68]
+	_ = x[InvalidLitField-69]
+	_ = x[UntypedLit-70]
+	_ = x[InvalidLit-71]
+	_ = x[AmbiguousSelector-72]
+	_ = x[UndeclaredImportedName-73]
+	_ = x[UnexportedName-74]
+	_ = x[UndeclaredName-75]
+	_ = x[MissingFieldOrMethod-76]
+	_ = x[BadDotDotDotSyntax-77]
+	_ = x[NonVariadicDotDotDot-78]
+	_ = x[MisplacedDotDotDot-79]
+	_ = x[InvalidDotDotDotOperand-80]
+	_ = x[InvalidDotDotDot-81]
+	_ = x[UncalledBuiltin-82]
+	_ = x[InvalidAppend-83]
+	_ = x[InvalidCap-84]
+	_ = x[InvalidClose-85]
+	_ = x[InvalidCopy-86]
+	_ = x[InvalidComplex-87]
+	_ = x[InvalidDelete-88]
+	_ = x[InvalidImag-89]
+	_ = x[InvalidLen-90]
+	_ = x[SwappedMakeArgs-91]
+	_ = x[InvalidMake-92]
+	_ = x[InvalidReal-93]
+	_ = x[InvalidAssert-94]
+	_ = x[ImpossibleAssert-95]
+	_ = x[InvalidConversion-96]
+	_ = x[InvalidUntypedConversion-97]
+	_ = x[BadOffsetofSyntax-98]
+	_ = x[InvalidOffsetof-99]
+	_ = x[UnusedExpr-100]
+	_ = x[UnusedVar-101]
+	_ = x[MissingReturn-102]
+	_ = x[WrongResultCount-103]
+	_ = x[OutOfScopeResult-104]
+	_ = x[InvalidCond-105]
+	_ = x[InvalidPostDecl-106]
+	_ = x[InvalidChanRange-107]
+	_ = x[InvalidIterVar-108]
+	_ = x[InvalidRangeExpr-109]
+	_ = x[MisplacedBreak-110]
+	_ = x[MisplacedContinue-111]
+	_ = x[MisplacedFallthrough-112]
+	_ = x[DuplicateCase-113]
+	_ = x[DuplicateDefault-114]
+	_ = x[BadTypeKeyword-115]
+	_ = x[InvalidTypeSwitch-116]
+	_ = x[InvalidExprSwitch-117]
+	_ = x[InvalidSelectCase-118]
+	_ = x[UndeclaredLabel-119]
+	_ = x[DuplicateLabel-120]
+	_ = x[MisplacedLabel-121]
+	_ = x[UnusedLabel-122]
+	_ = x[JumpOverDecl-123]
+	_ = x[JumpIntoBlock-124]
+	_ = x[InvalidMethodExpr-125]
+	_ = x[WrongArgCount-126]
+	_ = x[InvalidCall-127]
+	_ = x[UnusedResults-128]
+	_ = x[InvalidDefer-129]
+	_ = x[InvalidGo-130]
+	_ = x[BadDecl-131]
+	_ = x[RepeatedDecl-132]
+	_ = x[InvalidUnsafeAdd-133]
+	_ = x[InvalidUnsafeSlice-134]
+	_ = x[UnsupportedFeature-135]
+	_ = x[NotAGenericType-136]
+	_ = x[WrongTypeArgCount-137]
+	_ = x[CannotInferTypeArgs-138]
+	_ = x[InvalidTypeArg-139]
+	_ = x[InvalidInstanceCycle-140]
+	_ = x[InvalidUnion-141]
+	_ = x[MisplacedConstraintIface-142]
+	_ = x[InvalidMethodTypeParams-143]
+	_ = x[MisplacedTypeParam-144]
+	_ = x[InvalidUnsafeSliceData-145]
+	_ = x[InvalidUnsafeString-146]
+}
+
+const (
+	_ErrorCode_name_0 = "InvalidSyntaxTree"
+	_ErrorCode_name_1 = "TestBlankPkgNameMismatchedPkgNameInvalidPkgUseBadImportPathBrokenImportImportCRenamedUnusedImportInvalidInitCycleDuplicateDeclInvalidDeclCycleInvalidTypeCycleInvalidConstInitInvalidConstValInvalidConstTypeUntypedNilUseWrongAssignCountUnassignableOperandNoNewVarMultiValAssignOpInvalidIfaceAssignInvalidChanAssignIncompatibleAssignUnaddressableFieldAssignNotATypeInvalidArrayLenBlankIfaceMethodIncomparableMapKeyInvalidIfaceEmbedInvalidPtrEmbedBadRecvInvalidRecvDuplicateFieldAndMethodDuplicateMethodInvalidBlankInvalidIotaMissingInitBodyInvalidInitSigInvalidInitDeclInvalidMainDeclTooManyValuesNotAnExprTruncatedFloatNumericOverflowUndefinedOpMismatchedTypesDivByZeroNonNumericIncDecUnaddressableOperandInvalidIndirectionNonIndexableOperandInvalidIndexSwappedSliceIndicesNonSliceableOperandInvalidSliceExprInvalidShiftCountInvalidShiftOperandInvalidReceiveInvalidSendDuplicateLitKeyMissingLitKeyInvalidLitIndexOversizeArrayLitMixedStructLitInvalidStructLitMissingLitFieldDuplicateLitFieldUnexportedLitFieldInvalidLitFieldUntypedLitInvalidLitAmbiguousSelectorUndeclaredImportedNameUnexportedNameUndeclaredNameMissingFieldOrMethodBadDotDotDotSyntaxNonVariadicDotDotDotMisplacedDotDotDotInvalidDotDotDotOperandInvalidDotDotDotUncalledBuiltinInvalidAppendInvalidCapInvalidCloseInvalidCopyInvalidComplexInvalidDeleteInvalidImagInvalidLenSwappedMakeArgsInvalidMakeInvalidRealInvalidAssertImpossibleAssertInvalidConversionInvalidUntypedConversionBadOffsetofSyntaxInvalidOffsetofUnusedExprUnusedVarMissingReturnWrongResultCountOutOfScopeResultInvalidCondInvalidPostDeclInvalidChanRangeInvalidIterVarInvalidRangeExprMisplacedBreakMisplacedContinueMisplacedFallthroughDuplicateCaseDuplicateDefaultBadTypeKeywordInvalidTypeSwitchInvalidExprSwitchInvalidSelectCaseUndeclaredLabelDuplicateLabelMisplacedLabelUnusedLabelJumpOverDeclJumpIntoBlockInvalidMethodExprWrongArgCountInvalidCallUnusedResultsInvalidDeferInvalidGoBadDeclRepeatedDeclInvalidUnsafeAddInvalidUnsafeSliceUnsupportedFeatureNotAGenericTypeWrongTypeArgCountCannotInferTypeArgsInvalidTypeArgInvalidInstanceCycleInvalidUnionMisplacedConstraintIfaceInvalidMethodTypeParamsMisplacedTypeParamInvalidUnsafeSliceDataInvalidUnsafeString"
+)
+
+var (
+	_ErrorCode_index_1 = [...]uint16{0, 4, 16, 33, 46, 59, 71, 85, 97, 113, 126, 142, 158, 174, 189, 205, 218, 234, 253, 261, 277, 295, 312, 330, 354, 362, 377, 393, 411, 428, 443, 450, 461, 484, 499, 511, 522, 537, 551, 566, 581, 594, 603, 617, 632, 643, 658, 667, 683, 703, 721, 740, 752, 771, 790, 806, 823, 842, 856, 867, 882, 895, 910, 926, 940, 956, 971, 988, 1006, 1021, 1031, 1041, 1058, 1080, 1094, 1108, 1128, 1146, 1166, 1184, 1207, 1223, 1238, 1251, 1261, 1273, 1284, 1298, 1311, 1322, 1332, 1347, 1358, 1369, 1382, 1398, 1415, 1439, 1456, 1471, 1481, 1490, 1503, 1519, 1535, 1546, 1561, 1577, 1591, 1607, 1621, 1638, 1658, 1671, 1687, 1701, 1718, 1735, 1752, 1767, 1781, 1795, 1806, 1818, 1831, 1848, 1861, 1872, 1885, 1897, 1906, 1913, 1925, 1941, 1959, 1977, 1992, 2009, 2028, 2042, 2062, 2074, 2098, 2121, 2139, 2161, 2180}
+)
+
+func (i ErrorCode) String() string {
+	switch {
+	case i == -1:
+		return _ErrorCode_name_0
+	case 1 <= i && i <= 146:
+		i -= 1
+		return _ErrorCode_name_1[_ErrorCode_index_1[i]:_ErrorCode_index_1[i+1]]
+	default:
+		return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")"
+	}
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go
new file mode 100644
index 000000000..b64f714eb
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go
@@ -0,0 +1,46 @@
+// Copyright 2024 The Go 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 typesinternal
+
+import (
+	"go/ast"
+	"go/types"
+	"strconv"
+)
+
+// FileQualifier returns a [types.Qualifier] function that qualifies
+// imported symbols appropriately based on the import environment of a given
+// file.
+// If the same package is imported multiple times, the last appearance is
+// recorded.
+func FileQualifier(f *ast.File, pkg *types.Package) types.Qualifier {
+	// Construct mapping of import paths to their defined names.
+	// It is only necessary to look at renaming imports.
+	imports := make(map[string]string)
+	for _, imp := range f.Imports {
+		if imp.Name != nil && imp.Name.Name != "_" {
+			path, _ := strconv.Unquote(imp.Path.Value)
+			imports[path] = imp.Name.Name
+		}
+	}
+
+	// Define qualifier to replace full package paths with names of the imports.
+	return func(p *types.Package) string {
+		if p == nil || p == pkg {
+			return ""
+		}
+
+		if name, ok := imports[p.Path()]; ok {
+			if name == "." {
+				return ""
+			} else {
+				return name
+			}
+		}
+
+		// If there is no local renaming, fall back to the package name.
+		return p.Name()
+	}
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/recv.go b/vendor/golang.org/x/tools/internal/typesinternal/recv.go
new file mode 100644
index 000000000..8352ea761
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/recv.go
@@ -0,0 +1,44 @@
+// Copyright 2024 The Go 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 typesinternal
+
+import (
+	"go/types"
+)
+
+// ReceiverNamed returns the named type (if any) associated with the
+// type of recv, which may be of the form N or *N, or aliases thereof.
+// It also reports whether a Pointer was present.
+//
+// The named result may be nil if recv is from a method on an
+// anonymous interface or struct types or in ill-typed code.
+func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) {
+	t := recv.Type()
+	if ptr, ok := types.Unalias(t).(*types.Pointer); ok {
+		isPtr = true
+		t = ptr.Elem()
+	}
+	named, _ = types.Unalias(t).(*types.Named)
+	return
+}
+
+// Unpointer returns T given *T or an alias thereof.
+// For all other types it is the identity function.
+// It does not look at underlying types.
+// The result may be an alias.
+//
+// Use this function to strip off the optional pointer on a receiver
+// in a field or method selection, without losing the named type
+// (which is needed to compute the method set).
+//
+// See also [typeparams.MustDeref], which removes one level of
+// indirection from the type, regardless of named types (analogous to
+// a LOAD instruction).
+func Unpointer(t types.Type) types.Type {
+	if ptr, ok := types.Unalias(t).(*types.Pointer); ok {
+		return ptr.Elem()
+	}
+	return t
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/toonew.go b/vendor/golang.org/x/tools/internal/typesinternal/toonew.go
new file mode 100644
index 000000000..cc86487ea
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/toonew.go
@@ -0,0 +1,89 @@
+// Copyright 2024 The Go 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 typesinternal
+
+import (
+	"go/types"
+
+	"golang.org/x/tools/internal/stdlib"
+	"golang.org/x/tools/internal/versions"
+)
+
+// TooNewStdSymbols computes the set of package-level symbols
+// exported by pkg that are not available at the specified version.
+// The result maps each symbol to its minimum version.
+//
+// The pkg is allowed to contain type errors.
+func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]string {
+	disallowed := make(map[types.Object]string)
+
+	// Pass 1: package-level symbols.
+	symbols := stdlib.PackageSymbols[pkg.Path()]
+	for _, sym := range symbols {
+		symver := sym.Version.String()
+		if versions.Before(version, symver) {
+			switch sym.Kind {
+			case stdlib.Func, stdlib.Var, stdlib.Const, stdlib.Type:
+				disallowed[pkg.Scope().Lookup(sym.Name)] = symver
+			}
+		}
+	}
+
+	// Pass 2: fields and methods.
+	//
+	// We allow fields and methods if their associated type is
+	// disallowed, as otherwise we would report false positives
+	// for compatibility shims. Consider:
+	//
+	//   //go:build go1.22
+	//   type T struct { F std.Real } // correct new API
+	//
+	//   //go:build !go1.22
+	//   type T struct { F fake } // shim
+	//   type fake struct { ... }
+	//   func (fake) M () {}
+	//
+	// These alternative declarations of T use either the std.Real
+	// type, introduced in go1.22, or a fake type, for the field
+	// F. (The fakery could be arbitrarily deep, involving more
+	// nested fields and methods than are shown here.) Clients
+	// that use the compatibility shim T will compile with any
+	// version of go, whether older or newer than go1.22, but only
+	// the newer version will use the std.Real implementation.
+	//
+	// Now consider a reference to method M in new(T).F.M() in a
+	// module that requires a minimum of go1.21. The analysis may
+	// occur using a version of Go higher than 1.21, selecting the
+	// first version of T, so the method M is Real.M. This would
+	// spuriously cause the analyzer to report a reference to a
+	// too-new symbol even though this expression compiles just
+	// fine (with the fake implementation) using go1.21.
+	for _, sym := range symbols {
+		symVersion := sym.Version.String()
+		if !versions.Before(version, symVersion) {
+			continue // allowed
+		}
+
+		var obj types.Object
+		switch sym.Kind {
+		case stdlib.Field:
+			typename, name := sym.SplitField()
+			if t := pkg.Scope().Lookup(typename); t != nil && disallowed[t] == "" {
+				obj, _, _ = types.LookupFieldOrMethod(t.Type(), false, pkg, name)
+			}
+
+		case stdlib.Method:
+			ptr, recvname, name := sym.SplitMethod()
+			if t := pkg.Scope().Lookup(recvname); t != nil && disallowed[t] == "" {
+				obj, _, _ = types.LookupFieldOrMethod(t.Type(), ptr, pkg, name)
+			}
+		}
+		if obj != nil {
+			disallowed[obj] = symVersion
+		}
+	}
+
+	return disallowed
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go
new file mode 100644
index 000000000..cc244689e
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go
@@ -0,0 +1,144 @@
+// Copyright 2020 The Go 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 typesinternal provides access to internal go/types APIs that are not
+// yet exported.
+package typesinternal
+
+import (
+	"go/ast"
+	"go/token"
+	"go/types"
+	"reflect"
+	"unsafe"
+
+	"golang.org/x/tools/internal/aliases"
+)
+
+func SetUsesCgo(conf *types.Config) bool {
+	v := reflect.ValueOf(conf).Elem()
+
+	f := v.FieldByName("go115UsesCgo")
+	if !f.IsValid() {
+		f = v.FieldByName("UsesCgo")
+		if !f.IsValid() {
+			return false
+		}
+	}
+
+	addr := unsafe.Pointer(f.UnsafeAddr())
+	*(*bool)(addr) = true
+
+	return true
+}
+
+// ErrorCodeStartEnd extracts additional information from types.Error values
+// generated by Go version 1.16 and later: the error code, start position, and
+// end position. If all positions are valid, start <= err.Pos <= end.
+//
+// If the data could not be read, the final result parameter will be false.
+//
+// TODO(adonovan): eliminate start/end when proposal #71803 is accepted.
+func ErrorCodeStartEnd(err types.Error) (code ErrorCode, start, end token.Pos, ok bool) {
+	var data [3]int
+	// By coincidence all of these fields are ints, which simplifies things.
+	v := reflect.ValueOf(err)
+	for i, name := range []string{"go116code", "go116start", "go116end"} {
+		f := v.FieldByName(name)
+		if !f.IsValid() {
+			return 0, 0, 0, false
+		}
+		data[i] = int(f.Int())
+	}
+	return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true
+}
+
+// NameRelativeTo returns a types.Qualifier that qualifies members of
+// all packages other than pkg, using only the package name.
+// (By contrast, [types.RelativeTo] uses the complete package path,
+// which is often excessive.)
+//
+// If pkg is nil, it is equivalent to [*types.Package.Name].
+func NameRelativeTo(pkg *types.Package) types.Qualifier {
+	return func(other *types.Package) string {
+		if pkg != nil && pkg == other {
+			return "" // same package; unqualified
+		}
+		return other.Name()
+	}
+}
+
+// A NamedOrAlias is a [types.Type] that is named (as
+// defined by the spec) and capable of bearing type parameters: it
+// abstracts aliases ([types.Alias]) and defined types
+// ([types.Named]).
+//
+// Every type declared by an explicit "type" declaration is a
+// NamedOrAlias. (Built-in type symbols may additionally
+// have type [types.Basic], which is not a NamedOrAlias,
+// though the spec regards them as "named".)
+//
+// NamedOrAlias cannot expose the Origin method, because
+// [types.Alias.Origin] and [types.Named.Origin] have different
+// (covariant) result types; use [Origin] instead.
+type NamedOrAlias interface {
+	types.Type
+	Obj() *types.TypeName
+	// TODO(hxjiang): add method TypeArgs() *types.TypeList after stop supporting go1.22.
+}
+
+// TypeParams is a light shim around t.TypeParams().
+// (go/types.Alias).TypeParams requires >= 1.23.
+func TypeParams(t NamedOrAlias) *types.TypeParamList {
+	switch t := t.(type) {
+	case *types.Alias:
+		return aliases.TypeParams(t)
+	case *types.Named:
+		return t.TypeParams()
+	}
+	return nil
+}
+
+// TypeArgs is a light shim around t.TypeArgs().
+// (go/types.Alias).TypeArgs requires >= 1.23.
+func TypeArgs(t NamedOrAlias) *types.TypeList {
+	switch t := t.(type) {
+	case *types.Alias:
+		return aliases.TypeArgs(t)
+	case *types.Named:
+		return t.TypeArgs()
+	}
+	return nil
+}
+
+// Origin returns the generic type of the Named or Alias type t if it
+// is instantiated, otherwise it returns t.
+func Origin(t NamedOrAlias) NamedOrAlias {
+	switch t := t.(type) {
+	case *types.Alias:
+		return aliases.Origin(t)
+	case *types.Named:
+		return t.Origin()
+	}
+	return t
+}
+
+// IsPackageLevel reports whether obj is a package-level symbol.
+func IsPackageLevel(obj types.Object) bool {
+	return obj.Pkg() != nil && obj.Parent() == obj.Pkg().Scope()
+}
+
+// NewTypesInfo returns a *types.Info with all maps populated.
+func NewTypesInfo() *types.Info {
+	return &types.Info{
+		Types:        map[ast.Expr]types.TypeAndValue{},
+		Instances:    map[*ast.Ident]types.Instance{},
+		Defs:         map[*ast.Ident]types.Object{},
+		Uses:         map[*ast.Ident]types.Object{},
+		Implicits:    map[ast.Node]types.Object{},
+		Selections:   map[*ast.SelectorExpr]*types.Selection{},
+		Scopes:       map[ast.Node]*types.Scope{},
+		FileVersions: map[*ast.File]string{},
+	}
+}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/varkind.go b/vendor/golang.org/x/tools/internal/typesinternal/varkind.go
new file mode 100644
index 000000000..e5da04951
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/varkind.go
@@ -0,0 +1,40 @@
+// Copyright 2024 The Go 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 typesinternal
+
+// TODO(adonovan): when CL 645115 lands, define the go1.25 version of
+// this API that actually does something.
+
+import "go/types"
+
+type VarKind uint8
+
+const (
+	_          VarKind = iota // (not meaningful)
+	PackageVar                // a package-level variable
+	LocalVar                  // a local variable
+	RecvVar                   // a method receiver variable
+	ParamVar                  // a function parameter variable
+	ResultVar                 // a function result variable
+	FieldVar                  // a struct field
+)
+
+func (kind VarKind) String() string {
+	return [...]string{
+		0:          "VarKind(0)",
+		PackageVar: "PackageVar",
+		LocalVar:   "LocalVar",
+		RecvVar:    "RecvVar",
+		ParamVar:   "ParamVar",
+		ResultVar:  "ResultVar",
+		FieldVar:   "FieldVar",
+	}[kind]
+}
+
+// GetVarKind returns an invalid VarKind.
+func GetVarKind(v *types.Var) VarKind { return 0 }
+
+// SetVarKind has no effect.
+func SetVarKind(v *types.Var, kind VarKind) {}
diff --git a/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go
new file mode 100644
index 000000000..d272949c1
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go
@@ -0,0 +1,392 @@
+// Copyright 2024 The Go 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 typesinternal
+
+import (
+	"fmt"
+	"go/ast"
+	"go/token"
+	"go/types"
+	"strings"
+)
+
+// ZeroString returns the string representation of the zero value for any type t.
+// The boolean result indicates whether the type is or contains an invalid type
+// or a non-basic (constraint) interface type.
+//
+// Even for invalid input types, ZeroString may return a partially correct
+// string representation. The caller should use the returned isValid boolean
+// to determine the validity of the expression.
+//
+// When assigning to a wider type (such as 'any'), it's the caller's
+// responsibility to handle any necessary type conversions.
+//
+// This string can be used on the right-hand side of an assignment where the
+// left-hand side has that explicit type.
+// References to named types are qualified by an appropriate (optional)
+// qualifier function.
+// Exception: This does not apply to tuples. Their string representation is
+// informational only and cannot be used in an assignment.
+//
+// See [ZeroExpr] for a variant that returns an [ast.Expr].
+func ZeroString(t types.Type, qual types.Qualifier) (_ string, isValid bool) {
+	switch t := t.(type) {
+	case *types.Basic:
+		switch {
+		case t.Info()&types.IsBoolean != 0:
+			return "false", true
+		case t.Info()&types.IsNumeric != 0:
+			return "0", true
+		case t.Info()&types.IsString != 0:
+			return `""`, true
+		case t.Kind() == types.UnsafePointer:
+			fallthrough
+		case t.Kind() == types.UntypedNil:
+			return "nil", true
+		case t.Kind() == types.Invalid:
+			return "invalid", false
+		default:
+			panic(fmt.Sprintf("ZeroString for unexpected type %v", t))
+		}
+
+	case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature:
+		return "nil", true
+
+	case *types.Interface:
+		if !t.IsMethodSet() {
+			return "invalid", false
+		}
+		return "nil", true
+
+	case *types.Named:
+		switch under := t.Underlying().(type) {
+		case *types.Struct, *types.Array:
+			return types.TypeString(t, qual) + "{}", true
+		default:
+			return ZeroString(under, qual)
+		}
+
+	case *types.Alias:
+		switch t.Underlying().(type) {
+		case *types.Struct, *types.Array:
+			return types.TypeString(t, qual) + "{}", true
+		default:
+			// A type parameter can have alias but alias type's underlying type
+			// can never be a type parameter.
+			// Use types.Unalias to preserve the info of type parameter instead
+			// of call Underlying() going right through and get the underlying
+			// type of the type parameter which is always an interface.
+			return ZeroString(types.Unalias(t), qual)
+		}
+
+	case *types.Array, *types.Struct:
+		return types.TypeString(t, qual) + "{}", true
+
+	case *types.TypeParam:
+		// Assumes func new is not shadowed.
+		return "*new(" + types.TypeString(t, qual) + ")", true
+
+	case *types.Tuple:
+		// Tuples are not normal values.
+		// We are currently format as "(t[0], ..., t[n])". Could be something else.
+		isValid := true
+		components := make([]string, t.Len())
+		for i := 0; i < t.Len(); i++ {
+			comp, ok := ZeroString(t.At(i).Type(), qual)
+
+			components[i] = comp
+			isValid = isValid && ok
+		}
+		return "(" + strings.Join(components, ", ") + ")", isValid
+
+	case *types.Union:
+		// Variables of these types cannot be created, so it makes
+		// no sense to ask for their zero value.
+		panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+	default:
+		panic(t) // unreachable.
+	}
+}
+
+// ZeroExpr returns the ast.Expr representation of the zero value for any type t.
+// The boolean result indicates whether the type is or contains an invalid type
+// or a non-basic (constraint) interface type.
+//
+// Even for invalid input types, ZeroExpr may return a partially correct ast.Expr
+// representation. The caller should use the returned isValid boolean to determine
+// the validity of the expression.
+//
+// This function is designed for types suitable for variables and should not be
+// used with Tuple or Union types.References to named types are qualified by an
+// appropriate (optional) qualifier function.
+//
+// See [ZeroString] for a variant that returns a string.
+func ZeroExpr(t types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) {
+	switch t := t.(type) {
+	case *types.Basic:
+		switch {
+		case t.Info()&types.IsBoolean != 0:
+			return &ast.Ident{Name: "false"}, true
+		case t.Info()&types.IsNumeric != 0:
+			return &ast.BasicLit{Kind: token.INT, Value: "0"}, true
+		case t.Info()&types.IsString != 0:
+			return &ast.BasicLit{Kind: token.STRING, Value: `""`}, true
+		case t.Kind() == types.UnsafePointer:
+			fallthrough
+		case t.Kind() == types.UntypedNil:
+			return ast.NewIdent("nil"), true
+		case t.Kind() == types.Invalid:
+			return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false
+		default:
+			panic(fmt.Sprintf("ZeroExpr for unexpected type %v", t))
+		}
+
+	case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature:
+		return ast.NewIdent("nil"), true
+
+	case *types.Interface:
+		if !t.IsMethodSet() {
+			return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false
+		}
+		return ast.NewIdent("nil"), true
+
+	case *types.Named:
+		switch under := t.Underlying().(type) {
+		case *types.Struct, *types.Array:
+			return &ast.CompositeLit{
+				Type: TypeExpr(t, qual),
+			}, true
+		default:
+			return ZeroExpr(under, qual)
+		}
+
+	case *types.Alias:
+		switch t.Underlying().(type) {
+		case *types.Struct, *types.Array:
+			return &ast.CompositeLit{
+				Type: TypeExpr(t, qual),
+			}, true
+		default:
+			return ZeroExpr(types.Unalias(t), qual)
+		}
+
+	case *types.Array, *types.Struct:
+		return &ast.CompositeLit{
+			Type: TypeExpr(t, qual),
+		}, true
+
+	case *types.TypeParam:
+		return &ast.StarExpr{ // *new(T)
+			X: &ast.CallExpr{
+				// Assumes func new is not shadowed.
+				Fun: ast.NewIdent("new"),
+				Args: []ast.Expr{
+					ast.NewIdent(t.Obj().Name()),
+				},
+			},
+		}, true
+
+	case *types.Tuple:
+		// Unlike ZeroString, there is no ast.Expr can express tuple by
+		// "(t[0], ..., t[n])".
+		panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+	case *types.Union:
+		// Variables of these types cannot be created, so it makes
+		// no sense to ask for their zero value.
+		panic(fmt.Sprintf("invalid type for a variable: %v", t))
+
+	default:
+		panic(t) // unreachable.
+	}
+}
+
+// IsZeroExpr uses simple syntactic heuristics to report whether expr
+// is a obvious zero value, such as 0, "", nil, or false.
+// It cannot do better without type information.
+func IsZeroExpr(expr ast.Expr) bool {
+	switch e := expr.(type) {
+	case *ast.BasicLit:
+		return e.Value == "0" || e.Value == `""`
+	case *ast.Ident:
+		return e.Name == "nil" || e.Name == "false"
+	default:
+		return false
+	}
+}
+
+// TypeExpr returns syntax for the specified type. References to named types
+// are qualified by an appropriate (optional) qualifier function.
+// It may panic for types such as Tuple or Union.
+func TypeExpr(t types.Type, qual types.Qualifier) ast.Expr {
+	switch t := t.(type) {
+	case *types.Basic:
+		switch t.Kind() {
+		case types.UnsafePointer:
+			return &ast.SelectorExpr{X: ast.NewIdent(qual(types.NewPackage("unsafe", "unsafe"))), Sel: ast.NewIdent("Pointer")}
+		default:
+			return ast.NewIdent(t.Name())
+		}
+
+	case *types.Pointer:
+		return &ast.UnaryExpr{
+			Op: token.MUL,
+			X:  TypeExpr(t.Elem(), qual),
+		}
+
+	case *types.Array:
+		return &ast.ArrayType{
+			Len: &ast.BasicLit{
+				Kind:  token.INT,
+				Value: fmt.Sprintf("%d", t.Len()),
+			},
+			Elt: TypeExpr(t.Elem(), qual),
+		}
+
+	case *types.Slice:
+		return &ast.ArrayType{
+			Elt: TypeExpr(t.Elem(), qual),
+		}
+
+	case *types.Map:
+		return &ast.MapType{
+			Key:   TypeExpr(t.Key(), qual),
+			Value: TypeExpr(t.Elem(), qual),
+		}
+
+	case *types.Chan:
+		dir := ast.ChanDir(t.Dir())
+		if t.Dir() == types.SendRecv {
+			dir = ast.SEND | ast.RECV
+		}
+		return &ast.ChanType{
+			Dir:   dir,
+			Value: TypeExpr(t.Elem(), qual),
+		}
+
+	case *types.Signature:
+		var params []*ast.Field
+		for i := 0; i < t.Params().Len(); i++ {
+			params = append(params, &ast.Field{
+				Type: TypeExpr(t.Params().At(i).Type(), qual),
+				Names: []*ast.Ident{
+					{
+						Name: t.Params().At(i).Name(),
+					},
+				},
+			})
+		}
+		if t.Variadic() {
+			last := params[len(params)-1]
+			last.Type = &ast.Ellipsis{Elt: last.Type.(*ast.ArrayType).Elt}
+		}
+		var returns []*ast.Field
+		for i := 0; i < t.Results().Len(); i++ {
+			returns = append(returns, &ast.Field{
+				Type: TypeExpr(t.Results().At(i).Type(), qual),
+			})
+		}
+		return &ast.FuncType{
+			Params: &ast.FieldList{
+				List: params,
+			},
+			Results: &ast.FieldList{
+				List: returns,
+			},
+		}
+
+	case *types.TypeParam:
+		pkgName := qual(t.Obj().Pkg())
+		if pkgName == "" || t.Obj().Pkg() == nil {
+			return ast.NewIdent(t.Obj().Name())
+		}
+		return &ast.SelectorExpr{
+			X:   ast.NewIdent(pkgName),
+			Sel: ast.NewIdent(t.Obj().Name()),
+		}
+
+	// types.TypeParam also implements interface NamedOrAlias. To differentiate,
+	// case TypeParam need to be present before case NamedOrAlias.
+	// TODO(hxjiang): remove this comment once TypeArgs() is added to interface
+	// NamedOrAlias.
+	case NamedOrAlias:
+		var expr ast.Expr = ast.NewIdent(t.Obj().Name())
+		if pkgName := qual(t.Obj().Pkg()); pkgName != "." && pkgName != "" {
+			expr = &ast.SelectorExpr{
+				X:   ast.NewIdent(pkgName),
+				Sel: expr.(*ast.Ident),
+			}
+		}
+
+		// TODO(hxjiang): call t.TypeArgs after adding method TypeArgs() to
+		// typesinternal.NamedOrAlias.
+		if hasTypeArgs, ok := t.(interface{ TypeArgs() *types.TypeList }); ok {
+			if typeArgs := hasTypeArgs.TypeArgs(); typeArgs != nil && typeArgs.Len() > 0 {
+				var indices []ast.Expr
+				for i := range typeArgs.Len() {
+					indices = append(indices, TypeExpr(typeArgs.At(i), qual))
+				}
+				expr = &ast.IndexListExpr{
+					X:       expr,
+					Indices: indices,
+				}
+			}
+		}
+
+		return expr
+
+	case *types.Struct:
+		return ast.NewIdent(t.String())
+
+	case *types.Interface:
+		return ast.NewIdent(t.String())
+
+	case *types.Union:
+		if t.Len() == 0 {
+			panic("Union type should have at least one term")
+		}
+		// Same as go/ast, the return expression will put last term in the
+		// Y field at topmost level of BinaryExpr.
+		// For union of type "float32 | float64 | int64", the structure looks
+		// similar to:
+		// {
+		// 	X: {
+		// 		X: float32,
+		// 		Op: |
+		// 		Y: float64,
+		// 	}
+		// 	Op: |,
+		// 	Y: int64,
+		// }
+		var union ast.Expr
+		for i := range t.Len() {
+			term := t.Term(i)
+			termExpr := TypeExpr(term.Type(), qual)
+			if term.Tilde() {
+				termExpr = &ast.UnaryExpr{
+					Op: token.TILDE,
+					X:  termExpr,
+				}
+			}
+			if i == 0 {
+				union = termExpr
+			} else {
+				union = &ast.BinaryExpr{
+					X:  union,
+					Op: token.OR,
+					Y:  termExpr,
+				}
+			}
+		}
+		return union
+
+	case *types.Tuple:
+		panic("invalid input type types.Tuple")
+
+	default:
+		panic("unreachable")
+	}
+}
diff --git a/vendor/golang.org/x/tools/internal/versions/features.go b/vendor/golang.org/x/tools/internal/versions/features.go
new file mode 100644
index 000000000..b53f17861
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/versions/features.go
@@ -0,0 +1,43 @@
+// Copyright 2023 The Go 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 versions
+
+// This file contains predicates for working with file versions to
+// decide when a tool should consider a language feature enabled.
+
+// GoVersions that features in x/tools can be gated to.
+const (
+	Go1_18 = "go1.18"
+	Go1_19 = "go1.19"
+	Go1_20 = "go1.20"
+	Go1_21 = "go1.21"
+	Go1_22 = "go1.22"
+)
+
+// Future is an invalid unknown Go version sometime in the future.
+// Do not use directly with Compare.
+const Future = ""
+
+// AtLeast reports whether the file version v comes after a Go release.
+//
+// Use this predicate to enable a behavior once a certain Go release
+// has happened (and stays enabled in the future).
+func AtLeast(v, release string) bool {
+	if v == Future {
+		return true // an unknown future version is always after y.
+	}
+	return Compare(Lang(v), Lang(release)) >= 0
+}
+
+// Before reports whether the file version v is strictly before a Go release.
+//
+// Use this predicate to disable a behavior once a certain Go release
+// has happened (and stays enabled in the future).
+func Before(v, release string) bool {
+	if v == Future {
+		return false // an unknown future version happens after y.
+	}
+	return Compare(Lang(v), Lang(release)) < 0
+}
diff --git a/vendor/golang.org/x/tools/internal/versions/gover.go b/vendor/golang.org/x/tools/internal/versions/gover.go
new file mode 100644
index 000000000..bbabcd22e
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/versions/gover.go
@@ -0,0 +1,172 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This is a fork of internal/gover for use by x/tools until
+// go1.21 and earlier are no longer supported by x/tools.
+
+package versions
+
+import "strings"
+
+// A gover is a parsed Go gover: major[.Minor[.Patch]][kind[pre]]
+// The numbers are the original decimal strings to avoid integer overflows
+// and since there is very little actual math. (Probably overflow doesn't matter in practice,
+// but at the time this code was written, there was an existing test that used
+// go1.99999999999, which does not fit in an int on 32-bit platforms.
+// The "big decimal" representation avoids the problem entirely.)
+type gover struct {
+	major string // decimal
+	minor string // decimal or ""
+	patch string // decimal or ""
+	kind  string // "", "alpha", "beta", "rc"
+	pre   string // decimal or ""
+}
+
+// compare returns -1, 0, or +1 depending on whether
+// x < y, x == y, or x > y, interpreted as toolchain versions.
+// The versions x and y must not begin with a "go" prefix: just "1.21" not "go1.21".
+// Malformed versions compare less than well-formed versions and equal to each other.
+// The language version "1.21" compares less than the release candidate and eventual releases "1.21rc1" and "1.21.0".
+func compare(x, y string) int {
+	vx := parse(x)
+	vy := parse(y)
+
+	if c := cmpInt(vx.major, vy.major); c != 0 {
+		return c
+	}
+	if c := cmpInt(vx.minor, vy.minor); c != 0 {
+		return c
+	}
+	if c := cmpInt(vx.patch, vy.patch); c != 0 {
+		return c
+	}
+	if c := strings.Compare(vx.kind, vy.kind); c != 0 { // "" < alpha < beta < rc
+		return c
+	}
+	if c := cmpInt(vx.pre, vy.pre); c != 0 {
+		return c
+	}
+	return 0
+}
+
+// lang returns the Go language version. For example, lang("1.2.3") == "1.2".
+func lang(x string) string {
+	v := parse(x)
+	if v.minor == "" || v.major == "1" && v.minor == "0" {
+		return v.major
+	}
+	return v.major + "." + v.minor
+}
+
+// isValid reports whether the version x is valid.
+func isValid(x string) bool {
+	return parse(x) != gover{}
+}
+
+// parse parses the Go version string x into a version.
+// It returns the zero version if x is malformed.
+func parse(x string) gover {
+	var v gover
+
+	// Parse major version.
+	var ok bool
+	v.major, x, ok = cutInt(x)
+	if !ok {
+		return gover{}
+	}
+	if x == "" {
+		// Interpret "1" as "1.0.0".
+		v.minor = "0"
+		v.patch = "0"
+		return v
+	}
+
+	// Parse . before minor version.
+	if x[0] != '.' {
+		return gover{}
+	}
+
+	// Parse minor version.
+	v.minor, x, ok = cutInt(x[1:])
+	if !ok {
+		return gover{}
+	}
+	if x == "" {
+		// Patch missing is same as "0" for older versions.
+		// Starting in Go 1.21, patch missing is different from explicit .0.
+		if cmpInt(v.minor, "21") < 0 {
+			v.patch = "0"
+		}
+		return v
+	}
+
+	// Parse patch if present.
+	if x[0] == '.' {
+		v.patch, x, ok = cutInt(x[1:])
+		if !ok || x != "" {
+			// Note that we are disallowing prereleases (alpha, beta, rc) for patch releases here (x != "").
+			// Allowing them would be a bit confusing because we already have:
+			//	1.21 < 1.21rc1
+			// But a prerelease of a patch would have the opposite effect:
+			//	1.21.3rc1 < 1.21.3
+			// We've never needed them before, so let's not start now.
+			return gover{}
+		}
+		return v
+	}
+
+	// Parse prerelease.
+	i := 0
+	for i < len(x) && (x[i] < '0' || '9' < x[i]) {
+		if x[i] < 'a' || 'z' < x[i] {
+			return gover{}
+		}
+		i++
+	}
+	if i == 0 {
+		return gover{}
+	}
+	v.kind, x = x[:i], x[i:]
+	if x == "" {
+		return v
+	}
+	v.pre, x, ok = cutInt(x)
+	if !ok || x != "" {
+		return gover{}
+	}
+
+	return v
+}
+
+// cutInt scans the leading decimal number at the start of x to an integer
+// and returns that value and the rest of the string.
+func cutInt(x string) (n, rest string, ok bool) {
+	i := 0
+	for i < len(x) && '0' <= x[i] && x[i] <= '9' {
+		i++
+	}
+	if i == 0 || x[0] == '0' && i != 1 { // no digits or unnecessary leading zero
+		return "", "", false
+	}
+	return x[:i], x[i:], true
+}
+
+// cmpInt returns cmp.Compare(x, y) interpreting x and y as decimal numbers.
+// (Copied from golang.org/x/mod/semver's compareInt.)
+func cmpInt(x, y string) int {
+	if x == y {
+		return 0
+	}
+	if len(x) < len(y) {
+		return -1
+	}
+	if len(x) > len(y) {
+		return +1
+	}
+	if x < y {
+		return -1
+	} else {
+		return +1
+	}
+}
diff --git a/vendor/golang.org/x/tools/internal/versions/types.go b/vendor/golang.org/x/tools/internal/versions/types.go
new file mode 100644
index 000000000..0fc10ce4e
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/versions/types.go
@@ -0,0 +1,33 @@
+// Copyright 2023 The Go 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 versions
+
+import (
+	"go/ast"
+	"go/types"
+)
+
+// FileVersion returns a file's Go version.
+// The reported version is an unknown Future version if a
+// version cannot be determined.
+func FileVersion(info *types.Info, file *ast.File) string {
+	// In tools built with Go >= 1.22, the Go version of a file
+	// follow a cascades of sources:
+	// 1) types.Info.FileVersion, which follows the cascade:
+	//   1.a) file version (ast.File.GoVersion),
+	//   1.b) the package version (types.Config.GoVersion), or
+	// 2) is some unknown Future version.
+	//
+	// File versions require a valid package version to be provided to types
+	// in Config.GoVersion. Config.GoVersion is either from the package's module
+	// or the toolchain (go run). This value should be provided by go/packages
+	// or unitchecker.Config.GoVersion.
+	if v := info.FileVersions[file]; IsValid(v) {
+		return v
+	}
+	// Note: we could instead return runtime.Version() [if valid].
+	// This would act as a max version on what a tool can support.
+	return Future
+}
diff --git a/vendor/golang.org/x/tools/internal/versions/versions.go b/vendor/golang.org/x/tools/internal/versions/versions.go
new file mode 100644
index 000000000..8d1f7453d
--- /dev/null
+++ b/vendor/golang.org/x/tools/internal/versions/versions.go
@@ -0,0 +1,57 @@
+// Copyright 2023 The Go 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 versions
+
+import (
+	"strings"
+)
+
+// Note: If we use build tags to use go/versions when go >=1.22,
+// we run into go.dev/issue/53737. Under some operations users would see an
+// import of "go/versions" even if they would not compile the file.
+// For example, during `go get -u ./...` (go.dev/issue/64490) we do not try to include
+// For this reason, this library just a clone of go/versions for the moment.
+
+// Lang returns the Go language version for version x.
+// If x is not a valid version, Lang returns the empty string.
+// For example:
+//
+//	Lang("go1.21rc2") = "go1.21"
+//	Lang("go1.21.2") = "go1.21"
+//	Lang("go1.21") = "go1.21"
+//	Lang("go1") = "go1"
+//	Lang("bad") = ""
+//	Lang("1.21") = ""
+func Lang(x string) string {
+	v := lang(stripGo(x))
+	if v == "" {
+		return ""
+	}
+	return x[:2+len(v)] // "go"+v without allocation
+}
+
+// Compare returns -1, 0, or +1 depending on whether
+// x < y, x == y, or x > y, interpreted as Go versions.
+// The versions x and y must begin with a "go" prefix: "go1.21" not "1.21".
+// Invalid versions, including the empty string, compare less than
+// valid versions and equal to each other.
+// The language version "go1.21" compares less than the
+// release candidate and eventual releases "go1.21rc1" and "go1.21.0".
+// Custom toolchain suffixes are ignored during comparison:
+// "go1.21.0" and "go1.21.0-bigcorp" are equal.
+func Compare(x, y string) int { return compare(stripGo(x), stripGo(y)) }
+
+// IsValid reports whether the version x is valid.
+func IsValid(x string) bool { return isValid(stripGo(x)) }
+
+// stripGo converts from a "go1.21" version to a "1.21" version.
+// If v does not start with "go", stripGo returns the empty string (a known invalid version).
+func stripGo(v string) string {
+	v, _, _ = strings.Cut(v, "-") // strip -bigcorp suffix.
+	if len(v) < 2 || v[:2] != "go" {
+		return ""
+	}
+	return v[2:]
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/.import-restrictions b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/.import-restrictions
new file mode 100644
index 000000000..7408dd121
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/.import-restrictions
@@ -0,0 +1,5 @@
+inverseRules:
+  # Allow use of this package in all k8s.io packages.
+  - selectorRegexp: k8s[.]io
+    allowedPrefixes:
+      - ''
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go
new file mode 100644
index 000000000..eed3fde63
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go
@@ -0,0 +1,70 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+import (
+	"bytes"
+
+	"k8s.io/apimachinery/pkg/conversion"
+	"k8s.io/apimachinery/pkg/util/json"
+
+	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
+)
+
+func Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {
+	if err := autoConvert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in, out, s); err != nil {
+		return err
+	}
+	if in.Default != nil && *(in.Default) == nil {
+		out.Default = nil
+	}
+	if in.Example != nil && *(in.Example) == nil {
+		out.Example = nil
+	}
+	return nil
+}
+
+var nullLiteral = []byte(`null`)
+
+func Convert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error {
+	raw, err := json.Marshal(*in)
+	if err != nil {
+		return err
+	}
+	if len(raw) == 0 || bytes.Equal(raw, nullLiteral) {
+		// match JSON#UnmarshalJSON treatment of literal nulls
+		out.Raw = nil
+	} else {
+		out.Raw = raw
+	}
+	return nil
+}
+
+func Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {
+	if in != nil {
+		var i interface{}
+		if len(in.Raw) > 0 && !bytes.Equal(in.Raw, nullLiteral) {
+			if err := json.Unmarshal(in.Raw, &i); err != nil {
+				return err
+			}
+		}
+		*out = i
+	} else {
+		out = nil
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/deepcopy.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/deepcopy.go
new file mode 100644
index 000000000..3a2ee6807
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/deepcopy.go
@@ -0,0 +1,278 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+// TODO: Update this after a tag is created for interface fields in DeepCopy
+func (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaProps)
+	*out = *in
+
+	if in.Ref != nil {
+		in, out := &in.Ref, &out.Ref
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(string)
+			**out = **in
+		}
+	}
+
+	if in.Maximum != nil {
+		in, out := &in.Maximum, &out.Maximum
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(float64)
+			**out = **in
+		}
+	}
+
+	if in.Minimum != nil {
+		in, out := &in.Minimum, &out.Minimum
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(float64)
+			**out = **in
+		}
+	}
+
+	if in.MaxLength != nil {
+		in, out := &in.MaxLength, &out.MaxLength
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+
+	if in.MinLength != nil {
+		in, out := &in.MinLength, &out.MinLength
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+	if in.MaxItems != nil {
+		in, out := &in.MaxItems, &out.MaxItems
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+
+	if in.MinItems != nil {
+		in, out := &in.MinItems, &out.MinItems
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+
+	if in.MultipleOf != nil {
+		in, out := &in.MultipleOf, &out.MultipleOf
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(float64)
+			**out = **in
+		}
+	}
+
+	if in.MaxProperties != nil {
+		in, out := &in.MaxProperties, &out.MaxProperties
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+
+	if in.MinProperties != nil {
+		in, out := &in.MinProperties, &out.MinProperties
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(int64)
+			**out = **in
+		}
+	}
+
+	if in.Required != nil {
+		in, out := &in.Required, &out.Required
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(JSONSchemaPropsOrArray)
+			(*in).DeepCopyInto(*out)
+		}
+	}
+
+	if in.AllOf != nil {
+		in, out := &in.AllOf, &out.AllOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+
+	if in.OneOf != nil {
+		in, out := &in.OneOf, &out.OneOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	if in.AnyOf != nil {
+		in, out := &in.AnyOf, &out.AnyOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+
+	if in.Not != nil {
+		in, out := &in.Not, &out.Not
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(JSONSchemaProps)
+			(*in).DeepCopyInto(*out)
+		}
+	}
+
+	if in.Properties != nil {
+		in, out := &in.Properties, &out.Properties
+		*out = make(map[string]JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+	}
+
+	if in.AdditionalProperties != nil {
+		in, out := &in.AdditionalProperties, &out.AdditionalProperties
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(JSONSchemaPropsOrBool)
+			(*in).DeepCopyInto(*out)
+		}
+	}
+
+	if in.PatternProperties != nil {
+		in, out := &in.PatternProperties, &out.PatternProperties
+		*out = make(map[string]JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+	}
+
+	if in.Dependencies != nil {
+		in, out := &in.Dependencies, &out.Dependencies
+		*out = make(JSONSchemaDependencies, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+	}
+
+	if in.AdditionalItems != nil {
+		in, out := &in.AdditionalItems, &out.AdditionalItems
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(JSONSchemaPropsOrBool)
+			(*in).DeepCopyInto(*out)
+		}
+	}
+
+	if in.Definitions != nil {
+		in, out := &in.Definitions, &out.Definitions
+		*out = make(JSONSchemaDefinitions, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+	}
+
+	if in.ExternalDocs != nil {
+		in, out := &in.ExternalDocs, &out.ExternalDocs
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(ExternalDocumentation)
+			(*in).DeepCopyInto(*out)
+		}
+	}
+
+	if in.XPreserveUnknownFields != nil {
+		in, out := &in.XPreserveUnknownFields, &out.XPreserveUnknownFields
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(bool)
+			**out = **in
+		}
+	}
+
+	if in.XListMapKeys != nil {
+		in, out := &in.XListMapKeys, &out.XListMapKeys
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+
+	if in.XListType != nil {
+		in, out := &in.XListType, &out.XListType
+		if *in == nil {
+			*out = nil
+		} else {
+			*out = new(string)
+			**out = **in
+		}
+	}
+
+	if in.XMapType != nil {
+		in, out := &in.XMapType, &out.XMapType
+		*out = new(string)
+		**out = **in
+	}
+
+	if in.XValidations != nil {
+		inValidations, outValidations := &in.XValidations, &out.XValidations
+		*outValidations = make([]ValidationRule, len(*inValidations))
+		for i := range *inValidations {
+			in.XValidations[i].DeepCopyInto(&out.XValidations[i])
+		}
+	}
+
+	return out
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go
new file mode 100644
index 000000000..1a9c2238e
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go
@@ -0,0 +1,82 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+import (
+	"strings"
+
+	"k8s.io/apimachinery/pkg/runtime"
+	utilpointer "k8s.io/utils/pointer"
+)
+
+func addDefaultingFuncs(scheme *runtime.Scheme) error {
+	return RegisterDefaults(scheme)
+}
+
+func SetDefaults_CustomResourceDefinition(obj *CustomResourceDefinition) {
+	SetDefaults_CustomResourceDefinitionSpec(&obj.Spec)
+	if len(obj.Status.StoredVersions) == 0 {
+		for _, v := range obj.Spec.Versions {
+			if v.Storage {
+				obj.Status.StoredVersions = append(obj.Status.StoredVersions, v.Name)
+				break
+			}
+		}
+	}
+}
+
+func SetDefaults_CustomResourceDefinitionSpec(obj *CustomResourceDefinitionSpec) {
+	if len(obj.Scope) == 0 {
+		obj.Scope = NamespaceScoped
+	}
+	if len(obj.Names.Singular) == 0 {
+		obj.Names.Singular = strings.ToLower(obj.Names.Kind)
+	}
+	if len(obj.Names.ListKind) == 0 && len(obj.Names.Kind) > 0 {
+		obj.Names.ListKind = obj.Names.Kind + "List"
+	}
+	// If there is no list of versions, create on using deprecated Version field.
+	if len(obj.Versions) == 0 && len(obj.Version) != 0 {
+		obj.Versions = []CustomResourceDefinitionVersion{{
+			Name:    obj.Version,
+			Storage: true,
+			Served:  true,
+		}}
+	}
+	// For backward compatibility set the version field to the first item in versions list.
+	if len(obj.Version) == 0 && len(obj.Versions) != 0 {
+		obj.Version = obj.Versions[0].Name
+	}
+	if obj.Conversion == nil {
+		obj.Conversion = &CustomResourceConversion{
+			Strategy: NoneConverter,
+		}
+	}
+	if obj.Conversion.Strategy == WebhookConverter && len(obj.Conversion.ConversionReviewVersions) == 0 {
+		obj.Conversion.ConversionReviewVersions = []string{SchemeGroupVersion.Version}
+	}
+	if obj.PreserveUnknownFields == nil {
+		obj.PreserveUnknownFields = utilpointer.BoolPtr(true)
+	}
+}
+
+// SetDefaults_ServiceReference sets defaults for Webhook's ServiceReference
+func SetDefaults_ServiceReference(obj *ServiceReference) {
+	if obj.Port == nil {
+		obj.Port = utilpointer.Int32Ptr(443)
+	}
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/doc.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/doc.go
new file mode 100644
index 000000000..6ddea3e01
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/doc.go
@@ -0,0 +1,26 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// +k8s:deepcopy-gen=package
+// +k8s:protobuf-gen=package
+// +k8s:conversion-gen=k8s.io/apiextensions-apiserver/pkg/apis/apiextensions
+// +k8s:defaulter-gen=TypeMeta
+// +k8s:openapi-gen=true
+// +k8s:prerelease-lifecycle-gen=true
+// +groupName=apiextensions.k8s.io
+
+// Package v1beta1 is the v1beta1 version of the API.
+package v1beta1
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.pb.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.pb.go
new file mode 100644
index 000000000..32e583240
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.pb.go
@@ -0,0 +1,9745 @@
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto
+
+package v1beta1
+
+import (
+	encoding_binary "encoding/binary"
+	fmt "fmt"
+
+	io "io"
+
+	proto "github.com/gogo/protobuf/proto"
+	github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+	runtime "k8s.io/apimachinery/pkg/runtime"
+
+	math "math"
+	math_bits "math/bits"
+	reflect "reflect"
+	strings "strings"
+
+	k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+func (m *ConversionRequest) Reset()      { *m = ConversionRequest{} }
+func (*ConversionRequest) ProtoMessage() {}
+func (*ConversionRequest) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{0}
+}
+func (m *ConversionRequest) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ConversionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ConversionRequest) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ConversionRequest.Merge(m, src)
+}
+func (m *ConversionRequest) XXX_Size() int {
+	return m.Size()
+}
+func (m *ConversionRequest) XXX_DiscardUnknown() {
+	xxx_messageInfo_ConversionRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ConversionRequest proto.InternalMessageInfo
+
+func (m *ConversionResponse) Reset()      { *m = ConversionResponse{} }
+func (*ConversionResponse) ProtoMessage() {}
+func (*ConversionResponse) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{1}
+}
+func (m *ConversionResponse) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ConversionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ConversionResponse) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ConversionResponse.Merge(m, src)
+}
+func (m *ConversionResponse) XXX_Size() int {
+	return m.Size()
+}
+func (m *ConversionResponse) XXX_DiscardUnknown() {
+	xxx_messageInfo_ConversionResponse.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ConversionResponse proto.InternalMessageInfo
+
+func (m *ConversionReview) Reset()      { *m = ConversionReview{} }
+func (*ConversionReview) ProtoMessage() {}
+func (*ConversionReview) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{2}
+}
+func (m *ConversionReview) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ConversionReview) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ConversionReview) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ConversionReview.Merge(m, src)
+}
+func (m *ConversionReview) XXX_Size() int {
+	return m.Size()
+}
+func (m *ConversionReview) XXX_DiscardUnknown() {
+	xxx_messageInfo_ConversionReview.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ConversionReview proto.InternalMessageInfo
+
+func (m *CustomResourceColumnDefinition) Reset()      { *m = CustomResourceColumnDefinition{} }
+func (*CustomResourceColumnDefinition) ProtoMessage() {}
+func (*CustomResourceColumnDefinition) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{3}
+}
+func (m *CustomResourceColumnDefinition) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceColumnDefinition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceColumnDefinition) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceColumnDefinition.Merge(m, src)
+}
+func (m *CustomResourceColumnDefinition) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceColumnDefinition) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceColumnDefinition.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceColumnDefinition proto.InternalMessageInfo
+
+func (m *CustomResourceConversion) Reset()      { *m = CustomResourceConversion{} }
+func (*CustomResourceConversion) ProtoMessage() {}
+func (*CustomResourceConversion) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{4}
+}
+func (m *CustomResourceConversion) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceConversion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceConversion) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceConversion.Merge(m, src)
+}
+func (m *CustomResourceConversion) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceConversion) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceConversion.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceConversion proto.InternalMessageInfo
+
+func (m *CustomResourceDefinition) Reset()      { *m = CustomResourceDefinition{} }
+func (*CustomResourceDefinition) ProtoMessage() {}
+func (*CustomResourceDefinition) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{5}
+}
+func (m *CustomResourceDefinition) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinition) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinition.Merge(m, src)
+}
+func (m *CustomResourceDefinition) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinition) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinition.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinition proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionCondition) Reset()      { *m = CustomResourceDefinitionCondition{} }
+func (*CustomResourceDefinitionCondition) ProtoMessage() {}
+func (*CustomResourceDefinitionCondition) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{6}
+}
+func (m *CustomResourceDefinitionCondition) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionCondition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionCondition) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionCondition.Merge(m, src)
+}
+func (m *CustomResourceDefinitionCondition) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionCondition) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionCondition.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionCondition proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionList) Reset()      { *m = CustomResourceDefinitionList{} }
+func (*CustomResourceDefinitionList) ProtoMessage() {}
+func (*CustomResourceDefinitionList) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{7}
+}
+func (m *CustomResourceDefinitionList) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionList) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionList.Merge(m, src)
+}
+func (m *CustomResourceDefinitionList) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionList) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionList.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionList proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionNames) Reset()      { *m = CustomResourceDefinitionNames{} }
+func (*CustomResourceDefinitionNames) ProtoMessage() {}
+func (*CustomResourceDefinitionNames) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{8}
+}
+func (m *CustomResourceDefinitionNames) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionNames) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionNames) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionNames.Merge(m, src)
+}
+func (m *CustomResourceDefinitionNames) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionNames) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionNames.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionNames proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionSpec) Reset()      { *m = CustomResourceDefinitionSpec{} }
+func (*CustomResourceDefinitionSpec) ProtoMessage() {}
+func (*CustomResourceDefinitionSpec) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{9}
+}
+func (m *CustomResourceDefinitionSpec) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionSpec) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionSpec.Merge(m, src)
+}
+func (m *CustomResourceDefinitionSpec) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionSpec) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionSpec.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionSpec proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionStatus) Reset()      { *m = CustomResourceDefinitionStatus{} }
+func (*CustomResourceDefinitionStatus) ProtoMessage() {}
+func (*CustomResourceDefinitionStatus) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{10}
+}
+func (m *CustomResourceDefinitionStatus) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionStatus) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionStatus.Merge(m, src)
+}
+func (m *CustomResourceDefinitionStatus) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionStatus) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionStatus.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionStatus proto.InternalMessageInfo
+
+func (m *CustomResourceDefinitionVersion) Reset()      { *m = CustomResourceDefinitionVersion{} }
+func (*CustomResourceDefinitionVersion) ProtoMessage() {}
+func (*CustomResourceDefinitionVersion) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{11}
+}
+func (m *CustomResourceDefinitionVersion) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceDefinitionVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceDefinitionVersion) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceDefinitionVersion.Merge(m, src)
+}
+func (m *CustomResourceDefinitionVersion) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceDefinitionVersion) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceDefinitionVersion.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceDefinitionVersion proto.InternalMessageInfo
+
+func (m *CustomResourceSubresourceScale) Reset()      { *m = CustomResourceSubresourceScale{} }
+func (*CustomResourceSubresourceScale) ProtoMessage() {}
+func (*CustomResourceSubresourceScale) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{12}
+}
+func (m *CustomResourceSubresourceScale) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceSubresourceScale) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceSubresourceScale) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceSubresourceScale.Merge(m, src)
+}
+func (m *CustomResourceSubresourceScale) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceSubresourceScale) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceSubresourceScale.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceSubresourceScale proto.InternalMessageInfo
+
+func (m *CustomResourceSubresourceStatus) Reset()      { *m = CustomResourceSubresourceStatus{} }
+func (*CustomResourceSubresourceStatus) ProtoMessage() {}
+func (*CustomResourceSubresourceStatus) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{13}
+}
+func (m *CustomResourceSubresourceStatus) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceSubresourceStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceSubresourceStatus) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceSubresourceStatus.Merge(m, src)
+}
+func (m *CustomResourceSubresourceStatus) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceSubresourceStatus) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceSubresourceStatus.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceSubresourceStatus proto.InternalMessageInfo
+
+func (m *CustomResourceSubresources) Reset()      { *m = CustomResourceSubresources{} }
+func (*CustomResourceSubresources) ProtoMessage() {}
+func (*CustomResourceSubresources) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{14}
+}
+func (m *CustomResourceSubresources) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceSubresources) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceSubresources) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceSubresources.Merge(m, src)
+}
+func (m *CustomResourceSubresources) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceSubresources) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceSubresources.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceSubresources proto.InternalMessageInfo
+
+func (m *CustomResourceValidation) Reset()      { *m = CustomResourceValidation{} }
+func (*CustomResourceValidation) ProtoMessage() {}
+func (*CustomResourceValidation) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{15}
+}
+func (m *CustomResourceValidation) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *CustomResourceValidation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *CustomResourceValidation) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_CustomResourceValidation.Merge(m, src)
+}
+func (m *CustomResourceValidation) XXX_Size() int {
+	return m.Size()
+}
+func (m *CustomResourceValidation) XXX_DiscardUnknown() {
+	xxx_messageInfo_CustomResourceValidation.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CustomResourceValidation proto.InternalMessageInfo
+
+func (m *ExternalDocumentation) Reset()      { *m = ExternalDocumentation{} }
+func (*ExternalDocumentation) ProtoMessage() {}
+func (*ExternalDocumentation) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{16}
+}
+func (m *ExternalDocumentation) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ExternalDocumentation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ExternalDocumentation) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ExternalDocumentation.Merge(m, src)
+}
+func (m *ExternalDocumentation) XXX_Size() int {
+	return m.Size()
+}
+func (m *ExternalDocumentation) XXX_DiscardUnknown() {
+	xxx_messageInfo_ExternalDocumentation.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ExternalDocumentation proto.InternalMessageInfo
+
+func (m *JSON) Reset()      { *m = JSON{} }
+func (*JSON) ProtoMessage() {}
+func (*JSON) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{17}
+}
+func (m *JSON) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *JSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *JSON) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_JSON.Merge(m, src)
+}
+func (m *JSON) XXX_Size() int {
+	return m.Size()
+}
+func (m *JSON) XXX_DiscardUnknown() {
+	xxx_messageInfo_JSON.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_JSON proto.InternalMessageInfo
+
+func (m *JSONSchemaProps) Reset()      { *m = JSONSchemaProps{} }
+func (*JSONSchemaProps) ProtoMessage() {}
+func (*JSONSchemaProps) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{18}
+}
+func (m *JSONSchemaProps) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *JSONSchemaProps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *JSONSchemaProps) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_JSONSchemaProps.Merge(m, src)
+}
+func (m *JSONSchemaProps) XXX_Size() int {
+	return m.Size()
+}
+func (m *JSONSchemaProps) XXX_DiscardUnknown() {
+	xxx_messageInfo_JSONSchemaProps.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_JSONSchemaProps proto.InternalMessageInfo
+
+func (m *JSONSchemaPropsOrArray) Reset()      { *m = JSONSchemaPropsOrArray{} }
+func (*JSONSchemaPropsOrArray) ProtoMessage() {}
+func (*JSONSchemaPropsOrArray) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{19}
+}
+func (m *JSONSchemaPropsOrArray) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *JSONSchemaPropsOrArray) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *JSONSchemaPropsOrArray) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_JSONSchemaPropsOrArray.Merge(m, src)
+}
+func (m *JSONSchemaPropsOrArray) XXX_Size() int {
+	return m.Size()
+}
+func (m *JSONSchemaPropsOrArray) XXX_DiscardUnknown() {
+	xxx_messageInfo_JSONSchemaPropsOrArray.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_JSONSchemaPropsOrArray proto.InternalMessageInfo
+
+func (m *JSONSchemaPropsOrBool) Reset()      { *m = JSONSchemaPropsOrBool{} }
+func (*JSONSchemaPropsOrBool) ProtoMessage() {}
+func (*JSONSchemaPropsOrBool) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{20}
+}
+func (m *JSONSchemaPropsOrBool) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *JSONSchemaPropsOrBool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *JSONSchemaPropsOrBool) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_JSONSchemaPropsOrBool.Merge(m, src)
+}
+func (m *JSONSchemaPropsOrBool) XXX_Size() int {
+	return m.Size()
+}
+func (m *JSONSchemaPropsOrBool) XXX_DiscardUnknown() {
+	xxx_messageInfo_JSONSchemaPropsOrBool.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_JSONSchemaPropsOrBool proto.InternalMessageInfo
+
+func (m *JSONSchemaPropsOrStringArray) Reset()      { *m = JSONSchemaPropsOrStringArray{} }
+func (*JSONSchemaPropsOrStringArray) ProtoMessage() {}
+func (*JSONSchemaPropsOrStringArray) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{21}
+}
+func (m *JSONSchemaPropsOrStringArray) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *JSONSchemaPropsOrStringArray) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *JSONSchemaPropsOrStringArray) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_JSONSchemaPropsOrStringArray.Merge(m, src)
+}
+func (m *JSONSchemaPropsOrStringArray) XXX_Size() int {
+	return m.Size()
+}
+func (m *JSONSchemaPropsOrStringArray) XXX_DiscardUnknown() {
+	xxx_messageInfo_JSONSchemaPropsOrStringArray.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_JSONSchemaPropsOrStringArray proto.InternalMessageInfo
+
+func (m *SelectableField) Reset()      { *m = SelectableField{} }
+func (*SelectableField) ProtoMessage() {}
+func (*SelectableField) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{22}
+}
+func (m *SelectableField) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *SelectableField) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *SelectableField) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_SelectableField.Merge(m, src)
+}
+func (m *SelectableField) XXX_Size() int {
+	return m.Size()
+}
+func (m *SelectableField) XXX_DiscardUnknown() {
+	xxx_messageInfo_SelectableField.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_SelectableField proto.InternalMessageInfo
+
+func (m *ServiceReference) Reset()      { *m = ServiceReference{} }
+func (*ServiceReference) ProtoMessage() {}
+func (*ServiceReference) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{23}
+}
+func (m *ServiceReference) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ServiceReference) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ServiceReference) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ServiceReference.Merge(m, src)
+}
+func (m *ServiceReference) XXX_Size() int {
+	return m.Size()
+}
+func (m *ServiceReference) XXX_DiscardUnknown() {
+	xxx_messageInfo_ServiceReference.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ServiceReference proto.InternalMessageInfo
+
+func (m *ValidationRule) Reset()      { *m = ValidationRule{} }
+func (*ValidationRule) ProtoMessage() {}
+func (*ValidationRule) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{24}
+}
+func (m *ValidationRule) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *ValidationRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *ValidationRule) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ValidationRule.Merge(m, src)
+}
+func (m *ValidationRule) XXX_Size() int {
+	return m.Size()
+}
+func (m *ValidationRule) XXX_DiscardUnknown() {
+	xxx_messageInfo_ValidationRule.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ValidationRule proto.InternalMessageInfo
+
+func (m *WebhookClientConfig) Reset()      { *m = WebhookClientConfig{} }
+func (*WebhookClientConfig) ProtoMessage() {}
+func (*WebhookClientConfig) Descriptor() ([]byte, []int) {
+	return fileDescriptor_3623d6c0bd238430, []int{25}
+}
+func (m *WebhookClientConfig) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *WebhookClientConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	b = b[:cap(b)]
+	n, err := m.MarshalToSizedBuffer(b)
+	if err != nil {
+		return nil, err
+	}
+	return b[:n], nil
+}
+func (m *WebhookClientConfig) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_WebhookClientConfig.Merge(m, src)
+}
+func (m *WebhookClientConfig) XXX_Size() int {
+	return m.Size()
+}
+func (m *WebhookClientConfig) XXX_DiscardUnknown() {
+	xxx_messageInfo_WebhookClientConfig.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_WebhookClientConfig proto.InternalMessageInfo
+
+func init() {
+	proto.RegisterType((*ConversionRequest)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ConversionRequest")
+	proto.RegisterType((*ConversionResponse)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ConversionResponse")
+	proto.RegisterType((*ConversionReview)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ConversionReview")
+	proto.RegisterType((*CustomResourceColumnDefinition)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition")
+	proto.RegisterType((*CustomResourceConversion)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceConversion")
+	proto.RegisterType((*CustomResourceDefinition)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinition")
+	proto.RegisterType((*CustomResourceDefinitionCondition)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionCondition")
+	proto.RegisterType((*CustomResourceDefinitionList)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionList")
+	proto.RegisterType((*CustomResourceDefinitionNames)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames")
+	proto.RegisterType((*CustomResourceDefinitionSpec)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionSpec")
+	proto.RegisterType((*CustomResourceDefinitionStatus)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus")
+	proto.RegisterType((*CustomResourceDefinitionVersion)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionVersion")
+	proto.RegisterType((*CustomResourceSubresourceScale)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceScale")
+	proto.RegisterType((*CustomResourceSubresourceStatus)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceStatus")
+	proto.RegisterType((*CustomResourceSubresources)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources")
+	proto.RegisterType((*CustomResourceValidation)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation")
+	proto.RegisterType((*ExternalDocumentation)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ExternalDocumentation")
+	proto.RegisterType((*JSON)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSON")
+	proto.RegisterType((*JSONSchemaProps)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps")
+	proto.RegisterMapType((JSONSchemaDefinitions)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps.DefinitionsEntry")
+	proto.RegisterMapType((JSONSchemaDependencies)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps.DependenciesEntry")
+	proto.RegisterMapType((map[string]JSONSchemaProps)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps.PatternPropertiesEntry")
+	proto.RegisterMapType((map[string]JSONSchemaProps)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps.PropertiesEntry")
+	proto.RegisterType((*JSONSchemaPropsOrArray)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrArray")
+	proto.RegisterType((*JSONSchemaPropsOrBool)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool")
+	proto.RegisterType((*JSONSchemaPropsOrStringArray)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrStringArray")
+	proto.RegisterType((*SelectableField)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.SelectableField")
+	proto.RegisterType((*ServiceReference)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ServiceReference")
+	proto.RegisterType((*ValidationRule)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.ValidationRule")
+	proto.RegisterType((*WebhookClientConfig)(nil), "k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1.WebhookClientConfig")
+}
+
+func init() {
+	proto.RegisterFile("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto", fileDescriptor_3623d6c0bd238430)
+}
+
+var fileDescriptor_3623d6c0bd238430 = []byte{
+	// 3214 bytes of a gzipped FileDescriptorProto
+	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x5b, 0xcf, 0x73, 0x1c, 0x57,
+	0xf1, 0xf7, 0xac, 0xb4, 0xd2, 0xaa, 0x25, 0x5b, 0xd2, 0xb3, 0xa5, 0x8c, 0x15, 0x47, 0x2b, 0xaf,
+	0xbf, 0xf1, 0x57, 0x49, 0x9c, 0x55, 0xe2, 0x6f, 0xf2, 0x4d, 0x08, 0xa4, 0x52, 0x5a, 0x49, 0x0e,
+	0x4a, 0x2c, 0x4b, 0xbc, 0xb5, 0x1d, 0x41, 0x7e, 0x8e, 0x76, 0x9e, 0xd6, 0x63, 0xcf, 0xce, 0x8c,
+	0xe7, 0xcd, 0xac, 0xa4, 0x0a, 0x50, 0x40, 0x2a, 0x05, 0x45, 0x01, 0xa1, 0x48, 0x2e, 0x14, 0x70,
+	0x08, 0x14, 0x17, 0x0e, 0x70, 0x80, 0x1b, 0xfc, 0x01, 0x39, 0xa6, 0x80, 0x43, 0x0e, 0xd4, 0x16,
+	0x59, 0xfe, 0x05, 0x0a, 0xaa, 0x74, 0xa2, 0xde, 0x8f, 0x99, 0x79, 0x33, 0xbb, 0x6b, 0xbb, 0xa2,
+	0xdd, 0xb8, 0xb8, 0x69, 0xbb, 0xfb, 0xf5, 0xa7, 0xa7, 0x5f, 0xbf, 0xee, 0x7e, 0x3d, 0x23, 0xd8,
+	0xb8, 0xf5, 0x2c, 0x2d, 0x5b, 0xee, 0x92, 0xe1, 0x59, 0x64, 0x3f, 0x20, 0x0e, 0xb5, 0x5c, 0x87,
+	0x3e, 0x6e, 0x78, 0x16, 0x25, 0x7e, 0x93, 0xf8, 0x4b, 0xde, 0xad, 0x3a, 0xe3, 0xd1, 0xb4, 0xc0,
+	0x52, 0xf3, 0xc9, 0x1d, 0x12, 0x18, 0x4f, 0x2e, 0xd5, 0x89, 0x43, 0x7c, 0x23, 0x20, 0x66, 0xd9,
+	0xf3, 0xdd, 0xc0, 0x45, 0xcf, 0x0b, 0x75, 0xe5, 0x94, 0xf4, 0x9b, 0xb1, 0xba, 0xb2, 0x77, 0xab,
+	0xce, 0x78, 0x34, 0x2d, 0x50, 0x96, 0xea, 0xe6, 0x1e, 0xaf, 0x5b, 0xc1, 0x8d, 0x70, 0xa7, 0x5c,
+	0x73, 0x1b, 0x4b, 0x75, 0xb7, 0xee, 0x2e, 0x71, 0xad, 0x3b, 0xe1, 0x2e, 0xff, 0xc5, 0x7f, 0xf0,
+	0xbf, 0x04, 0xda, 0xdc, 0x53, 0x89, 0xf1, 0x0d, 0xa3, 0x76, 0xc3, 0x72, 0x88, 0x7f, 0x90, 0x58,
+	0xdc, 0x20, 0x81, 0xb1, 0xd4, 0xec, 0xb0, 0x71, 0x6e, 0xa9, 0xd7, 0x2a, 0x3f, 0x74, 0x02, 0xab,
+	0x41, 0x3a, 0x16, 0xfc, 0xff, 0xdd, 0x16, 0xd0, 0xda, 0x0d, 0xd2, 0x30, 0xb2, 0xeb, 0x4a, 0x87,
+	0x1a, 0x4c, 0xaf, 0xb8, 0x4e, 0x93, 0xf8, 0xec, 0x29, 0x31, 0xb9, 0x1d, 0x12, 0x1a, 0xa0, 0x0a,
+	0x0c, 0x85, 0x96, 0xa9, 0x6b, 0x0b, 0xda, 0xe2, 0x58, 0xe5, 0x89, 0x8f, 0x5a, 0xc5, 0x63, 0xed,
+	0x56, 0x71, 0xe8, 0xda, 0xfa, 0xea, 0x61, 0xab, 0x78, 0xb6, 0x17, 0x52, 0x70, 0xe0, 0x11, 0x5a,
+	0xbe, 0xb6, 0xbe, 0x8a, 0xd9, 0x62, 0xf4, 0x22, 0x4c, 0x9b, 0x84, 0x5a, 0x3e, 0x31, 0x97, 0xb7,
+	0xd6, 0xaf, 0x0b, 0xfd, 0x7a, 0x8e, 0x6b, 0x3c, 0x2d, 0x35, 0x4e, 0xaf, 0x66, 0x05, 0x70, 0xe7,
+	0x1a, 0xb4, 0x0d, 0xa3, 0xee, 0xce, 0x4d, 0x52, 0x0b, 0xa8, 0x3e, 0xb4, 0x30, 0xb4, 0x38, 0x7e,
+	0xf1, 0xf1, 0x72, 0xb2, 0x83, 0xb1, 0x09, 0x7c, 0xdb, 0xe4, 0xc3, 0x96, 0xb1, 0xb1, 0xb7, 0x16,
+	0xed, 0x5c, 0x65, 0x52, 0xa2, 0x8d, 0x6e, 0x0a, 0x2d, 0x38, 0x52, 0x57, 0xfa, 0x55, 0x0e, 0x90,
+	0xfa, 0xf0, 0xd4, 0x73, 0x1d, 0x4a, 0xfa, 0xf2, 0xf4, 0x14, 0xa6, 0x6a, 0x5c, 0x73, 0x40, 0x4c,
+	0x89, 0xab, 0xe7, 0x3e, 0x8b, 0xf5, 0xba, 0xc4, 0x9f, 0x5a, 0xc9, 0xa8, 0xc3, 0x1d, 0x00, 0xe8,
+	0x2a, 0x8c, 0xf8, 0x84, 0x86, 0x76, 0xa0, 0x0f, 0x2d, 0x68, 0x8b, 0xe3, 0x17, 0x2f, 0xf4, 0x84,
+	0xe2, 0xf1, 0xcd, 0x82, 0xaf, 0xdc, 0x7c, 0xb2, 0x5c, 0x0d, 0x8c, 0x20, 0xa4, 0x95, 0x13, 0x12,
+	0x69, 0x04, 0x73, 0x1d, 0x58, 0xea, 0x2a, 0x7d, 0x2f, 0x07, 0x53, 0xaa, 0x97, 0x9a, 0x16, 0xd9,
+	0x43, 0x7b, 0x30, 0xea, 0x8b, 0x60, 0xe1, 0x7e, 0x1a, 0xbf, 0xb8, 0x55, 0x3e, 0xd2, 0xb1, 0x2a,
+	0x77, 0x04, 0x61, 0x65, 0x9c, 0xed, 0x99, 0xfc, 0x81, 0x23, 0x34, 0xf4, 0x36, 0x14, 0x7c, 0xb9,
+	0x51, 0x3c, 0x9a, 0xc6, 0x2f, 0x7e, 0xa5, 0x8f, 0xc8, 0x42, 0x71, 0x65, 0xa2, 0xdd, 0x2a, 0x16,
+	0xa2, 0x5f, 0x38, 0x06, 0x2c, 0xbd, 0x9f, 0x83, 0xf9, 0x95, 0x90, 0x06, 0x6e, 0x03, 0x13, 0xea,
+	0x86, 0x7e, 0x8d, 0xac, 0xb8, 0x76, 0xd8, 0x70, 0x56, 0xc9, 0xae, 0xe5, 0x58, 0x01, 0x8b, 0xd6,
+	0x05, 0x18, 0x76, 0x8c, 0x06, 0x91, 0xd1, 0x33, 0x21, 0x7d, 0x3a, 0x7c, 0xc5, 0x68, 0x10, 0xcc,
+	0x39, 0x4c, 0x82, 0x05, 0x8b, 0x3c, 0x0b, 0xb1, 0xc4, 0xd5, 0x03, 0x8f, 0x60, 0xce, 0x41, 0xe7,
+	0x61, 0x64, 0xd7, 0xf5, 0x1b, 0x86, 0xd8, 0xc7, 0xb1, 0x64, 0x67, 0x2e, 0x71, 0x2a, 0x96, 0x5c,
+	0xf4, 0x34, 0x8c, 0x9b, 0x84, 0xd6, 0x7c, 0xcb, 0x63, 0xd0, 0xfa, 0x30, 0x17, 0x3e, 0x29, 0x85,
+	0xc7, 0x57, 0x13, 0x16, 0x56, 0xe5, 0xd0, 0x05, 0x28, 0x78, 0xbe, 0xe5, 0xfa, 0x56, 0x70, 0xa0,
+	0xe7, 0x17, 0xb4, 0xc5, 0x7c, 0x65, 0x4a, 0xae, 0x29, 0x6c, 0x49, 0x3a, 0x8e, 0x25, 0xd0, 0x02,
+	0x14, 0x5e, 0xaa, 0x6e, 0x5e, 0xd9, 0x32, 0x82, 0x1b, 0xfa, 0x08, 0x47, 0x18, 0x66, 0xd2, 0x38,
+	0xa6, 0x96, 0xfe, 0x96, 0x03, 0x3d, 0xeb, 0x95, 0xc8, 0xa5, 0xe8, 0x12, 0x14, 0x68, 0xc0, 0x32,
+	0x4e, 0xfd, 0x40, 0xfa, 0xe4, 0xd1, 0x08, 0xac, 0x2a, 0xe9, 0x87, 0xad, 0xe2, 0x6c, 0xb2, 0x22,
+	0xa2, 0x72, 0x7f, 0xc4, 0x6b, 0xd1, 0x2f, 0x34, 0x38, 0xb9, 0x47, 0x76, 0x6e, 0xb8, 0xee, 0xad,
+	0x15, 0xdb, 0x22, 0x4e, 0xb0, 0xe2, 0x3a, 0xbb, 0x56, 0x5d, 0xc6, 0x00, 0x3e, 0x62, 0x0c, 0xbc,
+	0xd2, 0xa9, 0xb9, 0xf2, 0x40, 0xbb, 0x55, 0x3c, 0xd9, 0x85, 0x81, 0xbb, 0xd9, 0x81, 0xb6, 0x41,
+	0xaf, 0x65, 0x0e, 0x89, 0x4c, 0x60, 0x22, 0x6d, 0x8d, 0x55, 0xce, 0xb4, 0x5b, 0x45, 0x7d, 0xa5,
+	0x87, 0x0c, 0xee, 0xb9, 0xba, 0xf4, 0xce, 0x50, 0xd6, 0xbd, 0x4a, 0xb8, 0xbd, 0x05, 0x05, 0x76,
+	0x8c, 0x4d, 0x23, 0x30, 0xe4, 0x41, 0x7c, 0xe2, 0xde, 0x0e, 0xbd, 0xc8, 0x19, 0x1b, 0x24, 0x30,
+	0x2a, 0x48, 0x6e, 0x08, 0x24, 0x34, 0x1c, 0x6b, 0x45, 0xdf, 0x80, 0x61, 0xea, 0x91, 0x9a, 0x74,
+	0xf4, 0xab, 0x47, 0x3d, 0x6c, 0x3d, 0x1e, 0xa4, 0xea, 0x91, 0x5a, 0x72, 0x16, 0xd8, 0x2f, 0xcc,
+	0x61, 0xd1, 0xbb, 0x1a, 0x8c, 0x50, 0x9e, 0xa0, 0x64, 0x52, 0x7b, 0x7d, 0x50, 0x16, 0x64, 0xb2,
+	0xa0, 0xf8, 0x8d, 0x25, 0x78, 0xe9, 0x9f, 0x39, 0x38, 0xdb, 0x6b, 0xe9, 0x8a, 0xeb, 0x98, 0x62,
+	0x3b, 0xd6, 0xe5, 0xd9, 0x16, 0x91, 0xfe, 0xb4, 0x7a, 0xb6, 0x0f, 0x5b, 0xc5, 0x87, 0xef, 0xaa,
+	0x40, 0x49, 0x02, 0x5f, 0x88, 0x9f, 0x5b, 0x24, 0x8a, 0xb3, 0x69, 0xc3, 0x0e, 0x5b, 0xc5, 0xc9,
+	0x78, 0x59, 0xda, 0x56, 0xd4, 0x04, 0x64, 0x1b, 0x34, 0xb8, 0xea, 0x1b, 0x0e, 0x15, 0x6a, 0xad,
+	0x06, 0x91, 0xee, 0x7b, 0xf4, 0xde, 0xc2, 0x83, 0xad, 0xa8, 0xcc, 0x49, 0x48, 0x74, 0xb9, 0x43,
+	0x1b, 0xee, 0x82, 0xc0, 0xf2, 0x96, 0x4f, 0x0c, 0x1a, 0xa7, 0x22, 0xa5, 0xa2, 0x30, 0x2a, 0x96,
+	0x5c, 0xf4, 0x08, 0x8c, 0x36, 0x08, 0xa5, 0x46, 0x9d, 0xf0, 0xfc, 0x33, 0x96, 0x94, 0xe8, 0x0d,
+	0x41, 0xc6, 0x11, 0x9f, 0xf5, 0x27, 0x67, 0x7a, 0x79, 0xed, 0xb2, 0x45, 0x03, 0xf4, 0x5a, 0xc7,
+	0x01, 0x28, 0xdf, 0xdb, 0x13, 0xb2, 0xd5, 0x3c, 0xfc, 0xe3, 0xe4, 0x17, 0x51, 0x94, 0xe0, 0xff,
+	0x3a, 0xe4, 0xad, 0x80, 0x34, 0xa2, 0xda, 0xfd, 0xca, 0x80, 0x62, 0xaf, 0x72, 0x5c, 0xda, 0x90,
+	0x5f, 0x67, 0x68, 0x58, 0x80, 0x96, 0x7e, 0x9d, 0x83, 0x87, 0x7a, 0x2d, 0x61, 0x05, 0x85, 0x32,
+	0x8f, 0x7b, 0x76, 0xe8, 0x1b, 0xb6, 0x8c, 0xb8, 0xd8, 0xe3, 0x5b, 0x9c, 0x8a, 0x25, 0x97, 0xa5,
+	0x7c, 0x6a, 0x39, 0xf5, 0xd0, 0x36, 0x7c, 0x19, 0x4e, 0xf1, 0x53, 0x57, 0x25, 0x1d, 0xc7, 0x12,
+	0xa8, 0x0c, 0x40, 0x6f, 0xb8, 0x7e, 0xc0, 0x31, 0x64, 0xf6, 0x3a, 0xc1, 0x12, 0x44, 0x35, 0xa6,
+	0x62, 0x45, 0x82, 0x55, 0xb4, 0x5b, 0x96, 0x63, 0xca, 0x5d, 0x8f, 0x4f, 0xf1, 0xcb, 0x96, 0x63,
+	0x62, 0xce, 0x61, 0xf8, 0xb6, 0x45, 0x03, 0x46, 0x91, 0x5b, 0x9e, 0xf2, 0x3a, 0x97, 0x8c, 0x25,
+	0x18, 0x7e, 0x8d, 0x65, 0x7d, 0xd7, 0xb7, 0x08, 0xd5, 0x47, 0x12, 0xfc, 0x95, 0x98, 0x8a, 0x15,
+	0x89, 0xd2, 0x3b, 0xd0, 0x3b, 0x48, 0x58, 0x2a, 0x41, 0xe7, 0x20, 0x5f, 0xf7, 0xdd, 0xd0, 0x93,
+	0x5e, 0x8a, 0xbd, 0xfd, 0x22, 0x23, 0x62, 0xc1, 0x63, 0x51, 0xd9, 0x4c, 0xb5, 0xa9, 0x71, 0x54,
+	0x46, 0xcd, 0x69, 0xc4, 0x47, 0xdf, 0xd6, 0x20, 0xef, 0x48, 0xe7, 0xb0, 0x90, 0x7b, 0x6d, 0x40,
+	0x71, 0xc1, 0xdd, 0x9b, 0x98, 0x2b, 0x3c, 0x2f, 0x90, 0xd1, 0x53, 0x90, 0xa7, 0x35, 0xd7, 0x23,
+	0xd2, 0xeb, 0xf3, 0x91, 0x50, 0x95, 0x11, 0x0f, 0x5b, 0xc5, 0xe3, 0x91, 0x3a, 0x4e, 0xc0, 0x42,
+	0x18, 0x7d, 0x57, 0x03, 0x68, 0x1a, 0xb6, 0x65, 0x1a, 0xbc, 0x65, 0xc8, 0x73, 0xf3, 0xfb, 0x1b,
+	0xd6, 0xd7, 0x63, 0xf5, 0x62, 0xd3, 0x92, 0xdf, 0x58, 0x81, 0x46, 0xef, 0x69, 0x30, 0x41, 0xc3,
+	0x1d, 0x5f, 0xae, 0xa2, 0xbc, 0xb9, 0x18, 0xbf, 0xf8, 0xd5, 0xbe, 0xda, 0x52, 0x55, 0x00, 0x2a,
+	0x53, 0xed, 0x56, 0x71, 0x42, 0xa5, 0xe0, 0x94, 0x01, 0xe8, 0x07, 0x1a, 0x14, 0x9a, 0x51, 0xcd,
+	0x1e, 0xe5, 0x07, 0xfe, 0x8d, 0x01, 0x6d, 0xac, 0x8c, 0xa8, 0xe4, 0x14, 0xc4, 0x7d, 0x40, 0x6c,
+	0x01, 0xfa, 0xa3, 0x06, 0xba, 0x61, 0x8a, 0x04, 0x6f, 0xd8, 0x5b, 0xbe, 0xe5, 0x04, 0xc4, 0x17,
+	0xfd, 0x26, 0xd5, 0x0b, 0xdc, 0xbc, 0xfe, 0xd6, 0xc2, 0x6c, 0x2f, 0x5b, 0x59, 0x90, 0xd6, 0xe9,
+	0xcb, 0x3d, 0xcc, 0xc0, 0x3d, 0x0d, 0x44, 0x1f, 0x68, 0x30, 0x45, 0x89, 0x4d, 0x6a, 0x81, 0xb1,
+	0x63, 0x93, 0x4b, 0x16, 0xb1, 0x4d, 0xaa, 0x8f, 0x73, 0xab, 0xaf, 0x1c, 0xd1, 0xea, 0x6a, 0x5a,
+	0x6d, 0x72, 0x45, 0xca, 0x30, 0x28, 0xee, 0xb0, 0x80, 0xc7, 0x7f, 0xd2, 0x69, 0xe9, 0x63, 0x03,
+	0x88, 0xff, 0xa4, 0xc5, 0x93, 0x49, 0x2b, 0x69, 0xec, 0x14, 0x68, 0xb4, 0x09, 0x33, 0x9e, 0x4f,
+	0x38, 0xc0, 0x35, 0xe7, 0x96, 0xe3, 0xee, 0x39, 0xd2, 0x49, 0xb0, 0xa0, 0x2d, 0x16, 0x2a, 0xa7,
+	0xdb, 0xad, 0xe2, 0xcc, 0x56, 0x37, 0x01, 0xdc, 0x7d, 0x5d, 0xe9, 0xbd, 0xa1, 0xec, 0xe5, 0x24,
+	0xdb, 0xdc, 0xb0, 0x4d, 0x61, 0x26, 0x88, 0x2d, 0xa3, 0xba, 0xc6, 0xb7, 0xe3, 0xad, 0x01, 0xc5,
+	0x78, 0xdc, 0x9d, 0x24, 0x0d, 0x66, 0x4c, 0xa2, 0x58, 0xb1, 0x03, 0xfd, 0x54, 0x83, 0xe3, 0x46,
+	0xad, 0x46, 0xbc, 0x80, 0x98, 0xa2, 0xe6, 0xe4, 0x3e, 0x87, 0xb4, 0x3a, 0x23, 0xad, 0x3a, 0xbe,
+	0xac, 0x42, 0xe3, 0xb4, 0x25, 0xe8, 0x39, 0x38, 0x41, 0x03, 0xd7, 0x27, 0x66, 0xa6, 0x9b, 0x47,
+	0xed, 0x56, 0xf1, 0x44, 0x35, 0xc5, 0xc1, 0x19, 0xc9, 0xd2, 0xbf, 0x46, 0xa0, 0x78, 0x97, 0x0c,
+	0x70, 0x0f, 0xf7, 0xc5, 0xf3, 0x30, 0xc2, 0x1f, 0xd7, 0xe4, 0x5e, 0x29, 0x28, 0x1d, 0x2a, 0xa7,
+	0x62, 0xc9, 0x65, 0xf5, 0x8b, 0xe1, 0xb3, 0xae, 0x6a, 0x88, 0x0b, 0xc6, 0xf5, 0xab, 0x2a, 0xc8,
+	0x38, 0xe2, 0xa3, 0x8b, 0x00, 0x26, 0xf1, 0x7c, 0xc2, 0x6a, 0xa8, 0xa9, 0x8f, 0x72, 0xe9, 0x78,
+	0x93, 0x56, 0x63, 0x0e, 0x56, 0xa4, 0xd0, 0x25, 0x40, 0xd1, 0x2f, 0xcb, 0x75, 0x5e, 0x31, 0x7c,
+	0xc7, 0x72, 0xea, 0x7a, 0x81, 0x9b, 0x3d, 0xcb, 0x9a, 0xc4, 0xd5, 0x0e, 0x2e, 0xee, 0xb2, 0x02,
+	0xbd, 0x0d, 0x23, 0x62, 0x16, 0xc5, 0x0b, 0xd7, 0x00, 0x8b, 0x0f, 0x70, 0x1f, 0x71, 0x28, 0x2c,
+	0x21, 0x3b, 0x8b, 0x4e, 0xfe, 0x7e, 0x17, 0x9d, 0x3b, 0x66, 0xf9, 0x91, 0xff, 0xca, 0x2c, 0x3f,
+	0x76, 0xbf, 0xb3, 0x7c, 0xe9, 0xdf, 0x5a, 0x36, 0x15, 0x2a, 0x3b, 0x50, 0xad, 0x19, 0x36, 0x41,
+	0xab, 0x30, 0xc5, 0xee, 0x97, 0x98, 0x78, 0xb6, 0x55, 0x33, 0x28, 0x1f, 0x6f, 0x88, 0x33, 0x98,
+	0x00, 0x65, 0xf8, 0xb8, 0x63, 0x05, 0x7a, 0x09, 0x90, 0xb8, 0x73, 0xa5, 0xf4, 0x88, 0xf6, 0x31,
+	0xbe, 0x3d, 0x55, 0x3b, 0x24, 0x70, 0x97, 0x55, 0x68, 0x05, 0xa6, 0x6d, 0x63, 0x87, 0xd8, 0xe2,
+	0xf9, 0x5c, 0x9f, 0xab, 0x12, 0x03, 0xa0, 0x99, 0x76, 0xab, 0x38, 0x7d, 0x39, 0xcb, 0xc4, 0x9d,
+	0xf2, 0xa5, 0xb3, 0xd9, 0x8c, 0xa3, 0x3e, 0xb8, 0xb8, 0xc9, 0x7e, 0x98, 0x83, 0xb9, 0xde, 0x01,
+	0x8b, 0xbe, 0x93, 0x5c, 0xb8, 0xc5, 0x7d, 0xea, 0x8d, 0x41, 0x1d, 0x0e, 0x79, 0xe3, 0x86, 0xce,
+	0xdb, 0x36, 0xfa, 0x26, 0x6b, 0x6e, 0x0d, 0x3b, 0x1a, 0xf1, 0xbd, 0x3e, 0x30, 0x13, 0x18, 0x48,
+	0x65, 0x4c, 0xf4, 0xcd, 0x86, 0xcd, 0xdb, 0x64, 0xc3, 0x26, 0xa5, 0xdf, 0x68, 0xd9, 0x99, 0x4b,
+	0x92, 0x58, 0xd0, 0x0f, 0x35, 0x98, 0x74, 0x3d, 0xe2, 0x2c, 0x6f, 0xad, 0x5f, 0xff, 0x3f, 0x91,
+	0x60, 0xa4, 0xab, 0x8e, 0x1a, 0xf3, 0x2f, 0x55, 0x37, 0xaf, 0x08, 0x85, 0x5b, 0xbe, 0xeb, 0xd1,
+	0xca, 0xc9, 0x76, 0xab, 0x38, 0xb9, 0x99, 0x86, 0xc2, 0x59, 0xec, 0x52, 0x03, 0x66, 0xd6, 0xf6,
+	0x03, 0xe2, 0x3b, 0x86, 0xbd, 0xea, 0xd6, 0xc2, 0x06, 0x71, 0x02, 0x61, 0x68, 0x66, 0x3e, 0xa8,
+	0xdd, 0xe3, 0x7c, 0xf0, 0x21, 0x18, 0x0a, 0x7d, 0x5b, 0x46, 0xf1, 0x78, 0x3c, 0xff, 0xc6, 0x97,
+	0x31, 0xa3, 0x97, 0xce, 0xc2, 0x30, 0xb3, 0x13, 0x9d, 0x86, 0x21, 0xdf, 0xd8, 0xe3, 0x5a, 0x27,
+	0x2a, 0xa3, 0x4c, 0x04, 0x1b, 0x7b, 0x98, 0xd1, 0x4a, 0x7f, 0x3d, 0x0b, 0x93, 0x99, 0x67, 0x41,
+	0x73, 0x90, 0x8b, 0x87, 0xea, 0x20, 0x95, 0xe6, 0xd6, 0x57, 0x71, 0xce, 0x32, 0xd1, 0x33, 0x71,
+	0x4d, 0x10, 0xa0, 0xc5, 0xb8, 0xc4, 0x71, 0x2a, 0xbb, 0xcd, 0x24, 0xea, 0x98, 0x21, 0x51, 0x3e,
+	0x67, 0x36, 0x90, 0x5d, 0x79, 0x4a, 0x84, 0x0d, 0x64, 0x17, 0x33, 0xda, 0x67, 0x1d, 0x8e, 0x46,
+	0xd3, 0xd9, 0xfc, 0x3d, 0x4c, 0x67, 0x47, 0xee, 0x38, 0x9d, 0x3d, 0x07, 0xf9, 0xc0, 0x0a, 0x6c,
+	0xc2, 0xeb, 0xab, 0x72, 0xe9, 0xbc, 0xca, 0x88, 0x58, 0xf0, 0xd0, 0x4d, 0x18, 0x35, 0xc9, 0xae,
+	0x11, 0xda, 0x01, 0x2f, 0xa5, 0xe3, 0x17, 0x57, 0xfa, 0x10, 0x42, 0x62, 0x74, 0xbe, 0x2a, 0xf4,
+	0xe2, 0x08, 0x00, 0x3d, 0x0c, 0xa3, 0x0d, 0x63, 0xdf, 0x6a, 0x84, 0x0d, 0xde, 0xf7, 0x6a, 0x42,
+	0x6c, 0x43, 0x90, 0x70, 0xc4, 0x63, 0x99, 0x91, 0xec, 0xd7, 0xec, 0x90, 0x5a, 0x4d, 0x22, 0x99,
+	0xb2, 0x27, 0x8d, 0x33, 0xe3, 0x5a, 0x86, 0x8f, 0x3b, 0x56, 0x70, 0x30, 0xcb, 0xe1, 0x8b, 0xc7,
+	0x15, 0x30, 0x41, 0xc2, 0x11, 0x2f, 0x0d, 0x26, 0xe5, 0x27, 0x7a, 0x81, 0xc9, 0xc5, 0x1d, 0x2b,
+	0xd0, 0x63, 0x30, 0xd6, 0x30, 0xf6, 0x2f, 0x13, 0xa7, 0x1e, 0xdc, 0xd0, 0x8f, 0x2f, 0x68, 0x8b,
+	0x43, 0x95, 0xe3, 0xed, 0x56, 0x71, 0x6c, 0x23, 0x22, 0xe2, 0x84, 0xcf, 0x85, 0x2d, 0x47, 0x0a,
+	0x9f, 0x50, 0x84, 0x23, 0x22, 0x4e, 0xf8, 0xac, 0xa9, 0xf2, 0x8c, 0x80, 0x1d, 0x2e, 0x7d, 0x32,
+	0x3d, 0x14, 0xd8, 0x12, 0x64, 0x1c, 0xf1, 0xd1, 0x22, 0x14, 0x1a, 0xc6, 0x3e, 0x1f, 0xe0, 0xe8,
+	0x53, 0x5c, 0x2d, 0x7f, 0x8d, 0xb0, 0x21, 0x69, 0x38, 0xe6, 0x72, 0x49, 0xcb, 0x11, 0x92, 0xd3,
+	0x8a, 0xa4, 0xa4, 0xe1, 0x98, 0xcb, 0x82, 0x38, 0x74, 0xac, 0xdb, 0x21, 0x11, 0xc2, 0x88, 0x7b,
+	0x26, 0x0e, 0xe2, 0x6b, 0x09, 0x0b, 0xab, 0x72, 0xa8, 0x0c, 0xd0, 0x08, 0xed, 0xc0, 0xf2, 0x6c,
+	0xb2, 0xb9, 0xab, 0x9f, 0xe4, 0xfe, 0xe7, 0x77, 0x91, 0x8d, 0x98, 0x8a, 0x15, 0x09, 0x44, 0x60,
+	0x98, 0x38, 0x61, 0x43, 0x3f, 0xc5, 0x2b, 0x77, 0x5f, 0x42, 0x30, 0x3e, 0x39, 0x6b, 0x4e, 0xd8,
+	0xc0, 0x5c, 0x3d, 0x7a, 0x06, 0x8e, 0x37, 0x8c, 0x7d, 0x96, 0x0e, 0x88, 0x1f, 0x58, 0x84, 0xea,
+	0x33, 0xfc, 0xe1, 0xa7, 0x59, 0x13, 0xbe, 0xa1, 0x32, 0x70, 0x5a, 0x8e, 0x2f, 0xb4, 0x1c, 0x65,
+	0xe1, 0xac, 0xb2, 0x50, 0x65, 0xe0, 0xb4, 0x1c, 0xf3, 0xb4, 0x4f, 0x6e, 0x87, 0x96, 0x4f, 0x4c,
+	0xfd, 0x01, 0xde, 0xb7, 0xcb, 0x57, 0x3b, 0x82, 0x86, 0x63, 0x2e, 0x6a, 0x46, 0x93, 0x3e, 0x9d,
+	0x1f, 0xc3, 0x6b, 0xfd, 0xcd, 0xe4, 0x9b, 0xfe, 0xb2, 0xef, 0x1b, 0x07, 0xa2, 0xd2, 0xa8, 0x33,
+	0x3e, 0x44, 0x21, 0x6f, 0xd8, 0xf6, 0xe6, 0xae, 0x7e, 0xba, 0x2f, 0x5d, 0x53, 0xb6, 0x82, 0xc4,
+	0x59, 0x67, 0x99, 0x81, 0x60, 0x81, 0xc5, 0x40, 0x5d, 0x87, 0x85, 0xc6, 0xdc, 0x60, 0x41, 0x37,
+	0x19, 0x08, 0x16, 0x58, 0xfc, 0x49, 0x9d, 0x83, 0xcd, 0x5d, 0xfd, 0xc1, 0x01, 0x3f, 0x29, 0x03,
+	0xc1, 0x02, 0x0b, 0x59, 0x30, 0xe4, 0xb8, 0x81, 0x7e, 0x66, 0x20, 0xe5, 0x99, 0x17, 0x9c, 0x2b,
+	0x6e, 0x80, 0x19, 0x06, 0xfa, 0x89, 0x06, 0xe0, 0x25, 0x21, 0xfa, 0x50, 0x5f, 0x06, 0x48, 0x19,
+	0xc8, 0x72, 0x12, 0xdb, 0x6b, 0x4e, 0xe0, 0x1f, 0x24, 0xb7, 0x36, 0xe5, 0x0c, 0x28, 0x56, 0xa0,
+	0x5f, 0x6a, 0x70, 0x4a, 0xed, 0xde, 0x63, 0xf3, 0xe6, 0xb9, 0x47, 0xae, 0xf6, 0x3b, 0xcc, 0x2b,
+	0xae, 0x6b, 0x57, 0xf4, 0x76, 0xab, 0x78, 0x6a, 0xb9, 0x0b, 0x2a, 0xee, 0x6a, 0x0b, 0xfa, 0xad,
+	0x06, 0xd3, 0x32, 0x8b, 0x2a, 0x16, 0x16, 0xb9, 0x03, 0x49, 0xbf, 0x1d, 0x98, 0xc5, 0x11, 0x7e,
+	0x8c, 0x3f, 0x49, 0xe8, 0xe0, 0xe3, 0x4e, 0xd3, 0xd0, 0x1f, 0x34, 0x98, 0x30, 0x89, 0x47, 0x1c,
+	0x93, 0x38, 0x35, 0x66, 0xeb, 0x42, 0x5f, 0x26, 0x29, 0x59, 0x5b, 0x57, 0x15, 0x08, 0x61, 0x66,
+	0x59, 0x9a, 0x39, 0xa1, 0xb2, 0x0e, 0x5b, 0xc5, 0xd9, 0x64, 0xa9, 0xca, 0xc1, 0x29, 0x2b, 0xd1,
+	0xfb, 0x1a, 0x4c, 0x26, 0x1b, 0x20, 0x4a, 0xca, 0xd9, 0x01, 0xc6, 0x01, 0x6f, 0x5f, 0x97, 0xd3,
+	0x80, 0x38, 0x6b, 0x01, 0xfa, 0x9d, 0xc6, 0x3a, 0xb5, 0xe8, 0x3a, 0x4a, 0xf5, 0x12, 0xf7, 0xe5,
+	0x9b, 0x7d, 0xf7, 0x65, 0x8c, 0x20, 0x5c, 0x79, 0x21, 0x69, 0x05, 0x63, 0xce, 0x61, 0xab, 0x38,
+	0xa3, 0x7a, 0x32, 0x66, 0x60, 0xd5, 0x42, 0xf4, 0x7d, 0x0d, 0x26, 0x48, 0xd2, 0x71, 0x53, 0xfd,
+	0x5c, 0x5f, 0x9c, 0xd8, 0xb5, 0x89, 0x17, 0x03, 0x04, 0x85, 0x45, 0x71, 0x0a, 0x9b, 0x75, 0x90,
+	0x64, 0xdf, 0x68, 0x78, 0x36, 0xd1, 0xff, 0xa7, 0xcf, 0x1d, 0xe4, 0x9a, 0xd0, 0x8b, 0x23, 0x00,
+	0x74, 0x01, 0x0a, 0x4e, 0x68, 0xdb, 0xec, 0xa6, 0xad, 0x3f, 0xcc, 0x7b, 0x91, 0x78, 0x80, 0x7d,
+	0x45, 0xd2, 0x71, 0x2c, 0x81, 0x76, 0x61, 0x61, 0xff, 0xe5, 0x70, 0x87, 0xf8, 0x0e, 0x09, 0x08,
+	0xed, 0x3a, 0xcb, 0xd4, 0xcf, 0x73, 0x2d, 0x73, 0xed, 0x56, 0x71, 0x76, 0xbb, 0xfb, 0xb4, 0xf3,
+	0xae, 0x3a, 0xd0, 0xab, 0xf0, 0xa0, 0x22, 0xb3, 0xd6, 0xd8, 0x21, 0xa6, 0x49, 0xcc, 0xe8, 0xe2,
+	0xa6, 0xff, 0xaf, 0x98, 0xa7, 0x46, 0x07, 0x7c, 0x3b, 0x2b, 0x80, 0xef, 0xb4, 0x1a, 0x5d, 0x86,
+	0x59, 0x85, 0xbd, 0xee, 0x04, 0x9b, 0x7e, 0x35, 0xf0, 0x2d, 0xa7, 0xae, 0x2f, 0x72, 0xbd, 0xa7,
+	0xa2, 0x13, 0xb9, 0xad, 0xf0, 0x70, 0x8f, 0x35, 0xe8, 0xcb, 0x29, 0x6d, 0xfc, 0x85, 0xa3, 0xe1,
+	0xbd, 0x4c, 0x0e, 0xa8, 0xfe, 0x08, 0xef, 0x4e, 0xf8, 0x66, 0x6f, 0x2b, 0x74, 0xdc, 0x43, 0x1e,
+	0xbd, 0x00, 0x27, 0x33, 0x1c, 0x76, 0x45, 0xd1, 0x1f, 0x15, 0x77, 0x0d, 0xd6, 0xcf, 0x6e, 0x47,
+	0x44, 0xdc, 0x4d, 0x12, 0x7d, 0x09, 0x90, 0x42, 0xde, 0x30, 0x3c, 0xbe, 0xfe, 0x31, 0x71, 0xed,
+	0x61, 0x3b, 0xba, 0x2d, 0x69, 0xb8, 0x8b, 0x1c, 0xfa, 0x99, 0x96, 0x7a, 0x92, 0xe4, 0x76, 0x4c,
+	0xf5, 0x0b, 0xfc, 0xfc, 0x6e, 0x1c, 0x31, 0x0a, 0x95, 0xb7, 0x46, 0xa1, 0x4d, 0x14, 0x37, 0x2b,
+	0x50, 0xb8, 0x87, 0x09, 0x73, 0xec, 0x86, 0x9e, 0xc9, 0xf0, 0x68, 0x0a, 0x86, 0x6e, 0x11, 0xf9,
+	0x0d, 0x0a, 0x66, 0x7f, 0x22, 0x13, 0xf2, 0x4d, 0xc3, 0x0e, 0xa3, 0x21, 0x43, 0x9f, 0xbb, 0x03,
+	0x2c, 0x94, 0x3f, 0x97, 0x7b, 0x56, 0x9b, 0xfb, 0x40, 0x83, 0xd9, 0xee, 0x85, 0xe7, 0xbe, 0x9a,
+	0xf5, 0x73, 0x0d, 0xa6, 0x3b, 0x6a, 0x4c, 0x17, 0x8b, 0x6e, 0xa7, 0x2d, 0x7a, 0xb5, 0xdf, 0xc5,
+	0x42, 0x1c, 0x0e, 0xde, 0x21, 0xab, 0xe6, 0xfd, 0x48, 0x83, 0xa9, 0x6c, 0xda, 0xbe, 0x9f, 0xfe,
+	0x2a, 0x7d, 0x90, 0x83, 0xd9, 0xee, 0x8d, 0x3d, 0xf2, 0xe3, 0x09, 0xc6, 0x60, 0x26, 0x41, 0xdd,
+	0x86, 0xd9, 0xef, 0x6a, 0x30, 0x7e, 0x33, 0x96, 0x8b, 0xbe, 0x51, 0xe8, 0xfb, 0x0c, 0x2a, 0xaa,
+	0x93, 0x09, 0x83, 0x62, 0x15, 0xb7, 0xf4, 0x7b, 0x0d, 0x66, 0xba, 0x36, 0x00, 0xe8, 0x3c, 0x8c,
+	0x18, 0xb6, 0xed, 0xee, 0x89, 0x51, 0xa2, 0xf2, 0xea, 0x62, 0x99, 0x53, 0xb1, 0xe4, 0x2a, 0xde,
+	0xcb, 0x7d, 0x5e, 0xde, 0x2b, 0xfd, 0x49, 0x83, 0x33, 0x77, 0x8a, 0xc4, 0xfb, 0xb2, 0xa5, 0x8b,
+	0x50, 0x90, 0xcd, 0xfb, 0x01, 0xdf, 0x4e, 0x99, 0x8a, 0x65, 0xd2, 0xe0, 0x9f, 0xe5, 0x89, 0xbf,
+	0x4a, 0x2f, 0xc0, 0x64, 0x66, 0x10, 0xce, 0xaa, 0xf3, 0x4d, 0xea, 0x3a, 0xca, 0x28, 0x3b, 0xae,
+	0xce, 0xd1, 0xb7, 0x7a, 0x38, 0x96, 0x28, 0x7d, 0xa8, 0xc1, 0x54, 0x95, 0xf8, 0x4d, 0xab, 0x46,
+	0x30, 0xd9, 0x25, 0x3e, 0x71, 0x6a, 0x04, 0x2d, 0xc1, 0x18, 0xff, 0xba, 0xc0, 0x33, 0x6a, 0xd1,
+	0x2b, 0xa9, 0x69, 0xa9, 0x63, 0xec, 0x4a, 0xc4, 0xc0, 0x89, 0x4c, 0xfc, 0xfa, 0x2a, 0xd7, 0xf3,
+	0xf5, 0xd5, 0x19, 0x18, 0xf6, 0x92, 0x49, 0x76, 0x81, 0x71, 0xb9, 0x25, 0x9c, 0xca, 0xb9, 0xae,
+	0x1f, 0xf0, 0xf1, 0x5c, 0x5e, 0x72, 0x5d, 0x3f, 0xc0, 0x9c, 0x5a, 0xfa, 0x4b, 0x0e, 0x4e, 0xa4,
+	0x0b, 0x01, 0x03, 0xf4, 0x43, 0xbb, 0xe3, 0x7d, 0x19, 0xe3, 0x61, 0xce, 0x51, 0xbf, 0x2e, 0xca,
+	0xdd, 0xf9, 0xeb, 0x22, 0xf4, 0x22, 0x4c, 0xcb, 0x3f, 0xd7, 0xf6, 0x3d, 0x9f, 0x50, 0xfe, 0x4e,
+	0x78, 0x28, 0xfd, 0x8d, 0xf2, 0x46, 0x56, 0x00, 0x77, 0xae, 0x41, 0x5f, 0xcc, 0x7c, 0xf9, 0x74,
+	0x2e, 0xf9, 0xea, 0x89, 0xf5, 0x94, 0x7c, 0x7f, 0xae, 0xb3, 0x3c, 0xb2, 0xe6, 0xfb, 0xae, 0x9f,
+	0xf9, 0x1c, 0x6a, 0x09, 0xc6, 0x76, 0x99, 0x00, 0xdf, 0xb8, 0x7c, 0xda, 0xe9, 0x97, 0x22, 0x06,
+	0x4e, 0x64, 0xd0, 0xf3, 0x30, 0xe9, 0x7a, 0xa2, 0x85, 0xde, 0xb4, 0xcd, 0x2a, 0xb1, 0x77, 0xf9,
+	0x28, 0xb2, 0x10, 0xcd, 0x8b, 0x53, 0x2c, 0x9c, 0x95, 0x2d, 0xfd, 0x59, 0x83, 0x6e, 0xdf, 0x35,
+	0xa2, 0xd3, 0x62, 0xee, 0xab, 0x0c, 0x53, 0xa3, 0x99, 0x2f, 0x6a, 0xc2, 0x28, 0x15, 0xb1, 0x22,
+	0x0f, 0xc3, 0xe6, 0x91, 0xdf, 0xee, 0xa4, 0x23, 0x4f, 0x34, 0x9c, 0x11, 0x35, 0x02, 0x63, 0xe7,
+	0xa1, 0x66, 0x54, 0x42, 0xc7, 0x94, 0xaf, 0x02, 0x26, 0xc4, 0x79, 0x58, 0x59, 0x16, 0x34, 0x1c,
+	0x73, 0x2b, 0xb5, 0x8f, 0x3e, 0x9d, 0x3f, 0xf6, 0xf1, 0xa7, 0xf3, 0xc7, 0x3e, 0xf9, 0x74, 0xfe,
+	0xd8, 0xb7, 0xda, 0xf3, 0xda, 0x47, 0xed, 0x79, 0xed, 0xe3, 0xf6, 0xbc, 0xf6, 0x49, 0x7b, 0x5e,
+	0xfb, 0x7b, 0x7b, 0x5e, 0xfb, 0xf1, 0x3f, 0xe6, 0x8f, 0x7d, 0xed, 0xf9, 0x23, 0xfd, 0x2b, 0xc1,
+	0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0xdf, 0xe3, 0x03, 0xa1, 0x8a, 0x30, 0x00, 0x00,
+}
+
+func (m *ConversionRequest) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ConversionRequest) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ConversionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.Objects) > 0 {
+		for iNdEx := len(m.Objects) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Objects[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x1a
+		}
+	}
+	i -= len(m.DesiredAPIVersion)
+	copy(dAtA[i:], m.DesiredAPIVersion)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.DesiredAPIVersion)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.UID)
+	copy(dAtA[i:], m.UID)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *ConversionResponse) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ConversionResponse) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ConversionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	{
+		size, err := m.Result.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x1a
+	if len(m.ConvertedObjects) > 0 {
+		for iNdEx := len(m.ConvertedObjects) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.ConvertedObjects[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+		}
+	}
+	i -= len(m.UID)
+	copy(dAtA[i:], m.UID)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *ConversionReview) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ConversionReview) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ConversionReview) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.Response != nil {
+		{
+			size, err := m.Response.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x12
+	}
+	if m.Request != nil {
+		{
+			size, err := m.Request.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceColumnDefinition) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceColumnDefinition) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceColumnDefinition) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	i -= len(m.JSONPath)
+	copy(dAtA[i:], m.JSONPath)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.JSONPath)))
+	i--
+	dAtA[i] = 0x32
+	i = encodeVarintGenerated(dAtA, i, uint64(m.Priority))
+	i--
+	dAtA[i] = 0x28
+	i -= len(m.Description)
+	copy(dAtA[i:], m.Description)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description)))
+	i--
+	dAtA[i] = 0x22
+	i -= len(m.Format)
+	copy(dAtA[i:], m.Format)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Format)))
+	i--
+	dAtA[i] = 0x1a
+	i -= len(m.Type)
+	copy(dAtA[i:], m.Type)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Name)
+	copy(dAtA[i:], m.Name)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceConversion) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceConversion) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceConversion) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.ConversionReviewVersions) > 0 {
+		for iNdEx := len(m.ConversionReviewVersions) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.ConversionReviewVersions[iNdEx])
+			copy(dAtA[i:], m.ConversionReviewVersions[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.ConversionReviewVersions[iNdEx])))
+			i--
+			dAtA[i] = 0x1a
+		}
+	}
+	if m.WebhookClientConfig != nil {
+		{
+			size, err := m.WebhookClientConfig.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x12
+	}
+	i -= len(m.Strategy)
+	copy(dAtA[i:], m.Strategy)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Strategy)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinition) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinition) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinition) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	{
+		size, err := m.Status.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x1a
+	{
+		size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x12
+	{
+		size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionCondition) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionCondition) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	i -= len(m.Message)
+	copy(dAtA[i:], m.Message)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message)))
+	i--
+	dAtA[i] = 0x2a
+	i -= len(m.Reason)
+	copy(dAtA[i:], m.Reason)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason)))
+	i--
+	dAtA[i] = 0x22
+	{
+		size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x1a
+	i -= len(m.Status)
+	copy(dAtA[i:], m.Status)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Type)
+	copy(dAtA[i:], m.Type)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionList) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionList) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionList) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.Items) > 0 {
+		for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+		}
+	}
+	{
+		size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionNames) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionNames) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionNames) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.Categories) > 0 {
+		for iNdEx := len(m.Categories) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.Categories[iNdEx])
+			copy(dAtA[i:], m.Categories[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.Categories[iNdEx])))
+			i--
+			dAtA[i] = 0x32
+		}
+	}
+	i -= len(m.ListKind)
+	copy(dAtA[i:], m.ListKind)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.ListKind)))
+	i--
+	dAtA[i] = 0x2a
+	i -= len(m.Kind)
+	copy(dAtA[i:], m.Kind)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind)))
+	i--
+	dAtA[i] = 0x22
+	if len(m.ShortNames) > 0 {
+		for iNdEx := len(m.ShortNames) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.ShortNames[iNdEx])
+			copy(dAtA[i:], m.ShortNames[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.ShortNames[iNdEx])))
+			i--
+			dAtA[i] = 0x1a
+		}
+	}
+	i -= len(m.Singular)
+	copy(dAtA[i:], m.Singular)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Singular)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Plural)
+	copy(dAtA[i:], m.Plural)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Plural)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionSpec) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionSpec) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.SelectableFields) > 0 {
+		for iNdEx := len(m.SelectableFields) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.SelectableFields[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x5a
+		}
+	}
+	if m.PreserveUnknownFields != nil {
+		i--
+		if *m.PreserveUnknownFields {
+			dAtA[i] = 1
+		} else {
+			dAtA[i] = 0
+		}
+		i--
+		dAtA[i] = 0x50
+	}
+	if m.Conversion != nil {
+		{
+			size, err := m.Conversion.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x4a
+	}
+	if len(m.AdditionalPrinterColumns) > 0 {
+		for iNdEx := len(m.AdditionalPrinterColumns) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.AdditionalPrinterColumns[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x42
+		}
+	}
+	if len(m.Versions) > 0 {
+		for iNdEx := len(m.Versions) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Versions[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x3a
+		}
+	}
+	if m.Subresources != nil {
+		{
+			size, err := m.Subresources.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x32
+	}
+	if m.Validation != nil {
+		{
+			size, err := m.Validation.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x2a
+	}
+	i -= len(m.Scope)
+	copy(dAtA[i:], m.Scope)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Scope)))
+	i--
+	dAtA[i] = 0x22
+	{
+		size, err := m.Names.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x1a
+	i -= len(m.Version)
+	copy(dAtA[i:], m.Version)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Version)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Group)
+	copy(dAtA[i:], m.Group)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Group)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionStatus) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionStatus) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.StoredVersions) > 0 {
+		for iNdEx := len(m.StoredVersions) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.StoredVersions[iNdEx])
+			copy(dAtA[i:], m.StoredVersions[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.StoredVersions[iNdEx])))
+			i--
+			dAtA[i] = 0x1a
+		}
+	}
+	{
+		size, err := m.AcceptedNames.MarshalToSizedBuffer(dAtA[:i])
+		if err != nil {
+			return 0, err
+		}
+		i -= size
+		i = encodeVarintGenerated(dAtA, i, uint64(size))
+	}
+	i--
+	dAtA[i] = 0x12
+	if len(m.Conditions) > 0 {
+		for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0xa
+		}
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceDefinitionVersion) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceDefinitionVersion) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceDefinitionVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.SelectableFields) > 0 {
+		for iNdEx := len(m.SelectableFields) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.SelectableFields[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x4a
+		}
+	}
+	if m.DeprecationWarning != nil {
+		i -= len(*m.DeprecationWarning)
+		copy(dAtA[i:], *m.DeprecationWarning)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.DeprecationWarning)))
+		i--
+		dAtA[i] = 0x42
+	}
+	i--
+	if m.Deprecated {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x38
+	if len(m.AdditionalPrinterColumns) > 0 {
+		for iNdEx := len(m.AdditionalPrinterColumns) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.AdditionalPrinterColumns[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x32
+		}
+	}
+	if m.Subresources != nil {
+		{
+			size, err := m.Subresources.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x2a
+	}
+	if m.Schema != nil {
+		{
+			size, err := m.Schema.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x22
+	}
+	i--
+	if m.Storage {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x18
+	i--
+	if m.Served {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x10
+	i -= len(m.Name)
+	copy(dAtA[i:], m.Name)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceSubresourceScale) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceSubresourceScale) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceSubresourceScale) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.LabelSelectorPath != nil {
+		i -= len(*m.LabelSelectorPath)
+		copy(dAtA[i:], *m.LabelSelectorPath)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.LabelSelectorPath)))
+		i--
+		dAtA[i] = 0x1a
+	}
+	i -= len(m.StatusReplicasPath)
+	copy(dAtA[i:], m.StatusReplicasPath)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.StatusReplicasPath)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.SpecReplicasPath)
+	copy(dAtA[i:], m.SpecReplicasPath)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.SpecReplicasPath)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceSubresourceStatus) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceSubresourceStatus) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceSubresourceStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceSubresources) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceSubresources) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceSubresources) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.Scale != nil {
+		{
+			size, err := m.Scale.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x12
+	}
+	if m.Status != nil {
+		{
+			size, err := m.Status.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *CustomResourceValidation) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *CustomResourceValidation) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CustomResourceValidation) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.OpenAPIV3Schema != nil {
+		{
+			size, err := m.OpenAPIV3Schema.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *ExternalDocumentation) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ExternalDocumentation) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ExternalDocumentation) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	i -= len(m.URL)
+	copy(dAtA[i:], m.URL)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.URL)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Description)
+	copy(dAtA[i:], m.Description)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *JSON) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *JSON) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *JSON) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.Raw != nil {
+		i -= len(m.Raw)
+		copy(dAtA[i:], m.Raw)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(m.Raw)))
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *JSONSchemaProps) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *JSONSchemaProps) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *JSONSchemaProps) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.XValidations) > 0 {
+		for iNdEx := len(m.XValidations) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.XValidations[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x2
+			i--
+			dAtA[i] = 0xe2
+		}
+	}
+	if m.XMapType != nil {
+		i -= len(*m.XMapType)
+		copy(dAtA[i:], *m.XMapType)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.XMapType)))
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0xda
+	}
+	if m.XListType != nil {
+		i -= len(*m.XListType)
+		copy(dAtA[i:], *m.XListType)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.XListType)))
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0xd2
+	}
+	if len(m.XListMapKeys) > 0 {
+		for iNdEx := len(m.XListMapKeys) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.XListMapKeys[iNdEx])
+			copy(dAtA[i:], m.XListMapKeys[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.XListMapKeys[iNdEx])))
+			i--
+			dAtA[i] = 0x2
+			i--
+			dAtA[i] = 0xca
+		}
+	}
+	i--
+	if m.XIntOrString {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x2
+	i--
+	dAtA[i] = 0xc0
+	i--
+	if m.XEmbeddedResource {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x2
+	i--
+	dAtA[i] = 0xb8
+	if m.XPreserveUnknownFields != nil {
+		i--
+		if *m.XPreserveUnknownFields {
+			dAtA[i] = 1
+		} else {
+			dAtA[i] = 0
+		}
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0xb0
+	}
+	i--
+	if m.Nullable {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x2
+	i--
+	dAtA[i] = 0xa8
+	if m.Example != nil {
+		{
+			size, err := m.Example.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0xa2
+	}
+	if m.ExternalDocs != nil {
+		{
+			size, err := m.ExternalDocs.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0x9a
+	}
+	if len(m.Definitions) > 0 {
+		keysForDefinitions := make([]string, 0, len(m.Definitions))
+		for k := range m.Definitions {
+			keysForDefinitions = append(keysForDefinitions, string(k))
+		}
+		github_com_gogo_protobuf_sortkeys.Strings(keysForDefinitions)
+		for iNdEx := len(keysForDefinitions) - 1; iNdEx >= 0; iNdEx-- {
+			v := m.Definitions[string(keysForDefinitions[iNdEx])]
+			baseI := i
+			{
+				size, err := (&v).MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+			i -= len(keysForDefinitions[iNdEx])
+			copy(dAtA[i:], keysForDefinitions[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(keysForDefinitions[iNdEx])))
+			i--
+			dAtA[i] = 0xa
+			i = encodeVarintGenerated(dAtA, i, uint64(baseI-i))
+			i--
+			dAtA[i] = 0x2
+			i--
+			dAtA[i] = 0x92
+		}
+	}
+	if m.AdditionalItems != nil {
+		{
+			size, err := m.AdditionalItems.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x2
+		i--
+		dAtA[i] = 0x8a
+	}
+	if len(m.Dependencies) > 0 {
+		keysForDependencies := make([]string, 0, len(m.Dependencies))
+		for k := range m.Dependencies {
+			keysForDependencies = append(keysForDependencies, string(k))
+		}
+		github_com_gogo_protobuf_sortkeys.Strings(keysForDependencies)
+		for iNdEx := len(keysForDependencies) - 1; iNdEx >= 0; iNdEx-- {
+			v := m.Dependencies[string(keysForDependencies[iNdEx])]
+			baseI := i
+			{
+				size, err := (&v).MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+			i -= len(keysForDependencies[iNdEx])
+			copy(dAtA[i:], keysForDependencies[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(keysForDependencies[iNdEx])))
+			i--
+			dAtA[i] = 0xa
+			i = encodeVarintGenerated(dAtA, i, uint64(baseI-i))
+			i--
+			dAtA[i] = 0x2
+			i--
+			dAtA[i] = 0x82
+		}
+	}
+	if len(m.PatternProperties) > 0 {
+		keysForPatternProperties := make([]string, 0, len(m.PatternProperties))
+		for k := range m.PatternProperties {
+			keysForPatternProperties = append(keysForPatternProperties, string(k))
+		}
+		github_com_gogo_protobuf_sortkeys.Strings(keysForPatternProperties)
+		for iNdEx := len(keysForPatternProperties) - 1; iNdEx >= 0; iNdEx-- {
+			v := m.PatternProperties[string(keysForPatternProperties[iNdEx])]
+			baseI := i
+			{
+				size, err := (&v).MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+			i -= len(keysForPatternProperties[iNdEx])
+			copy(dAtA[i:], keysForPatternProperties[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(keysForPatternProperties[iNdEx])))
+			i--
+			dAtA[i] = 0xa
+			i = encodeVarintGenerated(dAtA, i, uint64(baseI-i))
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xfa
+		}
+	}
+	if m.AdditionalProperties != nil {
+		{
+			size, err := m.AdditionalProperties.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0xf2
+	}
+	if len(m.Properties) > 0 {
+		keysForProperties := make([]string, 0, len(m.Properties))
+		for k := range m.Properties {
+			keysForProperties = append(keysForProperties, string(k))
+		}
+		github_com_gogo_protobuf_sortkeys.Strings(keysForProperties)
+		for iNdEx := len(keysForProperties) - 1; iNdEx >= 0; iNdEx-- {
+			v := m.Properties[string(keysForProperties[iNdEx])]
+			baseI := i
+			{
+				size, err := (&v).MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+			i -= len(keysForProperties[iNdEx])
+			copy(dAtA[i:], keysForProperties[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(keysForProperties[iNdEx])))
+			i--
+			dAtA[i] = 0xa
+			i = encodeVarintGenerated(dAtA, i, uint64(baseI-i))
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xea
+		}
+	}
+	if m.Not != nil {
+		{
+			size, err := m.Not.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0xe2
+	}
+	if len(m.AnyOf) > 0 {
+		for iNdEx := len(m.AnyOf) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.AnyOf[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xda
+		}
+	}
+	if len(m.OneOf) > 0 {
+		for iNdEx := len(m.OneOf) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.OneOf[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xd2
+		}
+	}
+	if len(m.AllOf) > 0 {
+		for iNdEx := len(m.AllOf) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.AllOf[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xca
+		}
+	}
+	if m.Items != nil {
+		{
+			size, err := m.Items.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0xc2
+	}
+	if len(m.Required) > 0 {
+		for iNdEx := len(m.Required) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.Required[iNdEx])
+			copy(dAtA[i:], m.Required[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.Required[iNdEx])))
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xba
+		}
+	}
+	if m.MinProperties != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MinProperties))
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0xb0
+	}
+	if m.MaxProperties != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MaxProperties))
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0xa8
+	}
+	if len(m.Enum) > 0 {
+		for iNdEx := len(m.Enum) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Enum[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x1
+			i--
+			dAtA[i] = 0xa2
+		}
+	}
+	if m.MultipleOf != nil {
+		i -= 8
+		encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(*m.MultipleOf))))
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0x99
+	}
+	i--
+	if m.UniqueItems {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x1
+	i--
+	dAtA[i] = 0x90
+	if m.MinItems != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MinItems))
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0x88
+	}
+	if m.MaxItems != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MaxItems))
+		i--
+		dAtA[i] = 0x1
+		i--
+		dAtA[i] = 0x80
+	}
+	i -= len(m.Pattern)
+	copy(dAtA[i:], m.Pattern)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Pattern)))
+	i--
+	dAtA[i] = 0x7a
+	if m.MinLength != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MinLength))
+		i--
+		dAtA[i] = 0x70
+	}
+	if m.MaxLength != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.MaxLength))
+		i--
+		dAtA[i] = 0x68
+	}
+	i--
+	if m.ExclusiveMinimum {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x60
+	if m.Minimum != nil {
+		i -= 8
+		encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(*m.Minimum))))
+		i--
+		dAtA[i] = 0x59
+	}
+	i--
+	if m.ExclusiveMaximum {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x50
+	if m.Maximum != nil {
+		i -= 8
+		encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(*m.Maximum))))
+		i--
+		dAtA[i] = 0x49
+	}
+	if m.Default != nil {
+		{
+			size, err := m.Default.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x42
+	}
+	i -= len(m.Title)
+	copy(dAtA[i:], m.Title)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Title)))
+	i--
+	dAtA[i] = 0x3a
+	i -= len(m.Format)
+	copy(dAtA[i:], m.Format)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Format)))
+	i--
+	dAtA[i] = 0x32
+	i -= len(m.Type)
+	copy(dAtA[i:], m.Type)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type)))
+	i--
+	dAtA[i] = 0x2a
+	i -= len(m.Description)
+	copy(dAtA[i:], m.Description)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description)))
+	i--
+	dAtA[i] = 0x22
+	if m.Ref != nil {
+		i -= len(*m.Ref)
+		copy(dAtA[i:], *m.Ref)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Ref)))
+		i--
+		dAtA[i] = 0x1a
+	}
+	i -= len(m.Schema)
+	copy(dAtA[i:], m.Schema)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Schema)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.ID)
+	copy(dAtA[i:], m.ID)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.ID)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *JSONSchemaPropsOrArray) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *JSONSchemaPropsOrArray) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *JSONSchemaPropsOrArray) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.JSONSchemas) > 0 {
+		for iNdEx := len(m.JSONSchemas) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.JSONSchemas[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenerated(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0x12
+		}
+	}
+	if m.Schema != nil {
+		{
+			size, err := m.Schema.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *JSONSchemaPropsOrBool) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *JSONSchemaPropsOrBool) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *JSONSchemaPropsOrBool) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.Schema != nil {
+		{
+			size, err := m.Schema.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0x12
+	}
+	i--
+	if m.Allows {
+		dAtA[i] = 1
+	} else {
+		dAtA[i] = 0
+	}
+	i--
+	dAtA[i] = 0x8
+	return len(dAtA) - i, nil
+}
+
+func (m *JSONSchemaPropsOrStringArray) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *JSONSchemaPropsOrStringArray) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *JSONSchemaPropsOrStringArray) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if len(m.Property) > 0 {
+		for iNdEx := len(m.Property) - 1; iNdEx >= 0; iNdEx-- {
+			i -= len(m.Property[iNdEx])
+			copy(dAtA[i:], m.Property[iNdEx])
+			i = encodeVarintGenerated(dAtA, i, uint64(len(m.Property[iNdEx])))
+			i--
+			dAtA[i] = 0x12
+		}
+	}
+	if m.Schema != nil {
+		{
+			size, err := m.Schema.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func (m *SelectableField) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *SelectableField) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *SelectableField) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	i -= len(m.JSONPath)
+	copy(dAtA[i:], m.JSONPath)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.JSONPath)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *ServiceReference) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ServiceReference) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ServiceReference) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.Port != nil {
+		i = encodeVarintGenerated(dAtA, i, uint64(*m.Port))
+		i--
+		dAtA[i] = 0x20
+	}
+	if m.Path != nil {
+		i -= len(*m.Path)
+		copy(dAtA[i:], *m.Path)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Path)))
+		i--
+		dAtA[i] = 0x1a
+	}
+	i -= len(m.Name)
+	copy(dAtA[i:], m.Name)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Namespace)
+	copy(dAtA[i:], m.Namespace)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Namespace)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *ValidationRule) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *ValidationRule) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *ValidationRule) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.OptionalOldSelf != nil {
+		i--
+		if *m.OptionalOldSelf {
+			dAtA[i] = 1
+		} else {
+			dAtA[i] = 0
+		}
+		i--
+		dAtA[i] = 0x30
+	}
+	i -= len(m.FieldPath)
+	copy(dAtA[i:], m.FieldPath)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.FieldPath)))
+	i--
+	dAtA[i] = 0x2a
+	if m.Reason != nil {
+		i -= len(*m.Reason)
+		copy(dAtA[i:], *m.Reason)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Reason)))
+		i--
+		dAtA[i] = 0x22
+	}
+	i -= len(m.MessageExpression)
+	copy(dAtA[i:], m.MessageExpression)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.MessageExpression)))
+	i--
+	dAtA[i] = 0x1a
+	i -= len(m.Message)
+	copy(dAtA[i:], m.Message)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message)))
+	i--
+	dAtA[i] = 0x12
+	i -= len(m.Rule)
+	copy(dAtA[i:], m.Rule)
+	i = encodeVarintGenerated(dAtA, i, uint64(len(m.Rule)))
+	i--
+	dAtA[i] = 0xa
+	return len(dAtA) - i, nil
+}
+
+func (m *WebhookClientConfig) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *WebhookClientConfig) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *WebhookClientConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.URL != nil {
+		i -= len(*m.URL)
+		copy(dAtA[i:], *m.URL)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.URL)))
+		i--
+		dAtA[i] = 0x1a
+	}
+	if m.CABundle != nil {
+		i -= len(m.CABundle)
+		copy(dAtA[i:], m.CABundle)
+		i = encodeVarintGenerated(dAtA, i, uint64(len(m.CABundle)))
+		i--
+		dAtA[i] = 0x12
+	}
+	if m.Service != nil {
+		{
+			size, err := m.Service.MarshalToSizedBuffer(dAtA[:i])
+			if err != nil {
+				return 0, err
+			}
+			i -= size
+			i = encodeVarintGenerated(dAtA, i, uint64(size))
+		}
+		i--
+		dAtA[i] = 0xa
+	}
+	return len(dAtA) - i, nil
+}
+
+func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
+	offset -= sovGenerated(v)
+	base := offset
+	for v >= 1<<7 {
+		dAtA[offset] = uint8(v&0x7f | 0x80)
+		v >>= 7
+		offset++
+	}
+	dAtA[offset] = uint8(v)
+	return base
+}
+func (m *ConversionRequest) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.UID)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.DesiredAPIVersion)
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.Objects) > 0 {
+		for _, e := range m.Objects {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *ConversionResponse) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.UID)
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.ConvertedObjects) > 0 {
+		for _, e := range m.ConvertedObjects {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	l = m.Result.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *ConversionReview) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Request != nil {
+		l = m.Request.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Response != nil {
+		l = m.Response.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *CustomResourceColumnDefinition) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Name)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Type)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Format)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Description)
+	n += 1 + l + sovGenerated(uint64(l))
+	n += 1 + sovGenerated(uint64(m.Priority))
+	l = len(m.JSONPath)
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *CustomResourceConversion) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Strategy)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.WebhookClientConfig != nil {
+		l = m.WebhookClientConfig.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.ConversionReviewVersions) > 0 {
+		for _, s := range m.ConversionReviewVersions {
+			l = len(s)
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceDefinition) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = m.ObjectMeta.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	l = m.Spec.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	l = m.Status.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *CustomResourceDefinitionCondition) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Type)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Status)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = m.LastTransitionTime.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Reason)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Message)
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *CustomResourceDefinitionList) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = m.ListMeta.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.Items) > 0 {
+		for _, e := range m.Items {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceDefinitionNames) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Plural)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Singular)
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.ShortNames) > 0 {
+		for _, s := range m.ShortNames {
+			l = len(s)
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	l = len(m.Kind)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.ListKind)
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.Categories) > 0 {
+		for _, s := range m.Categories {
+			l = len(s)
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceDefinitionSpec) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Group)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Version)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = m.Names.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Scope)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.Validation != nil {
+		l = m.Validation.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Subresources != nil {
+		l = m.Subresources.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.Versions) > 0 {
+		for _, e := range m.Versions {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	if len(m.AdditionalPrinterColumns) > 0 {
+		for _, e := range m.AdditionalPrinterColumns {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	if m.Conversion != nil {
+		l = m.Conversion.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.PreserveUnknownFields != nil {
+		n += 2
+	}
+	if len(m.SelectableFields) > 0 {
+		for _, e := range m.SelectableFields {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceDefinitionStatus) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if len(m.Conditions) > 0 {
+		for _, e := range m.Conditions {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	l = m.AcceptedNames.Size()
+	n += 1 + l + sovGenerated(uint64(l))
+	if len(m.StoredVersions) > 0 {
+		for _, s := range m.StoredVersions {
+			l = len(s)
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceDefinitionVersion) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Name)
+	n += 1 + l + sovGenerated(uint64(l))
+	n += 2
+	n += 2
+	if m.Schema != nil {
+		l = m.Schema.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Subresources != nil {
+		l = m.Subresources.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.AdditionalPrinterColumns) > 0 {
+		for _, e := range m.AdditionalPrinterColumns {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	n += 2
+	if m.DeprecationWarning != nil {
+		l = len(*m.DeprecationWarning)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.SelectableFields) > 0 {
+		for _, e := range m.SelectableFields {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *CustomResourceSubresourceScale) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.SpecReplicasPath)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.StatusReplicasPath)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.LabelSelectorPath != nil {
+		l = len(*m.LabelSelectorPath)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *CustomResourceSubresourceStatus) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	return n
+}
+
+func (m *CustomResourceSubresources) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Status != nil {
+		l = m.Status.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Scale != nil {
+		l = m.Scale.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *CustomResourceValidation) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.OpenAPIV3Schema != nil {
+		l = m.OpenAPIV3Schema.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *ExternalDocumentation) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Description)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.URL)
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *JSON) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Raw != nil {
+		l = len(m.Raw)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *JSONSchemaProps) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.ID)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Schema)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.Ref != nil {
+		l = len(*m.Ref)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	l = len(m.Description)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Type)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Format)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Title)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.Default != nil {
+		l = m.Default.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Maximum != nil {
+		n += 9
+	}
+	n += 2
+	if m.Minimum != nil {
+		n += 9
+	}
+	n += 2
+	if m.MaxLength != nil {
+		n += 1 + sovGenerated(uint64(*m.MaxLength))
+	}
+	if m.MinLength != nil {
+		n += 1 + sovGenerated(uint64(*m.MinLength))
+	}
+	l = len(m.Pattern)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.MaxItems != nil {
+		n += 2 + sovGenerated(uint64(*m.MaxItems))
+	}
+	if m.MinItems != nil {
+		n += 2 + sovGenerated(uint64(*m.MinItems))
+	}
+	n += 3
+	if m.MultipleOf != nil {
+		n += 10
+	}
+	if len(m.Enum) > 0 {
+		for _, e := range m.Enum {
+			l = e.Size()
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if m.MaxProperties != nil {
+		n += 2 + sovGenerated(uint64(*m.MaxProperties))
+	}
+	if m.MinProperties != nil {
+		n += 2 + sovGenerated(uint64(*m.MinProperties))
+	}
+	if len(m.Required) > 0 {
+		for _, s := range m.Required {
+			l = len(s)
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if m.Items != nil {
+		l = m.Items.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if len(m.AllOf) > 0 {
+		for _, e := range m.AllOf {
+			l = e.Size()
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if len(m.OneOf) > 0 {
+		for _, e := range m.OneOf {
+			l = e.Size()
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if len(m.AnyOf) > 0 {
+		for _, e := range m.AnyOf {
+			l = e.Size()
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if m.Not != nil {
+		l = m.Not.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if len(m.Properties) > 0 {
+		for k, v := range m.Properties {
+			_ = k
+			_ = v
+			l = v.Size()
+			mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l))
+			n += mapEntrySize + 2 + sovGenerated(uint64(mapEntrySize))
+		}
+	}
+	if m.AdditionalProperties != nil {
+		l = m.AdditionalProperties.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if len(m.PatternProperties) > 0 {
+		for k, v := range m.PatternProperties {
+			_ = k
+			_ = v
+			l = v.Size()
+			mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l))
+			n += mapEntrySize + 2 + sovGenerated(uint64(mapEntrySize))
+		}
+	}
+	if len(m.Dependencies) > 0 {
+		for k, v := range m.Dependencies {
+			_ = k
+			_ = v
+			l = v.Size()
+			mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l))
+			n += mapEntrySize + 2 + sovGenerated(uint64(mapEntrySize))
+		}
+	}
+	if m.AdditionalItems != nil {
+		l = m.AdditionalItems.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if len(m.Definitions) > 0 {
+		for k, v := range m.Definitions {
+			_ = k
+			_ = v
+			l = v.Size()
+			mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l))
+			n += mapEntrySize + 2 + sovGenerated(uint64(mapEntrySize))
+		}
+	}
+	if m.ExternalDocs != nil {
+		l = m.ExternalDocs.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if m.Example != nil {
+		l = m.Example.Size()
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	n += 3
+	if m.XPreserveUnknownFields != nil {
+		n += 3
+	}
+	n += 3
+	n += 3
+	if len(m.XListMapKeys) > 0 {
+		for _, s := range m.XListMapKeys {
+			l = len(s)
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	if m.XListType != nil {
+		l = len(*m.XListType)
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if m.XMapType != nil {
+		l = len(*m.XMapType)
+		n += 2 + l + sovGenerated(uint64(l))
+	}
+	if len(m.XValidations) > 0 {
+		for _, e := range m.XValidations {
+			l = e.Size()
+			n += 2 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *JSONSchemaPropsOrArray) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Schema != nil {
+		l = m.Schema.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.JSONSchemas) > 0 {
+		for _, e := range m.JSONSchemas {
+			l = e.Size()
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *JSONSchemaPropsOrBool) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	n += 2
+	if m.Schema != nil {
+		l = m.Schema.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func (m *JSONSchemaPropsOrStringArray) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Schema != nil {
+		l = m.Schema.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if len(m.Property) > 0 {
+		for _, s := range m.Property {
+			l = len(s)
+			n += 1 + l + sovGenerated(uint64(l))
+		}
+	}
+	return n
+}
+
+func (m *SelectableField) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.JSONPath)
+	n += 1 + l + sovGenerated(uint64(l))
+	return n
+}
+
+func (m *ServiceReference) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Namespace)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Name)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.Path != nil {
+		l = len(*m.Path)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.Port != nil {
+		n += 1 + sovGenerated(uint64(*m.Port))
+	}
+	return n
+}
+
+func (m *ValidationRule) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	l = len(m.Rule)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.Message)
+	n += 1 + l + sovGenerated(uint64(l))
+	l = len(m.MessageExpression)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.Reason != nil {
+		l = len(*m.Reason)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	l = len(m.FieldPath)
+	n += 1 + l + sovGenerated(uint64(l))
+	if m.OptionalOldSelf != nil {
+		n += 2
+	}
+	return n
+}
+
+func (m *WebhookClientConfig) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if m.Service != nil {
+		l = m.Service.Size()
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.CABundle != nil {
+		l = len(m.CABundle)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	if m.URL != nil {
+		l = len(*m.URL)
+		n += 1 + l + sovGenerated(uint64(l))
+	}
+	return n
+}
+
+func sovGenerated(x uint64) (n int) {
+	return (math_bits.Len64(x|1) + 6) / 7
+}
+func sozGenerated(x uint64) (n int) {
+	return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *ConversionRequest) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForObjects := "[]RawExtension{"
+	for _, f := range this.Objects {
+		repeatedStringForObjects += fmt.Sprintf("%v", f) + ","
+	}
+	repeatedStringForObjects += "}"
+	s := strings.Join([]string{`&ConversionRequest{`,
+		`UID:` + fmt.Sprintf("%v", this.UID) + `,`,
+		`DesiredAPIVersion:` + fmt.Sprintf("%v", this.DesiredAPIVersion) + `,`,
+		`Objects:` + repeatedStringForObjects + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *ConversionResponse) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForConvertedObjects := "[]RawExtension{"
+	for _, f := range this.ConvertedObjects {
+		repeatedStringForConvertedObjects += fmt.Sprintf("%v", f) + ","
+	}
+	repeatedStringForConvertedObjects += "}"
+	s := strings.Join([]string{`&ConversionResponse{`,
+		`UID:` + fmt.Sprintf("%v", this.UID) + `,`,
+		`ConvertedObjects:` + repeatedStringForConvertedObjects + `,`,
+		`Result:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Result), "Status", "v1.Status", 1), `&`, ``, 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *ConversionReview) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&ConversionReview{`,
+		`Request:` + strings.Replace(this.Request.String(), "ConversionRequest", "ConversionRequest", 1) + `,`,
+		`Response:` + strings.Replace(this.Response.String(), "ConversionResponse", "ConversionResponse", 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceColumnDefinition) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceColumnDefinition{`,
+		`Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+		`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+		`Format:` + fmt.Sprintf("%v", this.Format) + `,`,
+		`Description:` + fmt.Sprintf("%v", this.Description) + `,`,
+		`Priority:` + fmt.Sprintf("%v", this.Priority) + `,`,
+		`JSONPath:` + fmt.Sprintf("%v", this.JSONPath) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceConversion) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceConversion{`,
+		`Strategy:` + fmt.Sprintf("%v", this.Strategy) + `,`,
+		`WebhookClientConfig:` + strings.Replace(this.WebhookClientConfig.String(), "WebhookClientConfig", "WebhookClientConfig", 1) + `,`,
+		`ConversionReviewVersions:` + fmt.Sprintf("%v", this.ConversionReviewVersions) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinition) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceDefinition{`,
+		`ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`,
+		`Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CustomResourceDefinitionSpec", "CustomResourceDefinitionSpec", 1), `&`, ``, 1) + `,`,
+		`Status:` + strings.Replace(strings.Replace(this.Status.String(), "CustomResourceDefinitionStatus", "CustomResourceDefinitionStatus", 1), `&`, ``, 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionCondition) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceDefinitionCondition{`,
+		`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+		`Status:` + fmt.Sprintf("%v", this.Status) + `,`,
+		`LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`,
+		`Reason:` + fmt.Sprintf("%v", this.Reason) + `,`,
+		`Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionList) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForItems := "[]CustomResourceDefinition{"
+	for _, f := range this.Items {
+		repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "CustomResourceDefinition", "CustomResourceDefinition", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForItems += "}"
+	s := strings.Join([]string{`&CustomResourceDefinitionList{`,
+		`ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`,
+		`Items:` + repeatedStringForItems + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionNames) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceDefinitionNames{`,
+		`Plural:` + fmt.Sprintf("%v", this.Plural) + `,`,
+		`Singular:` + fmt.Sprintf("%v", this.Singular) + `,`,
+		`ShortNames:` + fmt.Sprintf("%v", this.ShortNames) + `,`,
+		`Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+		`ListKind:` + fmt.Sprintf("%v", this.ListKind) + `,`,
+		`Categories:` + fmt.Sprintf("%v", this.Categories) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionSpec) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForVersions := "[]CustomResourceDefinitionVersion{"
+	for _, f := range this.Versions {
+		repeatedStringForVersions += strings.Replace(strings.Replace(f.String(), "CustomResourceDefinitionVersion", "CustomResourceDefinitionVersion", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForVersions += "}"
+	repeatedStringForAdditionalPrinterColumns := "[]CustomResourceColumnDefinition{"
+	for _, f := range this.AdditionalPrinterColumns {
+		repeatedStringForAdditionalPrinterColumns += strings.Replace(strings.Replace(f.String(), "CustomResourceColumnDefinition", "CustomResourceColumnDefinition", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForAdditionalPrinterColumns += "}"
+	repeatedStringForSelectableFields := "[]SelectableField{"
+	for _, f := range this.SelectableFields {
+		repeatedStringForSelectableFields += strings.Replace(strings.Replace(f.String(), "SelectableField", "SelectableField", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForSelectableFields += "}"
+	s := strings.Join([]string{`&CustomResourceDefinitionSpec{`,
+		`Group:` + fmt.Sprintf("%v", this.Group) + `,`,
+		`Version:` + fmt.Sprintf("%v", this.Version) + `,`,
+		`Names:` + strings.Replace(strings.Replace(this.Names.String(), "CustomResourceDefinitionNames", "CustomResourceDefinitionNames", 1), `&`, ``, 1) + `,`,
+		`Scope:` + fmt.Sprintf("%v", this.Scope) + `,`,
+		`Validation:` + strings.Replace(this.Validation.String(), "CustomResourceValidation", "CustomResourceValidation", 1) + `,`,
+		`Subresources:` + strings.Replace(this.Subresources.String(), "CustomResourceSubresources", "CustomResourceSubresources", 1) + `,`,
+		`Versions:` + repeatedStringForVersions + `,`,
+		`AdditionalPrinterColumns:` + repeatedStringForAdditionalPrinterColumns + `,`,
+		`Conversion:` + strings.Replace(this.Conversion.String(), "CustomResourceConversion", "CustomResourceConversion", 1) + `,`,
+		`PreserveUnknownFields:` + valueToStringGenerated(this.PreserveUnknownFields) + `,`,
+		`SelectableFields:` + repeatedStringForSelectableFields + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionStatus) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForConditions := "[]CustomResourceDefinitionCondition{"
+	for _, f := range this.Conditions {
+		repeatedStringForConditions += strings.Replace(strings.Replace(f.String(), "CustomResourceDefinitionCondition", "CustomResourceDefinitionCondition", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForConditions += "}"
+	s := strings.Join([]string{`&CustomResourceDefinitionStatus{`,
+		`Conditions:` + repeatedStringForConditions + `,`,
+		`AcceptedNames:` + strings.Replace(strings.Replace(this.AcceptedNames.String(), "CustomResourceDefinitionNames", "CustomResourceDefinitionNames", 1), `&`, ``, 1) + `,`,
+		`StoredVersions:` + fmt.Sprintf("%v", this.StoredVersions) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceDefinitionVersion) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForAdditionalPrinterColumns := "[]CustomResourceColumnDefinition{"
+	for _, f := range this.AdditionalPrinterColumns {
+		repeatedStringForAdditionalPrinterColumns += strings.Replace(strings.Replace(f.String(), "CustomResourceColumnDefinition", "CustomResourceColumnDefinition", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForAdditionalPrinterColumns += "}"
+	repeatedStringForSelectableFields := "[]SelectableField{"
+	for _, f := range this.SelectableFields {
+		repeatedStringForSelectableFields += strings.Replace(strings.Replace(f.String(), "SelectableField", "SelectableField", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForSelectableFields += "}"
+	s := strings.Join([]string{`&CustomResourceDefinitionVersion{`,
+		`Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+		`Served:` + fmt.Sprintf("%v", this.Served) + `,`,
+		`Storage:` + fmt.Sprintf("%v", this.Storage) + `,`,
+		`Schema:` + strings.Replace(this.Schema.String(), "CustomResourceValidation", "CustomResourceValidation", 1) + `,`,
+		`Subresources:` + strings.Replace(this.Subresources.String(), "CustomResourceSubresources", "CustomResourceSubresources", 1) + `,`,
+		`AdditionalPrinterColumns:` + repeatedStringForAdditionalPrinterColumns + `,`,
+		`Deprecated:` + fmt.Sprintf("%v", this.Deprecated) + `,`,
+		`DeprecationWarning:` + valueToStringGenerated(this.DeprecationWarning) + `,`,
+		`SelectableFields:` + repeatedStringForSelectableFields + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceSubresourceScale) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceSubresourceScale{`,
+		`SpecReplicasPath:` + fmt.Sprintf("%v", this.SpecReplicasPath) + `,`,
+		`StatusReplicasPath:` + fmt.Sprintf("%v", this.StatusReplicasPath) + `,`,
+		`LabelSelectorPath:` + valueToStringGenerated(this.LabelSelectorPath) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceSubresourceStatus) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceSubresourceStatus{`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceSubresources) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceSubresources{`,
+		`Status:` + strings.Replace(this.Status.String(), "CustomResourceSubresourceStatus", "CustomResourceSubresourceStatus", 1) + `,`,
+		`Scale:` + strings.Replace(this.Scale.String(), "CustomResourceSubresourceScale", "CustomResourceSubresourceScale", 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *CustomResourceValidation) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&CustomResourceValidation{`,
+		`OpenAPIV3Schema:` + strings.Replace(this.OpenAPIV3Schema.String(), "JSONSchemaProps", "JSONSchemaProps", 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *ExternalDocumentation) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&ExternalDocumentation{`,
+		`Description:` + fmt.Sprintf("%v", this.Description) + `,`,
+		`URL:` + fmt.Sprintf("%v", this.URL) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *JSON) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&JSON{`,
+		`Raw:` + valueToStringGenerated(this.Raw) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *JSONSchemaProps) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForEnum := "[]JSON{"
+	for _, f := range this.Enum {
+		repeatedStringForEnum += strings.Replace(strings.Replace(f.String(), "JSON", "JSON", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForEnum += "}"
+	repeatedStringForAllOf := "[]JSONSchemaProps{"
+	for _, f := range this.AllOf {
+		repeatedStringForAllOf += strings.Replace(strings.Replace(f.String(), "JSONSchemaProps", "JSONSchemaProps", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForAllOf += "}"
+	repeatedStringForOneOf := "[]JSONSchemaProps{"
+	for _, f := range this.OneOf {
+		repeatedStringForOneOf += strings.Replace(strings.Replace(f.String(), "JSONSchemaProps", "JSONSchemaProps", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForOneOf += "}"
+	repeatedStringForAnyOf := "[]JSONSchemaProps{"
+	for _, f := range this.AnyOf {
+		repeatedStringForAnyOf += strings.Replace(strings.Replace(f.String(), "JSONSchemaProps", "JSONSchemaProps", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForAnyOf += "}"
+	repeatedStringForXValidations := "[]ValidationRule{"
+	for _, f := range this.XValidations {
+		repeatedStringForXValidations += strings.Replace(strings.Replace(f.String(), "ValidationRule", "ValidationRule", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForXValidations += "}"
+	keysForProperties := make([]string, 0, len(this.Properties))
+	for k := range this.Properties {
+		keysForProperties = append(keysForProperties, k)
+	}
+	github_com_gogo_protobuf_sortkeys.Strings(keysForProperties)
+	mapStringForProperties := "map[string]JSONSchemaProps{"
+	for _, k := range keysForProperties {
+		mapStringForProperties += fmt.Sprintf("%v: %v,", k, this.Properties[k])
+	}
+	mapStringForProperties += "}"
+	keysForPatternProperties := make([]string, 0, len(this.PatternProperties))
+	for k := range this.PatternProperties {
+		keysForPatternProperties = append(keysForPatternProperties, k)
+	}
+	github_com_gogo_protobuf_sortkeys.Strings(keysForPatternProperties)
+	mapStringForPatternProperties := "map[string]JSONSchemaProps{"
+	for _, k := range keysForPatternProperties {
+		mapStringForPatternProperties += fmt.Sprintf("%v: %v,", k, this.PatternProperties[k])
+	}
+	mapStringForPatternProperties += "}"
+	keysForDependencies := make([]string, 0, len(this.Dependencies))
+	for k := range this.Dependencies {
+		keysForDependencies = append(keysForDependencies, k)
+	}
+	github_com_gogo_protobuf_sortkeys.Strings(keysForDependencies)
+	mapStringForDependencies := "JSONSchemaDependencies{"
+	for _, k := range keysForDependencies {
+		mapStringForDependencies += fmt.Sprintf("%v: %v,", k, this.Dependencies[k])
+	}
+	mapStringForDependencies += "}"
+	keysForDefinitions := make([]string, 0, len(this.Definitions))
+	for k := range this.Definitions {
+		keysForDefinitions = append(keysForDefinitions, k)
+	}
+	github_com_gogo_protobuf_sortkeys.Strings(keysForDefinitions)
+	mapStringForDefinitions := "JSONSchemaDefinitions{"
+	for _, k := range keysForDefinitions {
+		mapStringForDefinitions += fmt.Sprintf("%v: %v,", k, this.Definitions[k])
+	}
+	mapStringForDefinitions += "}"
+	s := strings.Join([]string{`&JSONSchemaProps{`,
+		`ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+		`Schema:` + fmt.Sprintf("%v", this.Schema) + `,`,
+		`Ref:` + valueToStringGenerated(this.Ref) + `,`,
+		`Description:` + fmt.Sprintf("%v", this.Description) + `,`,
+		`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+		`Format:` + fmt.Sprintf("%v", this.Format) + `,`,
+		`Title:` + fmt.Sprintf("%v", this.Title) + `,`,
+		`Default:` + strings.Replace(this.Default.String(), "JSON", "JSON", 1) + `,`,
+		`Maximum:` + valueToStringGenerated(this.Maximum) + `,`,
+		`ExclusiveMaximum:` + fmt.Sprintf("%v", this.ExclusiveMaximum) + `,`,
+		`Minimum:` + valueToStringGenerated(this.Minimum) + `,`,
+		`ExclusiveMinimum:` + fmt.Sprintf("%v", this.ExclusiveMinimum) + `,`,
+		`MaxLength:` + valueToStringGenerated(this.MaxLength) + `,`,
+		`MinLength:` + valueToStringGenerated(this.MinLength) + `,`,
+		`Pattern:` + fmt.Sprintf("%v", this.Pattern) + `,`,
+		`MaxItems:` + valueToStringGenerated(this.MaxItems) + `,`,
+		`MinItems:` + valueToStringGenerated(this.MinItems) + `,`,
+		`UniqueItems:` + fmt.Sprintf("%v", this.UniqueItems) + `,`,
+		`MultipleOf:` + valueToStringGenerated(this.MultipleOf) + `,`,
+		`Enum:` + repeatedStringForEnum + `,`,
+		`MaxProperties:` + valueToStringGenerated(this.MaxProperties) + `,`,
+		`MinProperties:` + valueToStringGenerated(this.MinProperties) + `,`,
+		`Required:` + fmt.Sprintf("%v", this.Required) + `,`,
+		`Items:` + strings.Replace(this.Items.String(), "JSONSchemaPropsOrArray", "JSONSchemaPropsOrArray", 1) + `,`,
+		`AllOf:` + repeatedStringForAllOf + `,`,
+		`OneOf:` + repeatedStringForOneOf + `,`,
+		`AnyOf:` + repeatedStringForAnyOf + `,`,
+		`Not:` + strings.Replace(this.Not.String(), "JSONSchemaProps", "JSONSchemaProps", 1) + `,`,
+		`Properties:` + mapStringForProperties + `,`,
+		`AdditionalProperties:` + strings.Replace(this.AdditionalProperties.String(), "JSONSchemaPropsOrBool", "JSONSchemaPropsOrBool", 1) + `,`,
+		`PatternProperties:` + mapStringForPatternProperties + `,`,
+		`Dependencies:` + mapStringForDependencies + `,`,
+		`AdditionalItems:` + strings.Replace(this.AdditionalItems.String(), "JSONSchemaPropsOrBool", "JSONSchemaPropsOrBool", 1) + `,`,
+		`Definitions:` + mapStringForDefinitions + `,`,
+		`ExternalDocs:` + strings.Replace(this.ExternalDocs.String(), "ExternalDocumentation", "ExternalDocumentation", 1) + `,`,
+		`Example:` + strings.Replace(this.Example.String(), "JSON", "JSON", 1) + `,`,
+		`Nullable:` + fmt.Sprintf("%v", this.Nullable) + `,`,
+		`XPreserveUnknownFields:` + valueToStringGenerated(this.XPreserveUnknownFields) + `,`,
+		`XEmbeddedResource:` + fmt.Sprintf("%v", this.XEmbeddedResource) + `,`,
+		`XIntOrString:` + fmt.Sprintf("%v", this.XIntOrString) + `,`,
+		`XListMapKeys:` + fmt.Sprintf("%v", this.XListMapKeys) + `,`,
+		`XListType:` + valueToStringGenerated(this.XListType) + `,`,
+		`XMapType:` + valueToStringGenerated(this.XMapType) + `,`,
+		`XValidations:` + repeatedStringForXValidations + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *JSONSchemaPropsOrArray) String() string {
+	if this == nil {
+		return "nil"
+	}
+	repeatedStringForJSONSchemas := "[]JSONSchemaProps{"
+	for _, f := range this.JSONSchemas {
+		repeatedStringForJSONSchemas += strings.Replace(strings.Replace(f.String(), "JSONSchemaProps", "JSONSchemaProps", 1), `&`, ``, 1) + ","
+	}
+	repeatedStringForJSONSchemas += "}"
+	s := strings.Join([]string{`&JSONSchemaPropsOrArray{`,
+		`Schema:` + strings.Replace(this.Schema.String(), "JSONSchemaProps", "JSONSchemaProps", 1) + `,`,
+		`JSONSchemas:` + repeatedStringForJSONSchemas + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *JSONSchemaPropsOrBool) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&JSONSchemaPropsOrBool{`,
+		`Allows:` + fmt.Sprintf("%v", this.Allows) + `,`,
+		`Schema:` + strings.Replace(this.Schema.String(), "JSONSchemaProps", "JSONSchemaProps", 1) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *JSONSchemaPropsOrStringArray) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&JSONSchemaPropsOrStringArray{`,
+		`Schema:` + strings.Replace(this.Schema.String(), "JSONSchemaProps", "JSONSchemaProps", 1) + `,`,
+		`Property:` + fmt.Sprintf("%v", this.Property) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *SelectableField) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&SelectableField{`,
+		`JSONPath:` + fmt.Sprintf("%v", this.JSONPath) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *ServiceReference) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&ServiceReference{`,
+		`Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`,
+		`Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+		`Path:` + valueToStringGenerated(this.Path) + `,`,
+		`Port:` + valueToStringGenerated(this.Port) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *ValidationRule) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&ValidationRule{`,
+		`Rule:` + fmt.Sprintf("%v", this.Rule) + `,`,
+		`Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+		`MessageExpression:` + fmt.Sprintf("%v", this.MessageExpression) + `,`,
+		`Reason:` + valueToStringGenerated(this.Reason) + `,`,
+		`FieldPath:` + fmt.Sprintf("%v", this.FieldPath) + `,`,
+		`OptionalOldSelf:` + valueToStringGenerated(this.OptionalOldSelf) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func (this *WebhookClientConfig) String() string {
+	if this == nil {
+		return "nil"
+	}
+	s := strings.Join([]string{`&WebhookClientConfig{`,
+		`Service:` + strings.Replace(this.Service.String(), "ServiceReference", "ServiceReference", 1) + `,`,
+		`CABundle:` + valueToStringGenerated(this.CABundle) + `,`,
+		`URL:` + valueToStringGenerated(this.URL) + `,`,
+		`}`,
+	}, "")
+	return s
+}
+func valueToStringGenerated(v interface{}) string {
+	rv := reflect.ValueOf(v)
+	if rv.IsNil() {
+		return "nil"
+	}
+	pv := reflect.Indirect(rv).Interface()
+	return fmt.Sprintf("*%v", pv)
+}
+func (m *ConversionRequest) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ConversionRequest: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ConversionRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field DesiredAPIVersion", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.DesiredAPIVersion = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Objects", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Objects = append(m.Objects, runtime.RawExtension{})
+			if err := m.Objects[len(m.Objects)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *ConversionResponse) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ConversionResponse: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ConversionResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ConvertedObjects", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.ConvertedObjects = append(m.ConvertedObjects, runtime.RawExtension{})
+			if err := m.ConvertedObjects[len(m.ConvertedObjects)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *ConversionReview) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ConversionReview: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ConversionReview: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Request == nil {
+				m.Request = &ConversionRequest{}
+			}
+			if err := m.Request.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Response", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Response == nil {
+				m.Response = &ConversionResponse{}
+			}
+			if err := m.Response.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceColumnDefinition) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceColumnDefinition: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceColumnDefinition: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Name = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Type = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Format = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Description = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 5:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType)
+			}
+			m.Priority = 0
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				m.Priority |= int32(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+		case 6:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field JSONPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.JSONPath = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceConversion) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceConversion: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceConversion: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Strategy", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Strategy = ConversionStrategyType(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field WebhookClientConfig", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.WebhookClientConfig == nil {
+				m.WebhookClientConfig = &WebhookClientConfig{}
+			}
+			if err := m.WebhookClientConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ConversionReviewVersions", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.ConversionReviewVersions = append(m.ConversionReviewVersions, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinition) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinition: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinition: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionCondition) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionCondition: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionCondition: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Type = CustomResourceDefinitionConditionType(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Status = ConditionStatus(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Reason = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Message = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionList) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionList: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionList: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Items = append(m.Items, CustomResourceDefinition{})
+			if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionNames) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionNames: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionNames: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Plural", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Plural = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Singular", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Singular = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ShortNames", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.ShortNames = append(m.ShortNames, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Kind = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ListKind", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.ListKind = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 6:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Categories", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Categories = append(m.Categories, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionSpec) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionSpec: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Group", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Group = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Version = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.Names.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Scope = ResourceScope(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Validation", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Validation == nil {
+				m.Validation = &CustomResourceValidation{}
+			}
+			if err := m.Validation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 6:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Subresources", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Subresources == nil {
+				m.Subresources = &CustomResourceSubresources{}
+			}
+			if err := m.Subresources.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 7:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Versions", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Versions = append(m.Versions, CustomResourceDefinitionVersion{})
+			if err := m.Versions[len(m.Versions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 8:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AdditionalPrinterColumns", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.AdditionalPrinterColumns = append(m.AdditionalPrinterColumns, CustomResourceColumnDefinition{})
+			if err := m.AdditionalPrinterColumns[len(m.AdditionalPrinterColumns)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 9:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Conversion", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Conversion == nil {
+				m.Conversion = &CustomResourceConversion{}
+			}
+			if err := m.Conversion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 10:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field PreserveUnknownFields", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			b := bool(v != 0)
+			m.PreserveUnknownFields = &b
+		case 11:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field SelectableFields", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.SelectableFields = append(m.SelectableFields, SelectableField{})
+			if err := m.SelectableFields[len(m.SelectableFields)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionStatus) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionStatus: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Conditions = append(m.Conditions, CustomResourceDefinitionCondition{})
+			if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AcceptedNames", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if err := m.AcceptedNames.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field StoredVersions", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.StoredVersions = append(m.StoredVersions, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceDefinitionVersion) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceDefinitionVersion: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceDefinitionVersion: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Name = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Served", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Served = bool(v != 0)
+		case 3:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Storage", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Storage = bool(v != 0)
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Schema == nil {
+				m.Schema = &CustomResourceValidation{}
+			}
+			if err := m.Schema.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Subresources", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Subresources == nil {
+				m.Subresources = &CustomResourceSubresources{}
+			}
+			if err := m.Subresources.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 6:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AdditionalPrinterColumns", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.AdditionalPrinterColumns = append(m.AdditionalPrinterColumns, CustomResourceColumnDefinition{})
+			if err := m.AdditionalPrinterColumns[len(m.AdditionalPrinterColumns)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 7:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Deprecated", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Deprecated = bool(v != 0)
+		case 8:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field DeprecationWarning", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.DeprecationWarning = &s
+			iNdEx = postIndex
+		case 9:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field SelectableFields", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.SelectableFields = append(m.SelectableFields, SelectableField{})
+			if err := m.SelectableFields[len(m.SelectableFields)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceSubresourceScale) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceSubresourceScale: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceSubresourceScale: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field SpecReplicasPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.SpecReplicasPath = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field StatusReplicasPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.StatusReplicasPath = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field LabelSelectorPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.LabelSelectorPath = &s
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceSubresourceStatus) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceSubresourceStatus: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceSubresourceStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceSubresources) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceSubresources: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceSubresources: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Status == nil {
+				m.Status = &CustomResourceSubresourceStatus{}
+			}
+			if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Scale", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Scale == nil {
+				m.Scale = &CustomResourceSubresourceScale{}
+			}
+			if err := m.Scale.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *CustomResourceValidation) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: CustomResourceValidation: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: CustomResourceValidation: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field OpenAPIV3Schema", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.OpenAPIV3Schema == nil {
+				m.OpenAPIV3Schema = &JSONSchemaProps{}
+			}
+			if err := m.OpenAPIV3Schema.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *ExternalDocumentation) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ExternalDocumentation: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ExternalDocumentation: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Description = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field URL", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.URL = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *JSON) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: JSON: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: JSON: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Raw", wireType)
+			}
+			var byteLen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				byteLen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if byteLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + byteLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Raw = append(m.Raw[:0], dAtA[iNdEx:postIndex]...)
+			if m.Raw == nil {
+				m.Raw = []byte{}
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *JSONSchemaProps) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: JSONSchemaProps: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: JSONSchemaProps: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.ID = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Schema = JSONSchemaURL(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Ref", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.Ref = &s
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Description = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Type = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 6:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Format = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 7:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Title = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 8:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Default", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Default == nil {
+				m.Default = &JSON{}
+			}
+			if err := m.Default.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 9:
+			if wireType != 1 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Maximum", wireType)
+			}
+			var v uint64
+			if (iNdEx + 8) > l {
+				return io.ErrUnexpectedEOF
+			}
+			v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
+			iNdEx += 8
+			v2 := float64(math.Float64frombits(v))
+			m.Maximum = &v2
+		case 10:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ExclusiveMaximum", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.ExclusiveMaximum = bool(v != 0)
+		case 11:
+			if wireType != 1 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Minimum", wireType)
+			}
+			var v uint64
+			if (iNdEx + 8) > l {
+				return io.ErrUnexpectedEOF
+			}
+			v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
+			iNdEx += 8
+			v2 := float64(math.Float64frombits(v))
+			m.Minimum = &v2
+		case 12:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ExclusiveMinimum", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.ExclusiveMinimum = bool(v != 0)
+		case 13:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MaxLength", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MaxLength = &v
+		case 14:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MinLength", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MinLength = &v
+		case 15:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Pattern", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Pattern = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 16:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MaxItems", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MaxItems = &v
+		case 17:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MinItems", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MinItems = &v
+		case 18:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field UniqueItems", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.UniqueItems = bool(v != 0)
+		case 19:
+			if wireType != 1 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MultipleOf", wireType)
+			}
+			var v uint64
+			if (iNdEx + 8) > l {
+				return io.ErrUnexpectedEOF
+			}
+			v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
+			iNdEx += 8
+			v2 := float64(math.Float64frombits(v))
+			m.MultipleOf = &v2
+		case 20:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Enum", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Enum = append(m.Enum, JSON{})
+			if err := m.Enum[len(m.Enum)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 21:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MaxProperties", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MaxProperties = &v
+		case 22:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MinProperties", wireType)
+			}
+			var v int64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.MinProperties = &v
+		case 23:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Required", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Required = append(m.Required, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		case 24:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Items == nil {
+				m.Items = &JSONSchemaPropsOrArray{}
+			}
+			if err := m.Items.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 25:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AllOf", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.AllOf = append(m.AllOf, JSONSchemaProps{})
+			if err := m.AllOf[len(m.AllOf)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 26:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field OneOf", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.OneOf = append(m.OneOf, JSONSchemaProps{})
+			if err := m.OneOf[len(m.OneOf)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 27:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AnyOf", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.AnyOf = append(m.AnyOf, JSONSchemaProps{})
+			if err := m.AnyOf[len(m.AnyOf)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 28:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Not", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Not == nil {
+				m.Not = &JSONSchemaProps{}
+			}
+			if err := m.Not.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 29:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Properties", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Properties == nil {
+				m.Properties = make(map[string]JSONSchemaProps)
+			}
+			var mapkey string
+			mapvalue := &JSONSchemaProps{}
+			for iNdEx < postIndex {
+				entryPreIndex := iNdEx
+				var wire uint64
+				for shift := uint(0); ; shift += 7 {
+					if shift >= 64 {
+						return ErrIntOverflowGenerated
+					}
+					if iNdEx >= l {
+						return io.ErrUnexpectedEOF
+					}
+					b := dAtA[iNdEx]
+					iNdEx++
+					wire |= uint64(b&0x7F) << shift
+					if b < 0x80 {
+						break
+					}
+				}
+				fieldNum := int32(wire >> 3)
+				if fieldNum == 1 {
+					var stringLenmapkey uint64
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						stringLenmapkey |= uint64(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					intStringLenmapkey := int(stringLenmapkey)
+					if intStringLenmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postStringIndexmapkey := iNdEx + intStringLenmapkey
+					if postStringIndexmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postStringIndexmapkey > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
+					iNdEx = postStringIndexmapkey
+				} else if fieldNum == 2 {
+					var mapmsglen int
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						mapmsglen |= int(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					if mapmsglen < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postmsgIndex := iNdEx + mapmsglen
+					if postmsgIndex < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postmsgIndex > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapvalue = &JSONSchemaProps{}
+					if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+						return err
+					}
+					iNdEx = postmsgIndex
+				} else {
+					iNdEx = entryPreIndex
+					skippy, err := skipGenerated(dAtA[iNdEx:])
+					if err != nil {
+						return err
+					}
+					if (skippy < 0) || (iNdEx+skippy) < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if (iNdEx + skippy) > postIndex {
+						return io.ErrUnexpectedEOF
+					}
+					iNdEx += skippy
+				}
+			}
+			m.Properties[mapkey] = *mapvalue
+			iNdEx = postIndex
+		case 30:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AdditionalProperties", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.AdditionalProperties == nil {
+				m.AdditionalProperties = &JSONSchemaPropsOrBool{}
+			}
+			if err := m.AdditionalProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 31:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field PatternProperties", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.PatternProperties == nil {
+				m.PatternProperties = make(map[string]JSONSchemaProps)
+			}
+			var mapkey string
+			mapvalue := &JSONSchemaProps{}
+			for iNdEx < postIndex {
+				entryPreIndex := iNdEx
+				var wire uint64
+				for shift := uint(0); ; shift += 7 {
+					if shift >= 64 {
+						return ErrIntOverflowGenerated
+					}
+					if iNdEx >= l {
+						return io.ErrUnexpectedEOF
+					}
+					b := dAtA[iNdEx]
+					iNdEx++
+					wire |= uint64(b&0x7F) << shift
+					if b < 0x80 {
+						break
+					}
+				}
+				fieldNum := int32(wire >> 3)
+				if fieldNum == 1 {
+					var stringLenmapkey uint64
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						stringLenmapkey |= uint64(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					intStringLenmapkey := int(stringLenmapkey)
+					if intStringLenmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postStringIndexmapkey := iNdEx + intStringLenmapkey
+					if postStringIndexmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postStringIndexmapkey > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
+					iNdEx = postStringIndexmapkey
+				} else if fieldNum == 2 {
+					var mapmsglen int
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						mapmsglen |= int(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					if mapmsglen < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postmsgIndex := iNdEx + mapmsglen
+					if postmsgIndex < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postmsgIndex > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapvalue = &JSONSchemaProps{}
+					if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+						return err
+					}
+					iNdEx = postmsgIndex
+				} else {
+					iNdEx = entryPreIndex
+					skippy, err := skipGenerated(dAtA[iNdEx:])
+					if err != nil {
+						return err
+					}
+					if (skippy < 0) || (iNdEx+skippy) < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if (iNdEx + skippy) > postIndex {
+						return io.ErrUnexpectedEOF
+					}
+					iNdEx += skippy
+				}
+			}
+			m.PatternProperties[mapkey] = *mapvalue
+			iNdEx = postIndex
+		case 32:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Dependencies", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Dependencies == nil {
+				m.Dependencies = make(JSONSchemaDependencies)
+			}
+			var mapkey string
+			mapvalue := &JSONSchemaPropsOrStringArray{}
+			for iNdEx < postIndex {
+				entryPreIndex := iNdEx
+				var wire uint64
+				for shift := uint(0); ; shift += 7 {
+					if shift >= 64 {
+						return ErrIntOverflowGenerated
+					}
+					if iNdEx >= l {
+						return io.ErrUnexpectedEOF
+					}
+					b := dAtA[iNdEx]
+					iNdEx++
+					wire |= uint64(b&0x7F) << shift
+					if b < 0x80 {
+						break
+					}
+				}
+				fieldNum := int32(wire >> 3)
+				if fieldNum == 1 {
+					var stringLenmapkey uint64
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						stringLenmapkey |= uint64(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					intStringLenmapkey := int(stringLenmapkey)
+					if intStringLenmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postStringIndexmapkey := iNdEx + intStringLenmapkey
+					if postStringIndexmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postStringIndexmapkey > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
+					iNdEx = postStringIndexmapkey
+				} else if fieldNum == 2 {
+					var mapmsglen int
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						mapmsglen |= int(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					if mapmsglen < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postmsgIndex := iNdEx + mapmsglen
+					if postmsgIndex < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postmsgIndex > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapvalue = &JSONSchemaPropsOrStringArray{}
+					if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+						return err
+					}
+					iNdEx = postmsgIndex
+				} else {
+					iNdEx = entryPreIndex
+					skippy, err := skipGenerated(dAtA[iNdEx:])
+					if err != nil {
+						return err
+					}
+					if (skippy < 0) || (iNdEx+skippy) < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if (iNdEx + skippy) > postIndex {
+						return io.ErrUnexpectedEOF
+					}
+					iNdEx += skippy
+				}
+			}
+			m.Dependencies[mapkey] = *mapvalue
+			iNdEx = postIndex
+		case 33:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field AdditionalItems", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.AdditionalItems == nil {
+				m.AdditionalItems = &JSONSchemaPropsOrBool{}
+			}
+			if err := m.AdditionalItems.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 34:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Definitions", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Definitions == nil {
+				m.Definitions = make(JSONSchemaDefinitions)
+			}
+			var mapkey string
+			mapvalue := &JSONSchemaProps{}
+			for iNdEx < postIndex {
+				entryPreIndex := iNdEx
+				var wire uint64
+				for shift := uint(0); ; shift += 7 {
+					if shift >= 64 {
+						return ErrIntOverflowGenerated
+					}
+					if iNdEx >= l {
+						return io.ErrUnexpectedEOF
+					}
+					b := dAtA[iNdEx]
+					iNdEx++
+					wire |= uint64(b&0x7F) << shift
+					if b < 0x80 {
+						break
+					}
+				}
+				fieldNum := int32(wire >> 3)
+				if fieldNum == 1 {
+					var stringLenmapkey uint64
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						stringLenmapkey |= uint64(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					intStringLenmapkey := int(stringLenmapkey)
+					if intStringLenmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postStringIndexmapkey := iNdEx + intStringLenmapkey
+					if postStringIndexmapkey < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postStringIndexmapkey > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
+					iNdEx = postStringIndexmapkey
+				} else if fieldNum == 2 {
+					var mapmsglen int
+					for shift := uint(0); ; shift += 7 {
+						if shift >= 64 {
+							return ErrIntOverflowGenerated
+						}
+						if iNdEx >= l {
+							return io.ErrUnexpectedEOF
+						}
+						b := dAtA[iNdEx]
+						iNdEx++
+						mapmsglen |= int(b&0x7F) << shift
+						if b < 0x80 {
+							break
+						}
+					}
+					if mapmsglen < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					postmsgIndex := iNdEx + mapmsglen
+					if postmsgIndex < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if postmsgIndex > l {
+						return io.ErrUnexpectedEOF
+					}
+					mapvalue = &JSONSchemaProps{}
+					if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+						return err
+					}
+					iNdEx = postmsgIndex
+				} else {
+					iNdEx = entryPreIndex
+					skippy, err := skipGenerated(dAtA[iNdEx:])
+					if err != nil {
+						return err
+					}
+					if (skippy < 0) || (iNdEx+skippy) < 0 {
+						return ErrInvalidLengthGenerated
+					}
+					if (iNdEx + skippy) > postIndex {
+						return io.ErrUnexpectedEOF
+					}
+					iNdEx += skippy
+				}
+			}
+			m.Definitions[mapkey] = *mapvalue
+			iNdEx = postIndex
+		case 35:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field ExternalDocs", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.ExternalDocs == nil {
+				m.ExternalDocs = &ExternalDocumentation{}
+			}
+			if err := m.ExternalDocs.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 36:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Example", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Example == nil {
+				m.Example = &JSON{}
+			}
+			if err := m.Example.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 37:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Nullable", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Nullable = bool(v != 0)
+		case 38:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XPreserveUnknownFields", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			b := bool(v != 0)
+			m.XPreserveUnknownFields = &b
+		case 39:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XEmbeddedResource", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.XEmbeddedResource = bool(v != 0)
+		case 40:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XIntOrString", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.XIntOrString = bool(v != 0)
+		case 41:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XListMapKeys", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.XListMapKeys = append(m.XListMapKeys, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		case 42:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XListType", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.XListType = &s
+			iNdEx = postIndex
+		case 43:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XMapType", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.XMapType = &s
+			iNdEx = postIndex
+		case 44:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field XValidations", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.XValidations = append(m.XValidations, ValidationRule{})
+			if err := m.XValidations[len(m.XValidations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *JSONSchemaPropsOrArray) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrArray: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrArray: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Schema == nil {
+				m.Schema = &JSONSchemaProps{}
+			}
+			if err := m.Schema.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field JSONSchemas", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.JSONSchemas = append(m.JSONSchemas, JSONSchemaProps{})
+			if err := m.JSONSchemas[len(m.JSONSchemas)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *JSONSchemaPropsOrBool) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrBool: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrBool: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Allows", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Allows = bool(v != 0)
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Schema == nil {
+				m.Schema = &JSONSchemaProps{}
+			}
+			if err := m.Schema.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *JSONSchemaPropsOrStringArray) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrStringArray: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: JSONSchemaPropsOrStringArray: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Schema == nil {
+				m.Schema = &JSONSchemaProps{}
+			}
+			if err := m.Schema.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Property", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Property = append(m.Property, string(dAtA[iNdEx:postIndex]))
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *SelectableField) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: SelectableField: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: SelectableField: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field JSONPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.JSONPath = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *ServiceReference) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ServiceReference: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ServiceReference: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Namespace = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Name = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Path", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.Path = &s
+			iNdEx = postIndex
+		case 4:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Port", wireType)
+			}
+			var v int32
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int32(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			m.Port = &v
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *ValidationRule) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: ValidationRule: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: ValidationRule: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Rule", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Rule = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Message = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field MessageExpression", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.MessageExpression = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 4:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := FieldValueErrorReason(dAtA[iNdEx:postIndex])
+			m.Reason = &s
+			iNdEx = postIndex
+		case 5:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field FieldPath", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.FieldPath = string(dAtA[iNdEx:postIndex])
+			iNdEx = postIndex
+		case 6:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field OptionalOldSelf", wireType)
+			}
+			var v int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				v |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			b := bool(v != 0)
+			m.OptionalOldSelf = &b
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func (m *WebhookClientConfig) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: WebhookClientConfig: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: WebhookClientConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			if m.Service == nil {
+				m.Service = &ServiceReference{}
+			}
+			if err := m.Service.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field CABundle", wireType)
+			}
+			var byteLen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				byteLen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if byteLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + byteLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.CABundle = append(m.CABundle[:0], dAtA[iNdEx:postIndex]...)
+			if m.CABundle == nil {
+				m.CABundle = []byte{}
+			}
+			iNdEx = postIndex
+		case 3:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field URL", wireType)
+			}
+			var stringLen uint64
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				stringLen |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			intStringLen := int(stringLen)
+			if intStringLen < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			postIndex := iNdEx + intStringLen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			s := string(dAtA[iNdEx:postIndex])
+			m.URL = &s
+			iNdEx = postIndex
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenerated(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if (skippy < 0) || (iNdEx+skippy) < 0 {
+				return ErrInvalidLengthGenerated
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func skipGenerated(dAtA []byte) (n int, err error) {
+	l := len(dAtA)
+	iNdEx := 0
+	depth := 0
+	for iNdEx < l {
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return 0, ErrIntOverflowGenerated
+			}
+			if iNdEx >= l {
+				return 0, io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= (uint64(b) & 0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		wireType := int(wire & 0x7)
+		switch wireType {
+		case 0:
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				iNdEx++
+				if dAtA[iNdEx-1] < 0x80 {
+					break
+				}
+			}
+		case 1:
+			iNdEx += 8
+		case 2:
+			var length int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowGenerated
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				length |= (int(b) & 0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if length < 0 {
+				return 0, ErrInvalidLengthGenerated
+			}
+			iNdEx += length
+		case 3:
+			depth++
+		case 4:
+			if depth == 0 {
+				return 0, ErrUnexpectedEndOfGroupGenerated
+			}
+			depth--
+		case 5:
+			iNdEx += 4
+		default:
+			return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+		}
+		if iNdEx < 0 {
+			return 0, ErrInvalidLengthGenerated
+		}
+		if depth == 0 {
+			return iNdEx, nil
+		}
+	}
+	return 0, io.ErrUnexpectedEOF
+}
+
+var (
+	ErrInvalidLengthGenerated        = fmt.Errorf("proto: negative length found during unmarshaling")
+	ErrIntOverflowGenerated          = fmt.Errorf("proto: integer overflow")
+	ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group")
+)
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto
new file mode 100644
index 000000000..f9e560034
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto
@@ -0,0 +1,874 @@
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+
+// This file was autogenerated by go-to-protobuf. Do not edit it manually!
+
+syntax = "proto2";
+
+package k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1;
+
+import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
+import "k8s.io/apimachinery/pkg/runtime/generated.proto";
+import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
+
+// Package-wide variables from generator "generated".
+option go_package = "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1";
+
+// ConversionRequest describes the conversion request parameters.
+message ConversionRequest {
+  // uid is an identifier for the individual request/response. It allows distinguishing instances of requests which are
+  // otherwise identical (parallel requests, etc).
+  // The UID is meant to track the round trip (request/response) between the Kubernetes API server and the webhook, not the user request.
+  // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.
+  optional string uid = 1;
+
+  // desiredAPIVersion is the version to convert given objects to. e.g. "myapi.example.com/v1"
+  optional string desiredAPIVersion = 2;
+
+  // objects is the list of custom resource objects to be converted.
+  // +listType=atomic
+  repeated .k8s.io.apimachinery.pkg.runtime.RawExtension objects = 3;
+}
+
+// ConversionResponse describes a conversion response.
+message ConversionResponse {
+  // uid is an identifier for the individual request/response.
+  // This should be copied over from the corresponding `request.uid`.
+  optional string uid = 1;
+
+  // convertedObjects is the list of converted version of `request.objects` if the `result` is successful, otherwise empty.
+  // The webhook is expected to set `apiVersion` of these objects to the `request.desiredAPIVersion`. The list
+  // must also have the same size as the input list with the same objects in the same order (equal kind, metadata.uid, metadata.name and metadata.namespace).
+  // The webhook is allowed to mutate labels and annotations. Any other change to the metadata is silently ignored.
+  // +listType=atomic
+  repeated .k8s.io.apimachinery.pkg.runtime.RawExtension convertedObjects = 2;
+
+  // result contains the result of conversion with extra details if the conversion failed. `result.status` determines if
+  // the conversion failed or succeeded. The `result.status` field is required and represents the success or failure of the
+  // conversion. A successful conversion must set `result.status` to `Success`. A failed conversion must set
+  // `result.status` to `Failure` and provide more details in `result.message` and return http status 200. The `result.message`
+  // will be used to construct an error message for the end user.
+  optional .k8s.io.apimachinery.pkg.apis.meta.v1.Status result = 3;
+}
+
+// ConversionReview describes a conversion request/response.
+message ConversionReview {
+  // request describes the attributes for the conversion request.
+  // +optional
+  optional ConversionRequest request = 1;
+
+  // response describes the attributes for the conversion response.
+  // +optional
+  optional ConversionResponse response = 2;
+}
+
+// CustomResourceColumnDefinition specifies a column for server side printing.
+message CustomResourceColumnDefinition {
+  // name is a human readable name for the column.
+  optional string name = 1;
+
+  // type is an OpenAPI type definition for this column.
+  // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details.
+  optional string type = 2;
+
+  // format is an optional OpenAPI type definition for this column. The 'name' format is applied
+  // to the primary identifier column to assist in clients identifying column is the resource name.
+  // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details.
+  // +optional
+  optional string format = 3;
+
+  // description is a human readable description of this column.
+  // +optional
+  optional string description = 4;
+
+  // priority is an integer defining the relative importance of this column compared to others. Lower
+  // numbers are considered higher priority. Columns that may be omitted in limited space scenarios
+  // should be given a priority greater than 0.
+  // +optional
+  optional int32 priority = 5;
+
+  // JSONPath is a simple JSON path (i.e. with array notation) which is evaluated against
+  // each custom resource to produce the value for this column.
+  optional string JSONPath = 6;
+}
+
+// CustomResourceConversion describes how to convert different versions of a CR.
+message CustomResourceConversion {
+  // strategy specifies how custom resources are converted between versions. Allowed values are:
+  // - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource.
+  // - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information
+  //   is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhookClientConfig to be set.
+  optional string strategy = 1;
+
+  // webhookClientConfig is the instructions for how to call the webhook if strategy is `Webhook`.
+  // Required when `strategy` is set to `Webhook`.
+  // +optional
+  optional WebhookClientConfig webhookClientConfig = 2;
+
+  // conversionReviewVersions is an ordered list of preferred `ConversionReview`
+  // versions the Webhook expects. The API server will use the first version in
+  // the list which it supports. If none of the versions specified in this list
+  // are supported by API server, conversion will fail for the custom resource.
+  // If a persisted Webhook configuration specifies allowed versions and does not
+  // include any versions known to the API Server, calls to the webhook will fail.
+  // Defaults to `["v1beta1"]`.
+  // +optional
+  // +listType=atomic
+  repeated string conversionReviewVersions = 3;
+}
+
+// CustomResourceDefinition represents a resource that should be exposed on the API server.  Its name MUST be in the format
+// <.spec.name>.<.spec.group>.
+// Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead.
+message CustomResourceDefinition {
+  // Standard object's metadata
+  // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
+  // +optional
+  optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
+
+  // spec describes how the user wants the resources to appear
+  optional CustomResourceDefinitionSpec spec = 2;
+
+  // status indicates the actual state of the CustomResourceDefinition
+  // +optional
+  optional CustomResourceDefinitionStatus status = 3;
+}
+
+// CustomResourceDefinitionCondition contains details for the current condition of this pod.
+message CustomResourceDefinitionCondition {
+  // type is the type of the condition. Types include Established, NamesAccepted and Terminating.
+  optional string type = 1;
+
+  // status is the status of the condition.
+  // Can be True, False, Unknown.
+  optional string status = 2;
+
+  // lastTransitionTime last time the condition transitioned from one status to another.
+  // +optional
+  optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3;
+
+  // reason is a unique, one-word, CamelCase reason for the condition's last transition.
+  // +optional
+  optional string reason = 4;
+
+  // message is a human-readable message indicating details about last transition.
+  // +optional
+  optional string message = 5;
+}
+
+// CustomResourceDefinitionList is a list of CustomResourceDefinition objects.
+message CustomResourceDefinitionList {
+  // Standard object's metadata
+  // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
+  // +optional
+  optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
+
+  // items list individual CustomResourceDefinition objects
+  repeated CustomResourceDefinition items = 2;
+}
+
+// CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition
+message CustomResourceDefinitionNames {
+  // plural is the plural name of the resource to serve.
+  // The custom resources are served under `/apis///.../`.
+  // Must match the name of the CustomResourceDefinition (in the form `.`).
+  // Must be all lowercase.
+  optional string plural = 1;
+
+  // singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`.
+  // +optional
+  optional string singular = 2;
+
+  // shortNames are short names for the resource, exposed in API discovery documents,
+  // and used by clients to support invocations like `kubectl get `.
+  // It must be all lowercase.
+  // +optional
+  // +listType=atomic
+  repeated string shortNames = 3;
+
+  // kind is the serialized kind of the resource. It is normally CamelCase and singular.
+  // Custom resource instances will use this value as the `kind` attribute in API calls.
+  optional string kind = 4;
+
+  // listKind is the serialized kind of the list for this resource. Defaults to "`kind`List".
+  // +optional
+  optional string listKind = 5;
+
+  // categories is a list of grouped resources this custom resource belongs to (e.g. 'all').
+  // This is published in API discovery documents, and used by clients to support invocations like
+  // `kubectl get all`.
+  // +optional
+  // +listType=atomic
+  repeated string categories = 6;
+}
+
+// CustomResourceDefinitionSpec describes how a user wants their resource to appear
+message CustomResourceDefinitionSpec {
+  // group is the API group of the defined custom resource.
+  // The custom resources are served under `/apis//...`.
+  // Must match the name of the CustomResourceDefinition (in the form `.`).
+  optional string group = 1;
+
+  // version is the API version of the defined custom resource.
+  // The custom resources are served under `/apis///...`.
+  // Must match the name of the first item in the `versions` list if `version` and `versions` are both specified.
+  // Optional if `versions` is specified.
+  // Deprecated: use `versions` instead.
+  // +optional
+  optional string version = 2;
+
+  // names specify the resource and kind names for the custom resource.
+  optional CustomResourceDefinitionNames names = 3;
+
+  // scope indicates whether the defined custom resource is cluster- or namespace-scoped.
+  // Allowed values are `Cluster` and `Namespaced`. Default is `Namespaced`.
+  optional string scope = 4;
+
+  // validation describes the schema used for validation and pruning of the custom resource.
+  // If present, this validation schema is used to validate all versions.
+  // Top-level and per-version schemas are mutually exclusive.
+  // +optional
+  optional CustomResourceValidation validation = 5;
+
+  // subresources specify what subresources the defined custom resource has.
+  // If present, this field configures subresources for all versions.
+  // Top-level and per-version subresources are mutually exclusive.
+  // +optional
+  optional CustomResourceSubresources subresources = 6;
+
+  // versions is the list of all API versions of the defined custom resource.
+  // Optional if `version` is specified.
+  // The name of the first item in the `versions` list must match the `version` field if `version` and `versions` are both specified.
+  // Version names are used to compute the order in which served versions are listed in API discovery.
+  // If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered
+  // lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version),
+  // then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first
+  // by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing
+  // major version, then minor version. An example sorted list of versions:
+  // v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10.
+  // +optional
+  // +listType=atomic
+  repeated CustomResourceDefinitionVersion versions = 7;
+
+  // additionalPrinterColumns specifies additional columns returned in Table output.
+  // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details.
+  // If present, this field configures columns for all versions.
+  // Top-level and per-version columns are mutually exclusive.
+  // If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used.
+  // +optional
+  // +listType=atomic
+  repeated CustomResourceColumnDefinition additionalPrinterColumns = 8;
+
+  // selectableFields specifies paths to fields that may be used as field selectors.
+  // See https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors
+  //
+  // +featureGate=CustomResourceFieldSelectors
+  // +optional
+  // +listType=atomic
+  repeated SelectableField selectableFields = 11;
+
+  // conversion defines conversion settings for the CRD.
+  // +optional
+  optional CustomResourceConversion conversion = 9;
+
+  // preserveUnknownFields indicates that object fields which are not specified
+  // in the OpenAPI schema should be preserved when persisting to storage.
+  // apiVersion, kind, metadata and known fields inside metadata are always preserved.
+  // If false, schemas must be defined for all versions.
+  // Defaults to true in v1beta for backwards compatibility.
+  // Deprecated: will be required to be false in v1. Preservation of unknown fields can be specified
+  // in the validation schema using the `x-kubernetes-preserve-unknown-fields: true` extension.
+  // See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details.
+  // +optional
+  optional bool preserveUnknownFields = 10;
+}
+
+// CustomResourceDefinitionStatus indicates the state of the CustomResourceDefinition
+message CustomResourceDefinitionStatus {
+  // conditions indicate state for particular aspects of a CustomResourceDefinition
+  // +optional
+  // +listType=map
+  // +listMapKey=type
+  repeated CustomResourceDefinitionCondition conditions = 1;
+
+  // acceptedNames are the names that are actually being used to serve discovery.
+  // They may be different than the names in spec.
+  // +optional
+  optional CustomResourceDefinitionNames acceptedNames = 2;
+
+  // storedVersions lists all versions of CustomResources that were ever persisted. Tracking these
+  // versions allows a migration path for stored versions in etcd. The field is mutable
+  // so a migration controller can finish a migration to another version (ensuring
+  // no old objects are left in storage), and then remove the rest of the
+  // versions from this list.
+  // Versions may not be removed from `spec.versions` while they exist in this list.
+  // +optional
+  // +listType=atomic
+  repeated string storedVersions = 3;
+}
+
+// CustomResourceDefinitionVersion describes a version for CRD.
+message CustomResourceDefinitionVersion {
+  // name is the version name, e.g. “v1”, “v2beta1”, etc.
+  // The custom resources are served under this version at `/apis///...` if `served` is true.
+  optional string name = 1;
+
+  // served is a flag enabling/disabling this version from being served via REST APIs
+  optional bool served = 2;
+
+  // storage indicates this version should be used when persisting custom resources to storage.
+  // There must be exactly one version with storage=true.
+  optional bool storage = 3;
+
+  // deprecated indicates this version of the custom resource API is deprecated.
+  // When set to true, API requests to this version receive a warning header in the server response.
+  // Defaults to false.
+  // +optional
+  optional bool deprecated = 7;
+
+  // deprecationWarning overrides the default warning returned to API clients.
+  // May only be set when `deprecated` is true.
+  // The default warning indicates this version is deprecated and recommends use
+  // of the newest served version of equal or greater stability, if one exists.
+  // +optional
+  optional string deprecationWarning = 8;
+
+  // schema describes the schema used for validation and pruning of this version of the custom resource.
+  // Top-level and per-version schemas are mutually exclusive.
+  // Per-version schemas must not all be set to identical values (top-level validation schema should be used instead).
+  // +optional
+  optional CustomResourceValidation schema = 4;
+
+  // subresources specify what subresources this version of the defined custom resource have.
+  // Top-level and per-version subresources are mutually exclusive.
+  // Per-version subresources must not all be set to identical values (top-level subresources should be used instead).
+  // +optional
+  optional CustomResourceSubresources subresources = 5;
+
+  // additionalPrinterColumns specifies additional columns returned in Table output.
+  // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details.
+  // Top-level and per-version columns are mutually exclusive.
+  // Per-version columns must not all be set to identical values (top-level columns should be used instead).
+  // If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used.
+  // +optional
+  // +listType=atomic
+  repeated CustomResourceColumnDefinition additionalPrinterColumns = 6;
+
+  // selectableFields specifies paths to fields that may be used as field selectors.
+  // See https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors
+  //
+  // +featureGate=CustomResourceFieldSelectors
+  // +optional
+  // +listType=atomic
+  repeated SelectableField selectableFields = 9;
+}
+
+// CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources.
+message CustomResourceSubresourceScale {
+  // specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`.
+  // Only JSON paths without the array notation are allowed.
+  // Must be a JSON Path under `.spec`.
+  // If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET.
+  optional string specReplicasPath = 1;
+
+  // statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`.
+  // Only JSON paths without the array notation are allowed.
+  // Must be a JSON Path under `.status`.
+  // If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource
+  // will default to 0.
+  optional string statusReplicasPath = 2;
+
+  // labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`.
+  // Only JSON paths without the array notation are allowed.
+  // Must be a JSON Path under `.status` or `.spec`.
+  // Must be set to work with HorizontalPodAutoscaler.
+  // The field pointed by this JSON path must be a string field (not a complex selector struct)
+  // which contains a serialized label selector in string form.
+  // More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource
+  // If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale`
+  // subresource will default to the empty string.
+  // +optional
+  optional string labelSelectorPath = 3;
+}
+
+// CustomResourceSubresourceStatus defines how to serve the status subresource for CustomResources.
+// Status is represented by the `.status` JSON path inside of a CustomResource. When set,
+// * exposes a /status subresource for the custom resource
+// * PUT requests to the /status subresource take a custom resource object, and ignore changes to anything except the status stanza
+// * PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza
+message CustomResourceSubresourceStatus {
+}
+
+// CustomResourceSubresources defines the status and scale subresources for CustomResources.
+message CustomResourceSubresources {
+  // status indicates the custom resource should serve a `/status` subresource.
+  // When enabled:
+  // 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object.
+  // 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object.
+  // +optional
+  optional CustomResourceSubresourceStatus status = 1;
+
+  // scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object.
+  // +optional
+  optional CustomResourceSubresourceScale scale = 2;
+}
+
+// CustomResourceValidation is a list of validation methods for CustomResources.
+message CustomResourceValidation {
+  // openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning.
+  // +optional
+  optional JSONSchemaProps openAPIV3Schema = 1;
+}
+
+// ExternalDocumentation allows referencing an external resource for extended documentation.
+message ExternalDocumentation {
+  optional string description = 1;
+
+  optional string url = 2;
+}
+
+// JSON represents any valid JSON value.
+// These types are supported: bool, int64, float64, string, []interface{}, map[string]interface{} and nil.
+message JSON {
+  optional bytes raw = 1;
+}
+
+// JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/).
+message JSONSchemaProps {
+  optional string id = 1;
+
+  optional string schema = 2;
+
+  optional string ref = 3;
+
+  optional string description = 4;
+
+  optional string type = 5;
+
+  // format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated:
+  //
+  // - bsonobjectid: a bson object ID, i.e. a 24 characters hex string
+  // - uri: an URI as parsed by Golang net/url.ParseRequestURI
+  // - email: an email address as parsed by Golang net/mail.ParseAddress
+  // - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034].
+  // - ipv4: an IPv4 IP as parsed by Golang net.ParseIP
+  // - ipv6: an IPv6 IP as parsed by Golang net.ParseIP
+  // - cidr: a CIDR as parsed by Golang net.ParseCIDR
+  // - mac: a MAC address as parsed by Golang net.ParseMAC
+  // - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$
+  // - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$
+  // - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$
+  // - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$
+  // - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041"
+  // - isbn10: an ISBN10 number string like "0321751043"
+  // - isbn13: an ISBN13 number string like "978-0321751041"
+  // - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in
+  // - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$
+  // - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
+  // - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559"
+  // - byte: base64 encoded binary data
+  // - password: any kind of string
+  // - date: a date string like "2006-01-02" as defined by full-date in RFC3339
+  // - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format
+  // - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339.
+  optional string format = 6;
+
+  optional string title = 7;
+
+  // default is a default value for undefined object fields.
+  // Defaulting is a beta feature under the CustomResourceDefaulting feature gate.
+  // CustomResourceDefinitions with defaults must be created using the v1 (or newer) CustomResourceDefinition API.
+  optional JSON default = 8;
+
+  optional double maximum = 9;
+
+  optional bool exclusiveMaximum = 10;
+
+  optional double minimum = 11;
+
+  optional bool exclusiveMinimum = 12;
+
+  optional int64 maxLength = 13;
+
+  optional int64 minLength = 14;
+
+  optional string pattern = 15;
+
+  optional int64 maxItems = 16;
+
+  optional int64 minItems = 17;
+
+  optional bool uniqueItems = 18;
+
+  optional double multipleOf = 19;
+
+  // +listType=atomic
+  repeated JSON enum = 20;
+
+  optional int64 maxProperties = 21;
+
+  optional int64 minProperties = 22;
+
+  // +listType=atomic
+  repeated string required = 23;
+
+  optional JSONSchemaPropsOrArray items = 24;
+
+  // +listType=atomic
+  repeated JSONSchemaProps allOf = 25;
+
+  // +listType=atomic
+  repeated JSONSchemaProps oneOf = 26;
+
+  // +listType=atomic
+  repeated JSONSchemaProps anyOf = 27;
+
+  optional JSONSchemaProps not = 28;
+
+  map properties = 29;
+
+  optional JSONSchemaPropsOrBool additionalProperties = 30;
+
+  map patternProperties = 31;
+
+  map dependencies = 32;
+
+  optional JSONSchemaPropsOrBool additionalItems = 33;
+
+  map definitions = 34;
+
+  optional ExternalDocumentation externalDocs = 35;
+
+  optional JSON example = 36;
+
+  optional bool nullable = 37;
+
+  // x-kubernetes-preserve-unknown-fields stops the API server
+  // decoding step from pruning fields which are not specified
+  // in the validation schema. This affects fields recursively,
+  // but switches back to normal pruning behaviour if nested
+  // properties or additionalProperties are specified in the schema.
+  // This can either be true or undefined. False is forbidden.
+  optional bool xKubernetesPreserveUnknownFields = 38;
+
+  // x-kubernetes-embedded-resource defines that the value is an
+  // embedded Kubernetes runtime.Object, with TypeMeta and
+  // ObjectMeta. The type must be object. It is allowed to further
+  // restrict the embedded object. kind, apiVersion and metadata
+  // are validated automatically. x-kubernetes-preserve-unknown-fields
+  // is allowed to be true, but does not have to be if the object
+  // is fully specified (up to kind, apiVersion, metadata).
+  optional bool xKubernetesEmbeddedResource = 39;
+
+  // x-kubernetes-int-or-string specifies that this value is
+  // either an integer or a string. If this is true, an empty
+  // type is allowed and type as child of anyOf is permitted
+  // if following one of the following patterns:
+  //
+  // 1) anyOf:
+  //    - type: integer
+  //    - type: string
+  // 2) allOf:
+  //    - anyOf:
+  //      - type: integer
+  //      - type: string
+  //    - ... zero or more
+  optional bool xKubernetesIntOrString = 40;
+
+  // x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used
+  // as the index of the map.
+  //
+  // This tag MUST only be used on lists that have the "x-kubernetes-list-type"
+  // extension set to "map". Also, the values specified for this attribute must
+  // be a scalar typed field of the child structure (no nesting is supported).
+  //
+  // The properties specified must either be required or have a default value,
+  // to ensure those properties are present for all list items.
+  //
+  // +optional
+  // +listType=atomic
+  repeated string xKubernetesListMapKeys = 41;
+
+  // x-kubernetes-list-type annotates an array to further describe its topology.
+  // This extension must only be used on lists and may have 3 possible values:
+  //
+  // 1) `atomic`: the list is treated as a single entity, like a scalar.
+  //      Atomic lists will be entirely replaced when updated. This extension
+  //      may be used on any type of list (struct, scalar, ...).
+  // 2) `set`:
+  //      Sets are lists that must not have multiple items with the same value. Each
+  //      value must be a scalar, an object with x-kubernetes-map-type `atomic` or an
+  //      array with x-kubernetes-list-type `atomic`.
+  // 3) `map`:
+  //      These lists are like maps in that their elements have a non-index key
+  //      used to identify them. Order is preserved upon merge. The map tag
+  //      must only be used on a list with elements of type object.
+  // Defaults to atomic for arrays.
+  // +optional
+  optional string xKubernetesListType = 42;
+
+  // x-kubernetes-map-type annotates an object to further describe its topology.
+  // This extension must only be used when type is object and may have 2 possible values:
+  //
+  // 1) `granular`:
+  //      These maps are actual maps (key-value pairs) and each fields are independent
+  //      from each other (they can each be manipulated by separate actors). This is
+  //      the default behaviour for all maps.
+  // 2) `atomic`: the list is treated as a single entity, like a scalar.
+  //      Atomic maps will be entirely replaced when updated.
+  // +optional
+  optional string xKubernetesMapType = 43;
+
+  // x-kubernetes-validations describes a list of validation rules written in the CEL expression language.
+  // +patchMergeKey=rule
+  // +patchStrategy=merge
+  // +listType=map
+  // +listMapKey=rule
+  repeated ValidationRule xKubernetesValidations = 44;
+}
+
+// JSONSchemaPropsOrArray represents a value that can either be a JSONSchemaProps
+// or an array of JSONSchemaProps. Mainly here for serialization purposes.
+message JSONSchemaPropsOrArray {
+  optional JSONSchemaProps schema = 1;
+
+  // +listType=atomic
+  repeated JSONSchemaProps jSONSchemas = 2;
+}
+
+// JSONSchemaPropsOrBool represents JSONSchemaProps or a boolean value.
+// Defaults to true for the boolean property.
+message JSONSchemaPropsOrBool {
+  optional bool allows = 1;
+
+  optional JSONSchemaProps schema = 2;
+}
+
+// JSONSchemaPropsOrStringArray represents a JSONSchemaProps or a string array.
+message JSONSchemaPropsOrStringArray {
+  optional JSONSchemaProps schema = 1;
+
+  // +listType=atomic
+  repeated string property = 2;
+}
+
+// SelectableField specifies the JSON path of a field that may be used with field selectors.
+message SelectableField {
+  // jsonPath is a simple JSON path which is evaluated against each custom resource to produce a
+  // field selector value.
+  // Only JSON paths without the array notation are allowed.
+  // Must point to a field of type string, boolean or integer. Types with enum values
+  // and strings with formats are allowed.
+  // If jsonPath refers to absent field in a resource, the jsonPath evaluates to an empty string.
+  // Must not point to metdata fields.
+  // Required.
+  optional string jsonPath = 1;
+}
+
+// ServiceReference holds a reference to Service.legacy.k8s.io
+message ServiceReference {
+  // namespace is the namespace of the service.
+  // Required
+  optional string namespace = 1;
+
+  // name is the name of the service.
+  // Required
+  optional string name = 2;
+
+  // path is an optional URL path at which the webhook will be contacted.
+  // +optional
+  optional string path = 3;
+
+  // port is an optional service port at which the webhook will be contacted.
+  // `port` should be a valid port number (1-65535, inclusive).
+  // Defaults to 443 for backward compatibility.
+  // +optional
+  optional int32 port = 4;
+}
+
+// ValidationRule describes a validation rule written in the CEL expression language.
+message ValidationRule {
+  // Rule represents the expression which will be evaluated by CEL.
+  // ref: https://github.com/google/cel-spec
+  // The Rule is scoped to the location of the x-kubernetes-validations extension in the schema.
+  // The `self` variable in the CEL expression is bound to the scoped value.
+  // Example:
+  // - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"}
+  //
+  // If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable
+  // via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as
+  // absent fields in CEL expressions.
+  // If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map
+  // are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map
+  // are accessible via CEL macros and functions such as `self.all(...)`.
+  // If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and
+  // functions.
+  // If the Rule is scoped to a scalar, `self` is bound to the scalar value.
+  // Examples:
+  // - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"}
+  // - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"}
+  // - Rule scoped to a string value: {"rule": "self.startsWith('kube')"}
+  //
+  // The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the
+  // object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible.
+  //
+  // Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL
+  // expressions. This includes:
+  // - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields.
+  // - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as:
+  //   - A schema with no type and x-kubernetes-preserve-unknown-fields set to true
+  //   - An array where the items schema is of an "unknown type"
+  //   - An object where the additionalProperties schema is of an "unknown type"
+  //
+  // Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible.
+  // Accessible property names are escaped according to the following rules when accessed in the expression:
+  // - '__' escapes to '__underscores__'
+  // - '.' escapes to '__dot__'
+  // - '-' escapes to '__dash__'
+  // - '/' escapes to '__slash__'
+  // - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:
+  // 	  "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if",
+  // 	  "import", "let", "loop", "package", "namespace", "return".
+  // Examples:
+  //   - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"}
+  //   - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"}
+  //   - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"}
+  //
+  // Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1].
+  // Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:
+  //   - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and
+  //     non-intersecting elements in `Y` are appended, retaining their partial order.
+  //   - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values
+  //     are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with
+  //     non-intersecting keys are appended, retaining their partial order.
+  //
+  // If `rule` makes use of the `oldSelf` variable it is implicitly a
+  // `transition rule`.
+  //
+  // By default, the `oldSelf` variable is the same type as `self`.
+  // When `optionalOldSelf` is true, the `oldSelf` variable is a CEL optional
+  //  variable whose value() is the same type as `self`.
+  // See the documentation for the `optionalOldSelf` field for details.
+  //
+  // Transition rules by default are applied only on UPDATE requests and are
+  // skipped if an old value could not be found. You can opt a transition
+  // rule into unconditional evaluation by setting `optionalOldSelf` to true.
+  optional string rule = 1;
+
+  // Message represents the message displayed when validation fails. The message is required if the Rule contains
+  // line breaks. The message must not contain line breaks.
+  // If unset, the message is "failed rule: {Rule}".
+  // e.g. "must be a URL with the host matching spec.host"
+  optional string message = 2;
+
+  // MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails.
+  // Since messageExpression is used as a failure message, it must evaluate to a string.
+  // If both message and messageExpression are present on a rule, then messageExpression will be used if validation
+  // fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced
+  // as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string
+  // that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and
+  // the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged.
+  // messageExpression has access to all the same variables as the rule; the only difference is the return type.
+  // Example:
+  // "x must be less than max ("+string(self.max)+")"
+  // +optional
+  optional string messageExpression = 3;
+
+  // reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule.
+  // The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule.
+  // The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate".
+  // If not set, default to use "FieldValueInvalid".
+  // All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid.
+  // +optional
+  optional string reason = 4;
+
+  // fieldPath represents the field path returned when the validation fails.
+  // It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field.
+  // e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo`
+  // If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList`
+  // It does not support list numeric index.
+  // It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info.
+  // Numeric index of array is not supported.
+  // For field name which contains special characters, use `['specialName']` to refer the field name.
+  // e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']`
+  // +optional
+  optional string fieldPath = 5;
+
+  // optionalOldSelf is used to opt a transition rule into evaluation
+  // even when the object is first created, or if the old object is
+  // missing the value.
+  //
+  // When enabled `oldSelf` will be a CEL optional whose value will be
+  // `None` if there is no old value, or when the object is initially created.
+  //
+  // You may check for presence of oldSelf using `oldSelf.hasValue()` and
+  // unwrap it after checking using `oldSelf.value()`. Check the CEL
+  // documentation for Optional types for more information:
+  // https://pkg.go.dev/github.com/google/cel-go/cel#OptionalTypes
+  //
+  // May not be set unless `oldSelf` is used in `rule`.
+  //
+  // +featureGate=CRDValidationRatcheting
+  // +optional
+  optional bool optionalOldSelf = 6;
+}
+
+// WebhookClientConfig contains the information to make a TLS connection with the webhook.
+message WebhookClientConfig {
+  // url gives the location of the webhook, in standard URL form
+  // (`scheme://host:port/path`). Exactly one of `url` or `service`
+  // must be specified.
+  //
+  // The `host` should not refer to a service running in the cluster; use
+  // the `service` field instead. The host might be resolved via external
+  // DNS in some apiservers (e.g., `kube-apiserver` cannot resolve
+  // in-cluster DNS as that would be a layering violation). `host` may
+  // also be an IP address.
+  //
+  // Please note that using `localhost` or `127.0.0.1` as a `host` is
+  // risky unless you take great care to run this webhook on all hosts
+  // which run an apiserver which might need to make calls to this
+  // webhook. Such installs are likely to be non-portable, i.e., not easy
+  // to turn up in a new cluster.
+  //
+  // The scheme must be "https"; the URL must begin with "https://".
+  //
+  // A path is optional, and if present may be any string permissible in
+  // a URL. You may use the path to pass an arbitrary string to the
+  // webhook, for example, a cluster identifier.
+  //
+  // Attempting to use a user or basic auth e.g. "user:password@" is not
+  // allowed. Fragments ("#...") and query parameters ("?...") are not
+  // allowed, either.
+  //
+  // +optional
+  optional string url = 3;
+
+  // service is a reference to the service for this webhook. Either
+  // service or url must be specified.
+  //
+  // If the webhook is running within the cluster, then you should use `service`.
+  //
+  // +optional
+  optional ServiceReference service = 1;
+
+  // caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.
+  // If unspecified, system trust roots on the apiserver are used.
+  // +optional
+  optional bytes caBundle = 2;
+}
+
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go
new file mode 100644
index 000000000..5e6e82532
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go
@@ -0,0 +1,293 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+import (
+	"bytes"
+	"errors"
+
+	cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct"
+	"k8s.io/apimachinery/pkg/util/json"
+)
+
+var jsTrue = []byte("true")
+var jsFalse = []byte("false")
+
+// The CBOR parsing related constants and functions below are not exported so they can be
+// easily removed at a future date when the CBOR library provides equivalent functionality.
+
+type cborMajorType int
+
+const (
+	// https://www.rfc-editor.org/rfc/rfc8949.html#section-3.1
+	cborUnsignedInteger cborMajorType = 0
+	cborNegativeInteger cborMajorType = 1
+	cborByteString      cborMajorType = 2
+	cborTextString      cborMajorType = 3
+	cborArray           cborMajorType = 4
+	cborMap             cborMajorType = 5
+	cborTag             cborMajorType = 6
+	cborOther           cborMajorType = 7
+)
+
+const (
+	cborFalseValue = 0xf4
+	cborTrueValue  = 0xf5
+	cborNullValue  = 0xf6
+)
+
+func cborType(b byte) cborMajorType {
+	return cborMajorType(b >> 5)
+}
+
+func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error) {
+	if s.Schema != nil {
+		return json.Marshal(s.Schema)
+	}
+
+	if s.Schema == nil && !s.Allows {
+		return jsFalse, nil
+	}
+	return jsTrue, nil
+}
+
+func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error {
+	var nw JSONSchemaPropsOrBool
+	switch {
+	case len(data) == 0:
+	case data[0] == '{':
+		var sch JSONSchemaProps
+		if err := json.Unmarshal(data, &sch); err != nil {
+			return err
+		}
+		nw.Allows = true
+		nw.Schema = &sch
+	case len(data) == 4 && string(data) == "true":
+		nw.Allows = true
+	case len(data) == 5 && string(data) == "false":
+		nw.Allows = false
+	default:
+		return errors.New("boolean or JSON schema expected")
+	}
+	*s = nw
+	return nil
+}
+
+func (s JSONSchemaPropsOrBool) MarshalCBOR() ([]byte, error) {
+	if s.Schema != nil {
+		return cbor.Marshal(s.Schema)
+	}
+	return cbor.Marshal(s.Allows)
+}
+
+func (s *JSONSchemaPropsOrBool) UnmarshalCBOR(data []byte) error {
+	switch {
+	case len(data) == 0:
+		// ideally we would avoid modifying *s here, but we are matching the behavior of UnmarshalJSON
+		*s = JSONSchemaPropsOrBool{}
+		return nil
+	case cborType(data[0]) == cborMap:
+		var p JSONSchemaProps
+		if err := cbor.Unmarshal(data, &p); err != nil {
+			return err
+		}
+		*s = JSONSchemaPropsOrBool{Allows: true, Schema: &p}
+		return nil
+	case data[0] == cborTrueValue:
+		*s = JSONSchemaPropsOrBool{Allows: true}
+		return nil
+	case data[0] == cborFalseValue:
+		*s = JSONSchemaPropsOrBool{Allows: false}
+		return nil
+	default:
+		// ideally, this case would not also capture a null input value,
+		// but we are matching the behavior of the UnmarshalJSON
+		return errors.New("boolean or JSON schema expected")
+	}
+}
+
+func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error) {
+	if len(s.Property) > 0 {
+		return json.Marshal(s.Property)
+	}
+	if s.Schema != nil {
+		return json.Marshal(s.Schema)
+	}
+	return []byte("null"), nil
+}
+
+func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error {
+	var first byte
+	if len(data) > 1 {
+		first = data[0]
+	}
+	var nw JSONSchemaPropsOrStringArray
+	if first == '{' {
+		var sch JSONSchemaProps
+		if err := json.Unmarshal(data, &sch); err != nil {
+			return err
+		}
+		nw.Schema = &sch
+	}
+	if first == '[' {
+		if err := json.Unmarshal(data, &nw.Property); err != nil {
+			return err
+		}
+	}
+	*s = nw
+	return nil
+}
+
+func (s JSONSchemaPropsOrStringArray) MarshalCBOR() ([]byte, error) {
+	if len(s.Property) > 0 {
+		return cbor.Marshal(s.Property)
+	}
+	if s.Schema != nil {
+		return cbor.Marshal(s.Schema)
+	}
+	return cbor.Marshal(nil)
+}
+
+func (s *JSONSchemaPropsOrStringArray) UnmarshalCBOR(data []byte) error {
+	if len(data) > 0 && cborType(data[0]) == cborArray {
+		var a []string
+		if err := cbor.Unmarshal(data, &a); err != nil {
+			return err
+		}
+		*s = JSONSchemaPropsOrStringArray{Property: a}
+		return nil
+	}
+	if len(data) > 0 && cborType(data[0]) == cborMap {
+		var p JSONSchemaProps
+		if err := cbor.Unmarshal(data, &p); err != nil {
+			return err
+		}
+		*s = JSONSchemaPropsOrStringArray{Schema: &p}
+		return nil
+	}
+	// At this point we either have: empty data, a null value, or an
+	// unexpected type. In order to match the behavior of the existing
+	// UnmarshalJSON, no error is returned and *s is overwritten here.
+	*s = JSONSchemaPropsOrStringArray{}
+	return nil
+}
+
+func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error) {
+	if len(s.JSONSchemas) > 0 {
+		return json.Marshal(s.JSONSchemas)
+	}
+	return json.Marshal(s.Schema)
+}
+
+func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error {
+	var nw JSONSchemaPropsOrArray
+	var first byte
+	if len(data) > 1 {
+		first = data[0]
+	}
+	if first == '{' {
+		var sch JSONSchemaProps
+		if err := json.Unmarshal(data, &sch); err != nil {
+			return err
+		}
+		nw.Schema = &sch
+	}
+	if first == '[' {
+		if err := json.Unmarshal(data, &nw.JSONSchemas); err != nil {
+			return err
+		}
+	}
+	*s = nw
+	return nil
+}
+
+func (s JSONSchemaPropsOrArray) MarshalCBOR() ([]byte, error) {
+	if len(s.JSONSchemas) > 0 {
+		return cbor.Marshal(s.JSONSchemas)
+	}
+	return cbor.Marshal(s.Schema)
+}
+
+func (s *JSONSchemaPropsOrArray) UnmarshalCBOR(data []byte) error {
+	if len(data) > 0 && cborType(data[0]) == cborMap {
+		var p JSONSchemaProps
+		if err := cbor.Unmarshal(data, &p); err != nil {
+			return err
+		}
+		*s = JSONSchemaPropsOrArray{Schema: &p}
+		return nil
+	}
+	if len(data) > 0 && cborType(data[0]) == cborArray {
+		var a []JSONSchemaProps
+		if err := cbor.Unmarshal(data, &a); err != nil {
+			return err
+		}
+		*s = JSONSchemaPropsOrArray{JSONSchemas: a}
+		return nil
+	}
+	// At this point we either have: empty data, a null value, or an
+	// unexpected type. In order to match the behavior of the existing
+	// UnmarshalJSON, no error is returned and *s is overwritten here.
+	*s = JSONSchemaPropsOrArray{}
+	return nil
+}
+
+func (s JSON) MarshalJSON() ([]byte, error) {
+	if len(s.Raw) > 0 {
+		return s.Raw, nil
+	}
+	return []byte("null"), nil
+
+}
+
+func (s *JSON) UnmarshalJSON(data []byte) error {
+	if len(data) > 0 && !bytes.Equal(data, nullLiteral) {
+		s.Raw = append(s.Raw[0:0], data...)
+	}
+	return nil
+}
+
+func (s JSON) MarshalCBOR() ([]byte, error) {
+	// Note that non-semantic whitespace is lost during the transcoding performed here.
+	// We do not forsee this to be a problem given the current known uses of this type.
+	// Other limitations that arise when roundtripping JSON via dynamic clients also apply
+	// here, for example: insignificant whitespace handling, number handling, and map key ordering.
+	if len(s.Raw) == 0 {
+		return []byte{cborNullValue}, nil
+	}
+	var u any
+	if err := json.Unmarshal(s.Raw, &u); err != nil {
+		return nil, err
+	}
+	return cbor.Marshal(u)
+}
+
+func (s *JSON) UnmarshalCBOR(data []byte) error {
+	if len(data) == 0 || data[0] == cborNullValue {
+		return nil
+	}
+	var u any
+	if err := cbor.Unmarshal(data, &u); err != nil {
+		return err
+	}
+	raw, err := json.Marshal(u)
+	if err != nil {
+		return err
+	}
+	s.Raw = raw
+	return nil
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go
new file mode 100644
index 000000000..ac807211b
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go
@@ -0,0 +1,62 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+import (
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/runtime/schema"
+)
+
+const GroupName = "apiextensions.k8s.io"
+
+// SchemeGroupVersion is group version used to register these objects
+var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"}
+
+// Kind takes an unqualified kind and returns back a Group qualified GroupKind
+func Kind(kind string) schema.GroupKind {
+	return SchemeGroupVersion.WithKind(kind).GroupKind()
+}
+
+// Resource takes an unqualified resource and returns back a Group qualified GroupResource
+func Resource(resource string) schema.GroupResource {
+	return SchemeGroupVersion.WithResource(resource).GroupResource()
+}
+
+var (
+	SchemeBuilder      = runtime.NewSchemeBuilder(addKnownTypes, addDefaultingFuncs)
+	localSchemeBuilder = &SchemeBuilder
+	AddToScheme        = localSchemeBuilder.AddToScheme
+)
+
+// Adds the list of known types to the given scheme.
+func addKnownTypes(scheme *runtime.Scheme) error {
+	scheme.AddKnownTypes(SchemeGroupVersion,
+		&CustomResourceDefinition{},
+		&CustomResourceDefinitionList{},
+		&ConversionReview{},
+	)
+	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
+	return nil
+}
+
+func init() {
+	// We only register manually written functions here. The registration of the
+	// generated functions takes place in the generated files. The separation
+	// makes the code compile even when the generated files are missing.
+	localSchemeBuilder.Register(addDefaultingFuncs)
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go
new file mode 100644
index 000000000..153f72337
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go
@@ -0,0 +1,569 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+import (
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/types"
+)
+
+// ConversionStrategyType describes different conversion types.
+type ConversionStrategyType string
+
+const (
+	// KubeAPIApprovedAnnotation is an annotation that must be set to create a CRD for the k8s.io, *.k8s.io, kubernetes.io, or *.kubernetes.io namespaces.
+	// The value should be a link to a URL where the current spec was approved, so updates to the spec should also update the URL.
+	// If the API is unapproved, you may set the annotation to a string starting with `"unapproved"`.  For instance, `"unapproved, temporarily squatting"` or `"unapproved, experimental-only"`.  This is discouraged.
+	KubeAPIApprovedAnnotation = "api-approved.kubernetes.io"
+
+	// NoneConverter is a converter that only sets apiversion of the CR and leave everything else unchanged.
+	NoneConverter ConversionStrategyType = "None"
+	// WebhookConverter is a converter that calls to an external webhook to convert the CR.
+	WebhookConverter ConversionStrategyType = "Webhook"
+)
+
+// CustomResourceDefinitionSpec describes how a user wants their resource to appear
+type CustomResourceDefinitionSpec struct {
+	// group is the API group of the defined custom resource.
+	// The custom resources are served under `/apis//...`.
+	// Must match the name of the CustomResourceDefinition (in the form `.`).
+	Group string `json:"group" protobuf:"bytes,1,opt,name=group"`
+	// version is the API version of the defined custom resource.
+	// The custom resources are served under `/apis///...`.
+	// Must match the name of the first item in the `versions` list if `version` and `versions` are both specified.
+	// Optional if `versions` is specified.
+	// Deprecated: use `versions` instead.
+	// +optional
+	Version string `json:"version,omitempty" protobuf:"bytes,2,opt,name=version"`
+	// names specify the resource and kind names for the custom resource.
+	Names CustomResourceDefinitionNames `json:"names" protobuf:"bytes,3,opt,name=names"`
+	// scope indicates whether the defined custom resource is cluster- or namespace-scoped.
+	// Allowed values are `Cluster` and `Namespaced`. Default is `Namespaced`.
+	Scope ResourceScope `json:"scope" protobuf:"bytes,4,opt,name=scope,casttype=ResourceScope"`
+	// validation describes the schema used for validation and pruning of the custom resource.
+	// If present, this validation schema is used to validate all versions.
+	// Top-level and per-version schemas are mutually exclusive.
+	// +optional
+	Validation *CustomResourceValidation `json:"validation,omitempty" protobuf:"bytes,5,opt,name=validation"`
+	// subresources specify what subresources the defined custom resource has.
+	// If present, this field configures subresources for all versions.
+	// Top-level and per-version subresources are mutually exclusive.
+	// +optional
+	Subresources *CustomResourceSubresources `json:"subresources,omitempty" protobuf:"bytes,6,opt,name=subresources"`
+	// versions is the list of all API versions of the defined custom resource.
+	// Optional if `version` is specified.
+	// The name of the first item in the `versions` list must match the `version` field if `version` and `versions` are both specified.
+	// Version names are used to compute the order in which served versions are listed in API discovery.
+	// If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered
+	// lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version),
+	// then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first
+	// by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing
+	// major version, then minor version. An example sorted list of versions:
+	// v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10.
+	// +optional
+	// +listType=atomic
+	Versions []CustomResourceDefinitionVersion `json:"versions,omitempty" protobuf:"bytes,7,rep,name=versions"`
+	// additionalPrinterColumns specifies additional columns returned in Table output.
+	// See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details.
+	// If present, this field configures columns for all versions.
+	// Top-level and per-version columns are mutually exclusive.
+	// If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used.
+	// +optional
+	// +listType=atomic
+	AdditionalPrinterColumns []CustomResourceColumnDefinition `json:"additionalPrinterColumns,omitempty" protobuf:"bytes,8,rep,name=additionalPrinterColumns"`
+
+	// selectableFields specifies paths to fields that may be used as field selectors.
+	// See https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors
+	//
+	// +featureGate=CustomResourceFieldSelectors
+	// +optional
+	// +listType=atomic
+	SelectableFields []SelectableField `json:"selectableFields,omitempty" protobuf:"bytes,11,rep,name=selectableFields"`
+
+	// conversion defines conversion settings for the CRD.
+	// +optional
+	Conversion *CustomResourceConversion `json:"conversion,omitempty" protobuf:"bytes,9,opt,name=conversion"`
+
+	// preserveUnknownFields indicates that object fields which are not specified
+	// in the OpenAPI schema should be preserved when persisting to storage.
+	// apiVersion, kind, metadata and known fields inside metadata are always preserved.
+	// If false, schemas must be defined for all versions.
+	// Defaults to true in v1beta for backwards compatibility.
+	// Deprecated: will be required to be false in v1. Preservation of unknown fields can be specified
+	// in the validation schema using the `x-kubernetes-preserve-unknown-fields: true` extension.
+	// See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details.
+	// +optional
+	PreserveUnknownFields *bool `json:"preserveUnknownFields,omitempty" protobuf:"varint,10,opt,name=preserveUnknownFields"`
+}
+
+// CustomResourceConversion describes how to convert different versions of a CR.
+type CustomResourceConversion struct {
+	// strategy specifies how custom resources are converted between versions. Allowed values are:
+	// - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource.
+	// - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information
+	//   is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhookClientConfig to be set.
+	Strategy ConversionStrategyType `json:"strategy" protobuf:"bytes,1,name=strategy"`
+
+	// webhookClientConfig is the instructions for how to call the webhook if strategy is `Webhook`.
+	// Required when `strategy` is set to `Webhook`.
+	// +optional
+	WebhookClientConfig *WebhookClientConfig `json:"webhookClientConfig,omitempty" protobuf:"bytes,2,name=webhookClientConfig"`
+
+	// conversionReviewVersions is an ordered list of preferred `ConversionReview`
+	// versions the Webhook expects. The API server will use the first version in
+	// the list which it supports. If none of the versions specified in this list
+	// are supported by API server, conversion will fail for the custom resource.
+	// If a persisted Webhook configuration specifies allowed versions and does not
+	// include any versions known to the API Server, calls to the webhook will fail.
+	// Defaults to `["v1beta1"]`.
+	// +optional
+	// +listType=atomic
+	ConversionReviewVersions []string `json:"conversionReviewVersions,omitempty" protobuf:"bytes,3,rep,name=conversionReviewVersions"`
+}
+
+// WebhookClientConfig contains the information to make a TLS connection with the webhook.
+type WebhookClientConfig struct {
+	// url gives the location of the webhook, in standard URL form
+	// (`scheme://host:port/path`). Exactly one of `url` or `service`
+	// must be specified.
+	//
+	// The `host` should not refer to a service running in the cluster; use
+	// the `service` field instead. The host might be resolved via external
+	// DNS in some apiservers (e.g., `kube-apiserver` cannot resolve
+	// in-cluster DNS as that would be a layering violation). `host` may
+	// also be an IP address.
+	//
+	// Please note that using `localhost` or `127.0.0.1` as a `host` is
+	// risky unless you take great care to run this webhook on all hosts
+	// which run an apiserver which might need to make calls to this
+	// webhook. Such installs are likely to be non-portable, i.e., not easy
+	// to turn up in a new cluster.
+	//
+	// The scheme must be "https"; the URL must begin with "https://".
+	//
+	// A path is optional, and if present may be any string permissible in
+	// a URL. You may use the path to pass an arbitrary string to the
+	// webhook, for example, a cluster identifier.
+	//
+	// Attempting to use a user or basic auth e.g. "user:password@" is not
+	// allowed. Fragments ("#...") and query parameters ("?...") are not
+	// allowed, either.
+	//
+	// +optional
+	URL *string `json:"url,omitempty" protobuf:"bytes,3,opt,name=url"`
+
+	// service is a reference to the service for this webhook. Either
+	// service or url must be specified.
+	//
+	// If the webhook is running within the cluster, then you should use `service`.
+	//
+	// +optional
+	Service *ServiceReference `json:"service,omitempty" protobuf:"bytes,1,opt,name=service"`
+
+	// caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.
+	// If unspecified, system trust roots on the apiserver are used.
+	// +optional
+	CABundle []byte `json:"caBundle,omitempty" protobuf:"bytes,2,opt,name=caBundle"`
+}
+
+// ServiceReference holds a reference to Service.legacy.k8s.io
+type ServiceReference struct {
+	// namespace is the namespace of the service.
+	// Required
+	Namespace string `json:"namespace" protobuf:"bytes,1,opt,name=namespace"`
+	// name is the name of the service.
+	// Required
+	Name string `json:"name" protobuf:"bytes,2,opt,name=name"`
+
+	// path is an optional URL path at which the webhook will be contacted.
+	// +optional
+	Path *string `json:"path,omitempty" protobuf:"bytes,3,opt,name=path"`
+
+	// port is an optional service port at which the webhook will be contacted.
+	// `port` should be a valid port number (1-65535, inclusive).
+	// Defaults to 443 for backward compatibility.
+	// +optional
+	Port *int32 `json:"port,omitempty" protobuf:"varint,4,opt,name=port"`
+}
+
+// CustomResourceDefinitionVersion describes a version for CRD.
+type CustomResourceDefinitionVersion struct {
+	// name is the version name, e.g. “v1”, “v2beta1”, etc.
+	// The custom resources are served under this version at `/apis///...` if `served` is true.
+	Name string `json:"name" protobuf:"bytes,1,opt,name=name"`
+	// served is a flag enabling/disabling this version from being served via REST APIs
+	Served bool `json:"served" protobuf:"varint,2,opt,name=served"`
+	// storage indicates this version should be used when persisting custom resources to storage.
+	// There must be exactly one version with storage=true.
+	Storage bool `json:"storage" protobuf:"varint,3,opt,name=storage"`
+	// deprecated indicates this version of the custom resource API is deprecated.
+	// When set to true, API requests to this version receive a warning header in the server response.
+	// Defaults to false.
+	// +optional
+	Deprecated bool `json:"deprecated,omitempty" protobuf:"varint,7,opt,name=deprecated"`
+	// deprecationWarning overrides the default warning returned to API clients.
+	// May only be set when `deprecated` is true.
+	// The default warning indicates this version is deprecated and recommends use
+	// of the newest served version of equal or greater stability, if one exists.
+	// +optional
+	DeprecationWarning *string `json:"deprecationWarning,omitempty" protobuf:"bytes,8,opt,name=deprecationWarning"`
+	// schema describes the schema used for validation and pruning of this version of the custom resource.
+	// Top-level and per-version schemas are mutually exclusive.
+	// Per-version schemas must not all be set to identical values (top-level validation schema should be used instead).
+	// +optional
+	Schema *CustomResourceValidation `json:"schema,omitempty" protobuf:"bytes,4,opt,name=schema"`
+	// subresources specify what subresources this version of the defined custom resource have.
+	// Top-level and per-version subresources are mutually exclusive.
+	// Per-version subresources must not all be set to identical values (top-level subresources should be used instead).
+	// +optional
+	Subresources *CustomResourceSubresources `json:"subresources,omitempty" protobuf:"bytes,5,opt,name=subresources"`
+	// additionalPrinterColumns specifies additional columns returned in Table output.
+	// See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details.
+	// Top-level and per-version columns are mutually exclusive.
+	// Per-version columns must not all be set to identical values (top-level columns should be used instead).
+	// If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used.
+	// +optional
+	// +listType=atomic
+	AdditionalPrinterColumns []CustomResourceColumnDefinition `json:"additionalPrinterColumns,omitempty" protobuf:"bytes,6,rep,name=additionalPrinterColumns"`
+
+	// selectableFields specifies paths to fields that may be used as field selectors.
+	// See https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors
+	//
+	// +featureGate=CustomResourceFieldSelectors
+	// +optional
+	// +listType=atomic
+	SelectableFields []SelectableField `json:"selectableFields,omitempty" protobuf:"bytes,9,rep,name=selectableFields"`
+}
+
+// SelectableField specifies the JSON path of a field that may be used with field selectors.
+type SelectableField struct {
+	// jsonPath is a simple JSON path which is evaluated against each custom resource to produce a
+	// field selector value.
+	// Only JSON paths without the array notation are allowed.
+	// Must point to a field of type string, boolean or integer. Types with enum values
+	// and strings with formats are allowed.
+	// If jsonPath refers to absent field in a resource, the jsonPath evaluates to an empty string.
+	// Must not point to metdata fields.
+	// Required.
+	JSONPath string `json:"jsonPath" protobuf:"bytes,1,opt,name=jsonPath"`
+}
+
+// CustomResourceColumnDefinition specifies a column for server side printing.
+type CustomResourceColumnDefinition struct {
+	// name is a human readable name for the column.
+	Name string `json:"name" protobuf:"bytes,1,opt,name=name"`
+	// type is an OpenAPI type definition for this column.
+	// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details.
+	Type string `json:"type" protobuf:"bytes,2,opt,name=type"`
+	// format is an optional OpenAPI type definition for this column. The 'name' format is applied
+	// to the primary identifier column to assist in clients identifying column is the resource name.
+	// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details.
+	// +optional
+	Format string `json:"format,omitempty" protobuf:"bytes,3,opt,name=format"`
+	// description is a human readable description of this column.
+	// +optional
+	Description string `json:"description,omitempty" protobuf:"bytes,4,opt,name=description"`
+	// priority is an integer defining the relative importance of this column compared to others. Lower
+	// numbers are considered higher priority. Columns that may be omitted in limited space scenarios
+	// should be given a priority greater than 0.
+	// +optional
+	Priority int32 `json:"priority,omitempty" protobuf:"bytes,5,opt,name=priority"`
+	// JSONPath is a simple JSON path (i.e. with array notation) which is evaluated against
+	// each custom resource to produce the value for this column.
+	JSONPath string `json:"JSONPath" protobuf:"bytes,6,opt,name=JSONPath"`
+}
+
+// CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition
+type CustomResourceDefinitionNames struct {
+	// plural is the plural name of the resource to serve.
+	// The custom resources are served under `/apis///.../`.
+	// Must match the name of the CustomResourceDefinition (in the form `.`).
+	// Must be all lowercase.
+	Plural string `json:"plural" protobuf:"bytes,1,opt,name=plural"`
+	// singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`.
+	// +optional
+	Singular string `json:"singular,omitempty" protobuf:"bytes,2,opt,name=singular"`
+	// shortNames are short names for the resource, exposed in API discovery documents,
+	// and used by clients to support invocations like `kubectl get `.
+	// It must be all lowercase.
+	// +optional
+	// +listType=atomic
+	ShortNames []string `json:"shortNames,omitempty" protobuf:"bytes,3,opt,name=shortNames"`
+	// kind is the serialized kind of the resource. It is normally CamelCase and singular.
+	// Custom resource instances will use this value as the `kind` attribute in API calls.
+	Kind string `json:"kind" protobuf:"bytes,4,opt,name=kind"`
+	// listKind is the serialized kind of the list for this resource. Defaults to "`kind`List".
+	// +optional
+	ListKind string `json:"listKind,omitempty" protobuf:"bytes,5,opt,name=listKind"`
+	// categories is a list of grouped resources this custom resource belongs to (e.g. 'all').
+	// This is published in API discovery documents, and used by clients to support invocations like
+	// `kubectl get all`.
+	// +optional
+	// +listType=atomic
+	Categories []string `json:"categories,omitempty" protobuf:"bytes,6,rep,name=categories"`
+}
+
+// ResourceScope is an enum defining the different scopes available to a custom resource
+type ResourceScope string
+
+const (
+	ClusterScoped   ResourceScope = "Cluster"
+	NamespaceScoped ResourceScope = "Namespaced"
+)
+
+type ConditionStatus string
+
+// These are valid condition statuses. "ConditionTrue" means a resource is in the condition.
+// "ConditionFalse" means a resource is not in the condition. "ConditionUnknown" means kubernetes
+// can't decide if a resource is in the condition or not. In the future, we could add other
+// intermediate conditions, e.g. ConditionDegraded.
+const (
+	ConditionTrue    ConditionStatus = "True"
+	ConditionFalse   ConditionStatus = "False"
+	ConditionUnknown ConditionStatus = "Unknown"
+)
+
+// CustomResourceDefinitionConditionType is a valid value for CustomResourceDefinitionCondition.Type
+type CustomResourceDefinitionConditionType string
+
+const (
+	// Established means that the resource has become active. A resource is established when all names are
+	// accepted without a conflict for the first time. A resource stays established until deleted, even during
+	// a later NamesAccepted due to changed names. Note that not all names can be changed.
+	Established CustomResourceDefinitionConditionType = "Established"
+	// NamesAccepted means the names chosen for this CustomResourceDefinition do not conflict with others in
+	// the group and are therefore accepted.
+	NamesAccepted CustomResourceDefinitionConditionType = "NamesAccepted"
+	// NonStructuralSchema means that one or more OpenAPI schema is not structural.
+	//
+	// A schema is structural if it specifies types for all values, with the only exceptions of those with
+	// - x-kubernetes-int-or-string: true — for fields which can be integer or string
+	// - x-kubernetes-preserve-unknown-fields: true — for raw, unspecified JSON values
+	// and there is no type, additionalProperties, default, nullable or x-kubernetes-* vendor extenions
+	// specified under allOf, anyOf, oneOf or not.
+	//
+	// Non-structural schemas will not be allowed anymore in v1 API groups. Moreover, new features will not be
+	// available for non-structural CRDs:
+	// - pruning
+	// - defaulting
+	// - read-only
+	// - OpenAPI publishing
+	// - webhook conversion
+	NonStructuralSchema CustomResourceDefinitionConditionType = "NonStructuralSchema"
+	// Terminating means that the CustomResourceDefinition has been deleted and is cleaning up.
+	Terminating CustomResourceDefinitionConditionType = "Terminating"
+	// KubernetesAPIApprovalPolicyConformant indicates that an API in *.k8s.io or *.kubernetes.io is or is not approved.  For CRDs
+	// outside those groups, this condition will not be set.  For CRDs inside those groups, the condition will
+	// be true if .metadata.annotations["api-approved.kubernetes.io"] is set to a URL, otherwise it will be false.
+	// See https://github.com/kubernetes/enhancements/pull/1111 for more details.
+	KubernetesAPIApprovalPolicyConformant CustomResourceDefinitionConditionType = "KubernetesAPIApprovalPolicyConformant"
+)
+
+// CustomResourceDefinitionCondition contains details for the current condition of this pod.
+type CustomResourceDefinitionCondition struct {
+	// type is the type of the condition. Types include Established, NamesAccepted and Terminating.
+	Type CustomResourceDefinitionConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=CustomResourceDefinitionConditionType"`
+	// status is the status of the condition.
+	// Can be True, False, Unknown.
+	Status ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=ConditionStatus"`
+	// lastTransitionTime last time the condition transitioned from one status to another.
+	// +optional
+	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"`
+	// reason is a unique, one-word, CamelCase reason for the condition's last transition.
+	// +optional
+	Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"`
+	// message is a human-readable message indicating details about last transition.
+	// +optional
+	Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"`
+}
+
+// CustomResourceDefinitionStatus indicates the state of the CustomResourceDefinition
+type CustomResourceDefinitionStatus struct {
+	// conditions indicate state for particular aspects of a CustomResourceDefinition
+	// +optional
+	// +listType=map
+	// +listMapKey=type
+	Conditions []CustomResourceDefinitionCondition `json:"conditions" protobuf:"bytes,1,opt,name=conditions"`
+
+	// acceptedNames are the names that are actually being used to serve discovery.
+	// They may be different than the names in spec.
+	// +optional
+	AcceptedNames CustomResourceDefinitionNames `json:"acceptedNames" protobuf:"bytes,2,opt,name=acceptedNames"`
+
+	// storedVersions lists all versions of CustomResources that were ever persisted. Tracking these
+	// versions allows a migration path for stored versions in etcd. The field is mutable
+	// so a migration controller can finish a migration to another version (ensuring
+	// no old objects are left in storage), and then remove the rest of the
+	// versions from this list.
+	// Versions may not be removed from `spec.versions` while they exist in this list.
+	// +optional
+	// +listType=atomic
+	StoredVersions []string `json:"storedVersions" protobuf:"bytes,3,rep,name=storedVersions"`
+}
+
+// CustomResourceCleanupFinalizer is the name of the finalizer which will delete instances of
+// a CustomResourceDefinition
+const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s.io"
+
+// +genclient
+// +genclient:nonNamespaced
+// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
+// +k8s:prerelease-lifecycle-gen:introduced=1.7
+// +k8s:prerelease-lifecycle-gen:deprecated=1.16
+// +k8s:prerelease-lifecycle-gen:removed=1.22
+// +k8s:prerelease-lifecycle-gen:replacement=apiextensions.k8s.io,v1,CustomResourceDefinition
+
+// CustomResourceDefinition represents a resource that should be exposed on the API server.  Its name MUST be in the format
+// <.spec.name>.<.spec.group>.
+// Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead.
+type CustomResourceDefinition struct {
+	metav1.TypeMeta `json:",inline"`
+	// Standard object's metadata
+	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
+	// +optional
+	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
+
+	// spec describes how the user wants the resources to appear
+	Spec CustomResourceDefinitionSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`
+	// status indicates the actual state of the CustomResourceDefinition
+	// +optional
+	Status CustomResourceDefinitionStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
+}
+
+// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
+// +k8s:prerelease-lifecycle-gen:introduced=1.7
+// +k8s:prerelease-lifecycle-gen:deprecated=1.16
+// +k8s:prerelease-lifecycle-gen:removed=1.22
+// +k8s:prerelease-lifecycle-gen:replacement=apiextensions.k8s.io,v1,CustomResourceDefinitionList
+
+// CustomResourceDefinitionList is a list of CustomResourceDefinition objects.
+type CustomResourceDefinitionList struct {
+	metav1.TypeMeta `json:",inline"`
+
+	// Standard object's metadata
+	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
+	// +optional
+	metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
+
+	// items list individual CustomResourceDefinition objects
+	Items []CustomResourceDefinition `json:"items" protobuf:"bytes,2,rep,name=items"`
+}
+
+// CustomResourceValidation is a list of validation methods for CustomResources.
+type CustomResourceValidation struct {
+	// openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning.
+	// +optional
+	OpenAPIV3Schema *JSONSchemaProps `json:"openAPIV3Schema,omitempty" protobuf:"bytes,1,opt,name=openAPIV3Schema"`
+}
+
+// CustomResourceSubresources defines the status and scale subresources for CustomResources.
+type CustomResourceSubresources struct {
+	// status indicates the custom resource should serve a `/status` subresource.
+	// When enabled:
+	// 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object.
+	// 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object.
+	// +optional
+	Status *CustomResourceSubresourceStatus `json:"status,omitempty" protobuf:"bytes,1,opt,name=status"`
+	// scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object.
+	// +optional
+	Scale *CustomResourceSubresourceScale `json:"scale,omitempty" protobuf:"bytes,2,opt,name=scale"`
+}
+
+// CustomResourceSubresourceStatus defines how to serve the status subresource for CustomResources.
+// Status is represented by the `.status` JSON path inside of a CustomResource. When set,
+// * exposes a /status subresource for the custom resource
+// * PUT requests to the /status subresource take a custom resource object, and ignore changes to anything except the status stanza
+// * PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza
+type CustomResourceSubresourceStatus struct{}
+
+// CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources.
+type CustomResourceSubresourceScale struct {
+	// specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`.
+	// Only JSON paths without the array notation are allowed.
+	// Must be a JSON Path under `.spec`.
+	// If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET.
+	SpecReplicasPath string `json:"specReplicasPath" protobuf:"bytes,1,name=specReplicasPath"`
+	// statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`.
+	// Only JSON paths without the array notation are allowed.
+	// Must be a JSON Path under `.status`.
+	// If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource
+	// will default to 0.
+	StatusReplicasPath string `json:"statusReplicasPath" protobuf:"bytes,2,opt,name=statusReplicasPath"`
+	// labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`.
+	// Only JSON paths without the array notation are allowed.
+	// Must be a JSON Path under `.status` or `.spec`.
+	// Must be set to work with HorizontalPodAutoscaler.
+	// The field pointed by this JSON path must be a string field (not a complex selector struct)
+	// which contains a serialized label selector in string form.
+	// More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource
+	// If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale`
+	// subresource will default to the empty string.
+	// +optional
+	LabelSelectorPath *string `json:"labelSelectorPath,omitempty" protobuf:"bytes,3,opt,name=labelSelectorPath"`
+}
+
+// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
+// +k8s:prerelease-lifecycle-gen:introduced=1.13
+// +k8s:prerelease-lifecycle-gen:deprecated=1.19
+// This API is never served.  It is used for outbound requests from apiservers.  This will ensure it never gets served accidentally
+// and having the generator against this group will protect future APIs which may be served.
+// +k8s:prerelease-lifecycle-gen:replacement=apiextensions.k8s.io,v1,ConversionReview
+
+// ConversionReview describes a conversion request/response.
+type ConversionReview struct {
+	metav1.TypeMeta `json:",inline"`
+	// request describes the attributes for the conversion request.
+	// +optional
+	Request *ConversionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"`
+	// response describes the attributes for the conversion response.
+	// +optional
+	Response *ConversionResponse `json:"response,omitempty" protobuf:"bytes,2,opt,name=response"`
+}
+
+// ConversionRequest describes the conversion request parameters.
+type ConversionRequest struct {
+	// uid is an identifier for the individual request/response. It allows distinguishing instances of requests which are
+	// otherwise identical (parallel requests, etc).
+	// The UID is meant to track the round trip (request/response) between the Kubernetes API server and the webhook, not the user request.
+	// It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.
+	UID types.UID `json:"uid" protobuf:"bytes,1,name=uid"`
+	// desiredAPIVersion is the version to convert given objects to. e.g. "myapi.example.com/v1"
+	DesiredAPIVersion string `json:"desiredAPIVersion" protobuf:"bytes,2,name=desiredAPIVersion"`
+	// objects is the list of custom resource objects to be converted.
+	// +listType=atomic
+	Objects []runtime.RawExtension `json:"objects" protobuf:"bytes,3,rep,name=objects"`
+}
+
+// ConversionResponse describes a conversion response.
+type ConversionResponse struct {
+	// uid is an identifier for the individual request/response.
+	// This should be copied over from the corresponding `request.uid`.
+	UID types.UID `json:"uid" protobuf:"bytes,1,name=uid"`
+	// convertedObjects is the list of converted version of `request.objects` if the `result` is successful, otherwise empty.
+	// The webhook is expected to set `apiVersion` of these objects to the `request.desiredAPIVersion`. The list
+	// must also have the same size as the input list with the same objects in the same order (equal kind, metadata.uid, metadata.name and metadata.namespace).
+	// The webhook is allowed to mutate labels and annotations. Any other change to the metadata is silently ignored.
+	// +listType=atomic
+	ConvertedObjects []runtime.RawExtension `json:"convertedObjects" protobuf:"bytes,2,rep,name=convertedObjects"`
+	// result contains the result of conversion with extra details if the conversion failed. `result.status` determines if
+	// the conversion failed or succeeded. The `result.status` field is required and represents the success or failure of the
+	// conversion. A successful conversion must set `result.status` to `Success`. A failed conversion must set
+	// `result.status` to `Failure` and provide more details in `result.message` and return http status 200. The `result.message`
+	// will be used to construct an error message for the end user.
+	Result metav1.Status `json:"result" protobuf:"bytes,3,name=result"`
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go
new file mode 100644
index 000000000..3ed584dd9
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go
@@ -0,0 +1,419 @@
+/*
+Copyright 2017 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package v1beta1
+
+// FieldValueErrorReason is a machine-readable value providing more detail about why a field failed the validation.
+// +enum
+type FieldValueErrorReason string
+
+const (
+	// FieldValueRequired is used to report required values that are not
+	// provided (e.g. empty strings, null values, or empty arrays).
+	FieldValueRequired FieldValueErrorReason = "FieldValueRequired"
+	// FieldValueDuplicate is used to report collisions of values that must be
+	// unique (e.g. unique IDs).
+	FieldValueDuplicate FieldValueErrorReason = "FieldValueDuplicate"
+	// FieldValueInvalid is used to report malformed values (e.g. failed regex
+	// match, too long, out of bounds).
+	FieldValueInvalid FieldValueErrorReason = "FieldValueInvalid"
+	// FieldValueForbidden is used to report valid (as per formatting rules)
+	// values which would be accepted under some conditions, but which are not
+	// permitted by the current conditions (such as security policy).
+	FieldValueForbidden FieldValueErrorReason = "FieldValueForbidden"
+)
+
+// JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/).
+type JSONSchemaProps struct {
+	ID          string        `json:"id,omitempty" protobuf:"bytes,1,opt,name=id"`
+	Schema      JSONSchemaURL `json:"$schema,omitempty" protobuf:"bytes,2,opt,name=schema"`
+	Ref         *string       `json:"$ref,omitempty" protobuf:"bytes,3,opt,name=ref"`
+	Description string        `json:"description,omitempty" protobuf:"bytes,4,opt,name=description"`
+	Type        string        `json:"type,omitempty" protobuf:"bytes,5,opt,name=type"`
+
+	// format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated:
+	//
+	// - bsonobjectid: a bson object ID, i.e. a 24 characters hex string
+	// - uri: an URI as parsed by Golang net/url.ParseRequestURI
+	// - email: an email address as parsed by Golang net/mail.ParseAddress
+	// - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034].
+	// - ipv4: an IPv4 IP as parsed by Golang net.ParseIP
+	// - ipv6: an IPv6 IP as parsed by Golang net.ParseIP
+	// - cidr: a CIDR as parsed by Golang net.ParseCIDR
+	// - mac: a MAC address as parsed by Golang net.ParseMAC
+	// - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$
+	// - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$
+	// - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$
+	// - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$
+	// - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041"
+	// - isbn10: an ISBN10 number string like "0321751043"
+	// - isbn13: an ISBN13 number string like "978-0321751041"
+	// - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in
+	// - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$
+	// - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
+	// - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559"
+	// - byte: base64 encoded binary data
+	// - password: any kind of string
+	// - date: a date string like "2006-01-02" as defined by full-date in RFC3339
+	// - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format
+	// - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339.
+	Format string `json:"format,omitempty" protobuf:"bytes,6,opt,name=format"`
+
+	Title string `json:"title,omitempty" protobuf:"bytes,7,opt,name=title"`
+	// default is a default value for undefined object fields.
+	// Defaulting is a beta feature under the CustomResourceDefaulting feature gate.
+	// CustomResourceDefinitions with defaults must be created using the v1 (or newer) CustomResourceDefinition API.
+	Default          *JSON    `json:"default,omitempty" protobuf:"bytes,8,opt,name=default"`
+	Maximum          *float64 `json:"maximum,omitempty" protobuf:"bytes,9,opt,name=maximum"`
+	ExclusiveMaximum bool     `json:"exclusiveMaximum,omitempty" protobuf:"bytes,10,opt,name=exclusiveMaximum"`
+	Minimum          *float64 `json:"minimum,omitempty" protobuf:"bytes,11,opt,name=minimum"`
+	ExclusiveMinimum bool     `json:"exclusiveMinimum,omitempty" protobuf:"bytes,12,opt,name=exclusiveMinimum"`
+	MaxLength        *int64   `json:"maxLength,omitempty" protobuf:"bytes,13,opt,name=maxLength"`
+	MinLength        *int64   `json:"minLength,omitempty" protobuf:"bytes,14,opt,name=minLength"`
+	Pattern          string   `json:"pattern,omitempty" protobuf:"bytes,15,opt,name=pattern"`
+	MaxItems         *int64   `json:"maxItems,omitempty" protobuf:"bytes,16,opt,name=maxItems"`
+	MinItems         *int64   `json:"minItems,omitempty" protobuf:"bytes,17,opt,name=minItems"`
+	UniqueItems      bool     `json:"uniqueItems,omitempty" protobuf:"bytes,18,opt,name=uniqueItems"`
+	MultipleOf       *float64 `json:"multipleOf,omitempty" protobuf:"bytes,19,opt,name=multipleOf"`
+	// +listType=atomic
+	Enum          []JSON `json:"enum,omitempty" protobuf:"bytes,20,rep,name=enum"`
+	MaxProperties *int64 `json:"maxProperties,omitempty" protobuf:"bytes,21,opt,name=maxProperties"`
+	MinProperties *int64 `json:"minProperties,omitempty" protobuf:"bytes,22,opt,name=minProperties"`
+	// +listType=atomic
+	Required []string                `json:"required,omitempty" protobuf:"bytes,23,rep,name=required"`
+	Items    *JSONSchemaPropsOrArray `json:"items,omitempty" protobuf:"bytes,24,opt,name=items"`
+	// +listType=atomic
+	AllOf []JSONSchemaProps `json:"allOf,omitempty" protobuf:"bytes,25,rep,name=allOf"`
+	// +listType=atomic
+	OneOf []JSONSchemaProps `json:"oneOf,omitempty" protobuf:"bytes,26,rep,name=oneOf"`
+	// +listType=atomic
+	AnyOf                []JSONSchemaProps          `json:"anyOf,omitempty" protobuf:"bytes,27,rep,name=anyOf"`
+	Not                  *JSONSchemaProps           `json:"not,omitempty" protobuf:"bytes,28,opt,name=not"`
+	Properties           map[string]JSONSchemaProps `json:"properties,omitempty" protobuf:"bytes,29,rep,name=properties"`
+	AdditionalProperties *JSONSchemaPropsOrBool     `json:"additionalProperties,omitempty" protobuf:"bytes,30,opt,name=additionalProperties"`
+	PatternProperties    map[string]JSONSchemaProps `json:"patternProperties,omitempty" protobuf:"bytes,31,rep,name=patternProperties"`
+	Dependencies         JSONSchemaDependencies     `json:"dependencies,omitempty" protobuf:"bytes,32,opt,name=dependencies"`
+	AdditionalItems      *JSONSchemaPropsOrBool     `json:"additionalItems,omitempty" protobuf:"bytes,33,opt,name=additionalItems"`
+	Definitions          JSONSchemaDefinitions      `json:"definitions,omitempty" protobuf:"bytes,34,opt,name=definitions"`
+	ExternalDocs         *ExternalDocumentation     `json:"externalDocs,omitempty" protobuf:"bytes,35,opt,name=externalDocs"`
+	Example              *JSON                      `json:"example,omitempty" protobuf:"bytes,36,opt,name=example"`
+	Nullable             bool                       `json:"nullable,omitempty" protobuf:"bytes,37,opt,name=nullable"`
+
+	// x-kubernetes-preserve-unknown-fields stops the API server
+	// decoding step from pruning fields which are not specified
+	// in the validation schema. This affects fields recursively,
+	// but switches back to normal pruning behaviour if nested
+	// properties or additionalProperties are specified in the schema.
+	// This can either be true or undefined. False is forbidden.
+	XPreserveUnknownFields *bool `json:"x-kubernetes-preserve-unknown-fields,omitempty" protobuf:"bytes,38,opt,name=xKubernetesPreserveUnknownFields"`
+
+	// x-kubernetes-embedded-resource defines that the value is an
+	// embedded Kubernetes runtime.Object, with TypeMeta and
+	// ObjectMeta. The type must be object. It is allowed to further
+	// restrict the embedded object. kind, apiVersion and metadata
+	// are validated automatically. x-kubernetes-preserve-unknown-fields
+	// is allowed to be true, but does not have to be if the object
+	// is fully specified (up to kind, apiVersion, metadata).
+	XEmbeddedResource bool `json:"x-kubernetes-embedded-resource,omitempty" protobuf:"bytes,39,opt,name=xKubernetesEmbeddedResource"`
+
+	// x-kubernetes-int-or-string specifies that this value is
+	// either an integer or a string. If this is true, an empty
+	// type is allowed and type as child of anyOf is permitted
+	// if following one of the following patterns:
+	//
+	// 1) anyOf:
+	//    - type: integer
+	//    - type: string
+	// 2) allOf:
+	//    - anyOf:
+	//      - type: integer
+	//      - type: string
+	//    - ... zero or more
+	XIntOrString bool `json:"x-kubernetes-int-or-string,omitempty" protobuf:"bytes,40,opt,name=xKubernetesIntOrString"`
+
+	// x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used
+	// as the index of the map.
+	//
+	// This tag MUST only be used on lists that have the "x-kubernetes-list-type"
+	// extension set to "map". Also, the values specified for this attribute must
+	// be a scalar typed field of the child structure (no nesting is supported).
+	//
+	// The properties specified must either be required or have a default value,
+	// to ensure those properties are present for all list items.
+	//
+	// +optional
+	// +listType=atomic
+	XListMapKeys []string `json:"x-kubernetes-list-map-keys,omitempty" protobuf:"bytes,41,rep,name=xKubernetesListMapKeys"`
+
+	// x-kubernetes-list-type annotates an array to further describe its topology.
+	// This extension must only be used on lists and may have 3 possible values:
+	//
+	// 1) `atomic`: the list is treated as a single entity, like a scalar.
+	//      Atomic lists will be entirely replaced when updated. This extension
+	//      may be used on any type of list (struct, scalar, ...).
+	// 2) `set`:
+	//      Sets are lists that must not have multiple items with the same value. Each
+	//      value must be a scalar, an object with x-kubernetes-map-type `atomic` or an
+	//      array with x-kubernetes-list-type `atomic`.
+	// 3) `map`:
+	//      These lists are like maps in that their elements have a non-index key
+	//      used to identify them. Order is preserved upon merge. The map tag
+	//      must only be used on a list with elements of type object.
+	// Defaults to atomic for arrays.
+	// +optional
+	XListType *string `json:"x-kubernetes-list-type,omitempty" protobuf:"bytes,42,opt,name=xKubernetesListType"`
+
+	// x-kubernetes-map-type annotates an object to further describe its topology.
+	// This extension must only be used when type is object and may have 2 possible values:
+	//
+	// 1) `granular`:
+	//      These maps are actual maps (key-value pairs) and each fields are independent
+	//      from each other (they can each be manipulated by separate actors). This is
+	//      the default behaviour for all maps.
+	// 2) `atomic`: the list is treated as a single entity, like a scalar.
+	//      Atomic maps will be entirely replaced when updated.
+	// +optional
+	XMapType *string `json:"x-kubernetes-map-type,omitempty" protobuf:"bytes,43,opt,name=xKubernetesMapType"`
+
+	// x-kubernetes-validations describes a list of validation rules written in the CEL expression language.
+	// +patchMergeKey=rule
+	// +patchStrategy=merge
+	// +listType=map
+	// +listMapKey=rule
+	XValidations ValidationRules `json:"x-kubernetes-validations,omitempty" patchStrategy:"merge" patchMergeKey:"rule" protobuf:"bytes,44,rep,name=xKubernetesValidations"`
+}
+
+// ValidationRules describes a list of validation rules written in the CEL expression language.
+type ValidationRules []ValidationRule
+
+// ValidationRule describes a validation rule written in the CEL expression language.
+type ValidationRule struct {
+	// Rule represents the expression which will be evaluated by CEL.
+	// ref: https://github.com/google/cel-spec
+	// The Rule is scoped to the location of the x-kubernetes-validations extension in the schema.
+	// The `self` variable in the CEL expression is bound to the scoped value.
+	// Example:
+	// - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"}
+	//
+	// If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable
+	// via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as
+	// absent fields in CEL expressions.
+	// If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map
+	// are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map
+	// are accessible via CEL macros and functions such as `self.all(...)`.
+	// If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and
+	// functions.
+	// If the Rule is scoped to a scalar, `self` is bound to the scalar value.
+	// Examples:
+	// - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"}
+	// - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"}
+	// - Rule scoped to a string value: {"rule": "self.startsWith('kube')"}
+	//
+	// The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the
+	// object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible.
+	//
+	// Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL
+	// expressions. This includes:
+	// - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields.
+	// - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as:
+	//   - A schema with no type and x-kubernetes-preserve-unknown-fields set to true
+	//   - An array where the items schema is of an "unknown type"
+	//   - An object where the additionalProperties schema is of an "unknown type"
+	//
+	// Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible.
+	// Accessible property names are escaped according to the following rules when accessed in the expression:
+	// - '__' escapes to '__underscores__'
+	// - '.' escapes to '__dot__'
+	// - '-' escapes to '__dash__'
+	// - '/' escapes to '__slash__'
+	// - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:
+	//	  "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if",
+	//	  "import", "let", "loop", "package", "namespace", "return".
+	// Examples:
+	//   - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"}
+	//   - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"}
+	//   - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"}
+	//
+	// Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1].
+	// Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:
+	//   - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and
+	//     non-intersecting elements in `Y` are appended, retaining their partial order.
+	//   - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values
+	//     are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with
+	//     non-intersecting keys are appended, retaining their partial order.
+	//
+	// If `rule` makes use of the `oldSelf` variable it is implicitly a
+	// `transition rule`.
+	//
+	// By default, the `oldSelf` variable is the same type as `self`.
+	// When `optionalOldSelf` is true, the `oldSelf` variable is a CEL optional
+	//  variable whose value() is the same type as `self`.
+	// See the documentation for the `optionalOldSelf` field for details.
+	//
+	// Transition rules by default are applied only on UPDATE requests and are
+	// skipped if an old value could not be found. You can opt a transition
+	// rule into unconditional evaluation by setting `optionalOldSelf` to true.
+	//
+	Rule string `json:"rule" protobuf:"bytes,1,opt,name=rule"`
+	// Message represents the message displayed when validation fails. The message is required if the Rule contains
+	// line breaks. The message must not contain line breaks.
+	// If unset, the message is "failed rule: {Rule}".
+	// e.g. "must be a URL with the host matching spec.host"
+	Message string `json:"message,omitempty" protobuf:"bytes,2,opt,name=message"`
+	// MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails.
+	// Since messageExpression is used as a failure message, it must evaluate to a string.
+	// If both message and messageExpression are present on a rule, then messageExpression will be used if validation
+	// fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced
+	// as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string
+	// that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and
+	// the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged.
+	// messageExpression has access to all the same variables as the rule; the only difference is the return type.
+	// Example:
+	// "x must be less than max ("+string(self.max)+")"
+	// +optional
+	MessageExpression string `json:"messageExpression,omitempty" protobuf:"bytes,3,opt,name=messageExpression"`
+	// reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule.
+	// The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule.
+	// The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate".
+	// If not set, default to use "FieldValueInvalid".
+	// All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid.
+	// +optional
+	Reason *FieldValueErrorReason `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"`
+	// fieldPath represents the field path returned when the validation fails.
+	// It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field.
+	// e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo`
+	// If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList`
+	// It does not support list numeric index.
+	// It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info.
+	// Numeric index of array is not supported.
+	// For field name which contains special characters, use `['specialName']` to refer the field name.
+	// e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']`
+	// +optional
+	FieldPath string `json:"fieldPath,omitempty" protobuf:"bytes,5,opt,name=fieldPath"`
+
+	// optionalOldSelf is used to opt a transition rule into evaluation
+	// even when the object is first created, or if the old object is
+	// missing the value.
+	//
+	// When enabled `oldSelf` will be a CEL optional whose value will be
+	// `None` if there is no old value, or when the object is initially created.
+	//
+	// You may check for presence of oldSelf using `oldSelf.hasValue()` and
+	// unwrap it after checking using `oldSelf.value()`. Check the CEL
+	// documentation for Optional types for more information:
+	// https://pkg.go.dev/github.com/google/cel-go/cel#OptionalTypes
+	//
+	// May not be set unless `oldSelf` is used in `rule`.
+	//
+	// +featureGate=CRDValidationRatcheting
+	// +optional
+	OptionalOldSelf *bool `json:"optionalOldSelf,omitempty" protobuf:"bytes,6,opt,name=optionalOldSelf"`
+}
+
+// JSON represents any valid JSON value.
+// These types are supported: bool, int64, float64, string, []interface{}, map[string]interface{} and nil.
+type JSON struct {
+	Raw []byte `json:"-" protobuf:"bytes,1,opt,name=raw"`
+}
+
+// OpenAPISchemaType is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+//
+// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
+func (_ JSON) OpenAPISchemaType() []string {
+	// TODO: return actual types when anyOf is supported
+	return nil
+}
+
+// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+func (_ JSON) OpenAPISchemaFormat() string { return "" }
+
+// JSONSchemaURL represents a schema url.
+type JSONSchemaURL string
+
+// JSONSchemaPropsOrArray represents a value that can either be a JSONSchemaProps
+// or an array of JSONSchemaProps. Mainly here for serialization purposes.
+type JSONSchemaPropsOrArray struct {
+	Schema *JSONSchemaProps `protobuf:"bytes,1,opt,name=schema"`
+	// +listType=atomic
+	JSONSchemas []JSONSchemaProps `protobuf:"bytes,2,rep,name=jSONSchemas"`
+}
+
+// OpenAPISchemaType is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+//
+// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
+func (_ JSONSchemaPropsOrArray) OpenAPISchemaType() []string {
+	// TODO: return actual types when anyOf is supported
+	return nil
+}
+
+// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+func (_ JSONSchemaPropsOrArray) OpenAPISchemaFormat() string { return "" }
+
+// JSONSchemaPropsOrBool represents JSONSchemaProps or a boolean value.
+// Defaults to true for the boolean property.
+type JSONSchemaPropsOrBool struct {
+	Allows bool             `protobuf:"varint,1,opt,name=allows"`
+	Schema *JSONSchemaProps `protobuf:"bytes,2,opt,name=schema"`
+}
+
+// OpenAPISchemaType is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+//
+// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
+func (_ JSONSchemaPropsOrBool) OpenAPISchemaType() []string {
+	// TODO: return actual types when anyOf is supported
+	return nil
+}
+
+// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+func (_ JSONSchemaPropsOrBool) OpenAPISchemaFormat() string { return "" }
+
+// JSONSchemaDependencies represent a dependencies property.
+type JSONSchemaDependencies map[string]JSONSchemaPropsOrStringArray
+
+// JSONSchemaPropsOrStringArray represents a JSONSchemaProps or a string array.
+type JSONSchemaPropsOrStringArray struct {
+	Schema *JSONSchemaProps `protobuf:"bytes,1,opt,name=schema"`
+	// +listType=atomic
+	Property []string `protobuf:"bytes,2,rep,name=property"`
+}
+
+// OpenAPISchemaType is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+//
+// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
+func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaType() []string {
+	// TODO: return actual types when anyOf is supported
+	return nil
+}
+
+// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
+// the OpenAPI spec of this type.
+func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaFormat() string { return "" }
+
+// JSONSchemaDefinitions contains the models explicitly defined in this spec.
+type JSONSchemaDefinitions map[string]JSONSchemaProps
+
+// ExternalDocumentation allows referencing an external resource for extended documentation.
+type ExternalDocumentation struct {
+	Description string `json:"description,omitempty" protobuf:"bytes,1,opt,name=description"`
+	URL         string `json:"url,omitempty" protobuf:"bytes,2,opt,name=url"`
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go
new file mode 100644
index 000000000..d59274e8d
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go
@@ -0,0 +1,1408 @@
+//go:build !ignore_autogenerated
+// +build !ignore_autogenerated
+
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by conversion-gen. DO NOT EDIT.
+
+package v1beta1
+
+import (
+	unsafe "unsafe"
+
+	apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
+	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	conversion "k8s.io/apimachinery/pkg/conversion"
+	runtime "k8s.io/apimachinery/pkg/runtime"
+)
+
+func init() {
+	localSchemeBuilder.Register(RegisterConversions)
+}
+
+// RegisterConversions adds conversion functions to the given scheme.
+// Public to allow building arbitrary schemes.
+func RegisterConversions(s *runtime.Scheme) error {
+	if err := s.AddGeneratedConversionFunc((*CustomResourceColumnDefinition)(nil), (*apiextensions.CustomResourceColumnDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(a.(*CustomResourceColumnDefinition), b.(*apiextensions.CustomResourceColumnDefinition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceColumnDefinition)(nil), (*CustomResourceColumnDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(a.(*apiextensions.CustomResourceColumnDefinition), b.(*CustomResourceColumnDefinition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceConversion)(nil), (*apiextensions.CustomResourceConversion)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(a.(*CustomResourceConversion), b.(*apiextensions.CustomResourceConversion), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceConversion)(nil), (*CustomResourceConversion)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion(a.(*apiextensions.CustomResourceConversion), b.(*CustomResourceConversion), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinition)(nil), (*apiextensions.CustomResourceDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(a.(*CustomResourceDefinition), b.(*apiextensions.CustomResourceDefinition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinition)(nil), (*CustomResourceDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(a.(*apiextensions.CustomResourceDefinition), b.(*CustomResourceDefinition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionCondition)(nil), (*apiextensions.CustomResourceDefinitionCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(a.(*CustomResourceDefinitionCondition), b.(*apiextensions.CustomResourceDefinitionCondition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionCondition)(nil), (*CustomResourceDefinitionCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(a.(*apiextensions.CustomResourceDefinitionCondition), b.(*CustomResourceDefinitionCondition), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionList)(nil), (*apiextensions.CustomResourceDefinitionList)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionList_To_apiextensions_CustomResourceDefinitionList(a.(*CustomResourceDefinitionList), b.(*apiextensions.CustomResourceDefinitionList), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionList)(nil), (*CustomResourceDefinitionList)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourceDefinitionList(a.(*apiextensions.CustomResourceDefinitionList), b.(*CustomResourceDefinitionList), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionNames)(nil), (*apiextensions.CustomResourceDefinitionNames)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(a.(*CustomResourceDefinitionNames), b.(*apiextensions.CustomResourceDefinitionNames), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionNames)(nil), (*CustomResourceDefinitionNames)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(a.(*apiextensions.CustomResourceDefinitionNames), b.(*CustomResourceDefinitionNames), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionSpec)(nil), (*apiextensions.CustomResourceDefinitionSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(a.(*CustomResourceDefinitionSpec), b.(*apiextensions.CustomResourceDefinitionSpec), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionSpec)(nil), (*CustomResourceDefinitionSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec(a.(*apiextensions.CustomResourceDefinitionSpec), b.(*CustomResourceDefinitionSpec), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionStatus)(nil), (*apiextensions.CustomResourceDefinitionStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(a.(*CustomResourceDefinitionStatus), b.(*apiextensions.CustomResourceDefinitionStatus), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionStatus)(nil), (*CustomResourceDefinitionStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(a.(*apiextensions.CustomResourceDefinitionStatus), b.(*CustomResourceDefinitionStatus), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceDefinitionVersion)(nil), (*apiextensions.CustomResourceDefinitionVersion)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion(a.(*CustomResourceDefinitionVersion), b.(*apiextensions.CustomResourceDefinitionVersion), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceDefinitionVersion)(nil), (*CustomResourceDefinitionVersion)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion(a.(*apiextensions.CustomResourceDefinitionVersion), b.(*CustomResourceDefinitionVersion), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceSubresourceScale)(nil), (*apiextensions.CustomResourceSubresourceScale)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(a.(*CustomResourceSubresourceScale), b.(*apiextensions.CustomResourceSubresourceScale), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceSubresourceScale)(nil), (*CustomResourceSubresourceScale)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(a.(*apiextensions.CustomResourceSubresourceScale), b.(*CustomResourceSubresourceScale), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceSubresourceStatus)(nil), (*apiextensions.CustomResourceSubresourceStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(a.(*CustomResourceSubresourceStatus), b.(*apiextensions.CustomResourceSubresourceStatus), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceSubresourceStatus)(nil), (*CustomResourceSubresourceStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(a.(*apiextensions.CustomResourceSubresourceStatus), b.(*CustomResourceSubresourceStatus), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceSubresources)(nil), (*apiextensions.CustomResourceSubresources)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(a.(*CustomResourceSubresources), b.(*apiextensions.CustomResourceSubresources), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceSubresources)(nil), (*CustomResourceSubresources)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(a.(*apiextensions.CustomResourceSubresources), b.(*CustomResourceSubresources), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*CustomResourceValidation)(nil), (*apiextensions.CustomResourceValidation)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(a.(*CustomResourceValidation), b.(*apiextensions.CustomResourceValidation), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.CustomResourceValidation)(nil), (*CustomResourceValidation)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(a.(*apiextensions.CustomResourceValidation), b.(*CustomResourceValidation), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*ExternalDocumentation)(nil), (*apiextensions.ExternalDocumentation)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(a.(*ExternalDocumentation), b.(*apiextensions.ExternalDocumentation), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.ExternalDocumentation)(nil), (*ExternalDocumentation)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(a.(*apiextensions.ExternalDocumentation), b.(*ExternalDocumentation), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*JSONSchemaProps)(nil), (*apiextensions.JSONSchemaProps)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(a.(*JSONSchemaProps), b.(*apiextensions.JSONSchemaProps), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*JSONSchemaPropsOrArray)(nil), (*apiextensions.JSONSchemaPropsOrArray)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray(a.(*JSONSchemaPropsOrArray), b.(*apiextensions.JSONSchemaPropsOrArray), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.JSONSchemaPropsOrArray)(nil), (*JSONSchemaPropsOrArray)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray(a.(*apiextensions.JSONSchemaPropsOrArray), b.(*JSONSchemaPropsOrArray), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*JSONSchemaPropsOrBool)(nil), (*apiextensions.JSONSchemaPropsOrBool)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(a.(*JSONSchemaPropsOrBool), b.(*apiextensions.JSONSchemaPropsOrBool), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.JSONSchemaPropsOrBool)(nil), (*JSONSchemaPropsOrBool)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(a.(*apiextensions.JSONSchemaPropsOrBool), b.(*JSONSchemaPropsOrBool), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*JSONSchemaPropsOrStringArray)(nil), (*apiextensions.JSONSchemaPropsOrStringArray)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray(a.(*JSONSchemaPropsOrStringArray), b.(*apiextensions.JSONSchemaPropsOrStringArray), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.JSONSchemaPropsOrStringArray)(nil), (*JSONSchemaPropsOrStringArray)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray(a.(*apiextensions.JSONSchemaPropsOrStringArray), b.(*JSONSchemaPropsOrStringArray), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*SelectableField)(nil), (*apiextensions.SelectableField)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_SelectableField_To_apiextensions_SelectableField(a.(*SelectableField), b.(*apiextensions.SelectableField), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.SelectableField)(nil), (*SelectableField)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_SelectableField_To_v1beta1_SelectableField(a.(*apiextensions.SelectableField), b.(*SelectableField), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*ServiceReference)(nil), (*apiextensions.ServiceReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_ServiceReference_To_apiextensions_ServiceReference(a.(*ServiceReference), b.(*apiextensions.ServiceReference), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.ServiceReference)(nil), (*ServiceReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(a.(*apiextensions.ServiceReference), b.(*ServiceReference), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*ValidationRule)(nil), (*apiextensions.ValidationRule)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(a.(*ValidationRule), b.(*apiextensions.ValidationRule), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.ValidationRule)(nil), (*ValidationRule)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(a.(*apiextensions.ValidationRule), b.(*ValidationRule), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*WebhookClientConfig)(nil), (*apiextensions.WebhookClientConfig)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(a.(*WebhookClientConfig), b.(*apiextensions.WebhookClientConfig), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddGeneratedConversionFunc((*apiextensions.WebhookClientConfig)(nil), (*WebhookClientConfig)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig(a.(*apiextensions.WebhookClientConfig), b.(*WebhookClientConfig), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddConversionFunc((*apiextensions.JSONSchemaProps)(nil), (*JSONSchemaProps)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(a.(*apiextensions.JSONSchemaProps), b.(*JSONSchemaProps), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddConversionFunc((*apiextensions.JSON)(nil), (*JSON)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_apiextensions_JSON_To_v1beta1_JSON(a.(*apiextensions.JSON), b.(*JSON), scope)
+	}); err != nil {
+		return err
+	}
+	if err := s.AddConversionFunc((*JSON)(nil), (*apiextensions.JSON)(nil), func(a, b interface{}, scope conversion.Scope) error {
+		return Convert_v1beta1_JSON_To_apiextensions_JSON(a.(*JSON), b.(*apiextensions.JSON), scope)
+	}); err != nil {
+		return err
+	}
+	return nil
+}
+
+func autoConvert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error {
+	out.Name = in.Name
+	out.Type = in.Type
+	out.Format = in.Format
+	out.Description = in.Description
+	out.Priority = in.Priority
+	out.JSONPath = in.JSONPath
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error {
+	out.Name = in.Name
+	out.Type = in.Type
+	out.Format = in.Format
+	out.Description = in.Description
+	out.Priority = in.Priority
+	out.JSONPath = in.JSONPath
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in *CustomResourceConversion, out *apiextensions.CustomResourceConversion, s conversion.Scope) error {
+	out.Strategy = apiextensions.ConversionStrategyType(in.Strategy)
+	if in.WebhookClientConfig != nil {
+		in, out := &in.WebhookClientConfig, &out.WebhookClientConfig
+		*out = new(apiextensions.WebhookClientConfig)
+		if err := Convert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.WebhookClientConfig = nil
+	}
+	out.ConversionReviewVersions = *(*[]string)(unsafe.Pointer(&in.ConversionReviewVersions))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in *CustomResourceConversion, out *apiextensions.CustomResourceConversion, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion(in *apiextensions.CustomResourceConversion, out *CustomResourceConversion, s conversion.Scope) error {
+	out.Strategy = ConversionStrategyType(in.Strategy)
+	if in.WebhookClientConfig != nil {
+		in, out := &in.WebhookClientConfig, &out.WebhookClientConfig
+		*out = new(WebhookClientConfig)
+		if err := Convert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.WebhookClientConfig = nil
+	}
+	out.ConversionReviewVersions = *(*[]string)(unsafe.Pointer(&in.ConversionReviewVersions))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion(in *apiextensions.CustomResourceConversion, out *CustomResourceConversion, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(in *CustomResourceDefinition, out *apiextensions.CustomResourceDefinition, s conversion.Scope) error {
+	out.ObjectMeta = in.ObjectMeta
+	if err := Convert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(&in.Spec, &out.Spec, s); err != nil {
+		return err
+	}
+	if err := Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(&in.Status, &out.Status, s); err != nil {
+		return err
+	}
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(in *CustomResourceDefinition, out *apiextensions.CustomResourceDefinition, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(in *apiextensions.CustomResourceDefinition, out *CustomResourceDefinition, s conversion.Scope) error {
+	out.ObjectMeta = in.ObjectMeta
+	if err := Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec(&in.Spec, &out.Spec, s); err != nil {
+		return err
+	}
+	if err := Convert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(&in.Status, &out.Status, s); err != nil {
+		return err
+	}
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(in *apiextensions.CustomResourceDefinition, out *CustomResourceDefinition, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error {
+	out.Type = apiextensions.CustomResourceDefinitionConditionType(in.Type)
+	out.Status = apiextensions.ConditionStatus(in.Status)
+	out.LastTransitionTime = in.LastTransitionTime
+	out.Reason = in.Reason
+	out.Message = in.Message
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error {
+	out.Type = CustomResourceDefinitionConditionType(in.Type)
+	out.Status = ConditionStatus(in.Status)
+	out.LastTransitionTime = in.LastTransitionTime
+	out.Reason = in.Reason
+	out.Message = in.Message
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionList_To_apiextensions_CustomResourceDefinitionList(in *CustomResourceDefinitionList, out *apiextensions.CustomResourceDefinitionList, s conversion.Scope) error {
+	out.ListMeta = in.ListMeta
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		*out = make([]apiextensions.CustomResourceDefinition, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Items = nil
+	}
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionList_To_apiextensions_CustomResourceDefinitionList is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionList_To_apiextensions_CustomResourceDefinitionList(in *CustomResourceDefinitionList, out *apiextensions.CustomResourceDefinitionList, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionList_To_apiextensions_CustomResourceDefinitionList(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourceDefinitionList(in *apiextensions.CustomResourceDefinitionList, out *CustomResourceDefinitionList, s conversion.Scope) error {
+	out.ListMeta = in.ListMeta
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		*out = make([]CustomResourceDefinition, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Items = nil
+	}
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourceDefinitionList is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourceDefinitionList(in *apiextensions.CustomResourceDefinitionList, out *CustomResourceDefinitionList, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourceDefinitionList(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error {
+	out.Plural = in.Plural
+	out.Singular = in.Singular
+	out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames))
+	out.Kind = in.Kind
+	out.ListKind = in.ListKind
+	out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error {
+	out.Plural = in.Plural
+	out.Singular = in.Singular
+	out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames))
+	out.Kind = in.Kind
+	out.ListKind = in.ListKind
+	out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in *CustomResourceDefinitionSpec, out *apiextensions.CustomResourceDefinitionSpec, s conversion.Scope) error {
+	out.Group = in.Group
+	out.Version = in.Version
+	if err := Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.Names, &out.Names, s); err != nil {
+		return err
+	}
+	out.Scope = apiextensions.ResourceScope(in.Scope)
+	if in.Validation != nil {
+		in, out := &in.Validation, &out.Validation
+		*out = new(apiextensions.CustomResourceValidation)
+		if err := Convert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Validation = nil
+	}
+	out.Subresources = (*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in.Subresources))
+	if in.Versions != nil {
+		in, out := &in.Versions, &out.Versions
+		*out = make([]apiextensions.CustomResourceDefinitionVersion, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Versions = nil
+	}
+	out.AdditionalPrinterColumns = *(*[]apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(&in.AdditionalPrinterColumns))
+	out.SelectableFields = *(*[]apiextensions.SelectableField)(unsafe.Pointer(&in.SelectableFields))
+	if in.Conversion != nil {
+		in, out := &in.Conversion, &out.Conversion
+		*out = new(apiextensions.CustomResourceConversion)
+		if err := Convert_v1beta1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Conversion = nil
+	}
+	out.PreserveUnknownFields = (*bool)(unsafe.Pointer(in.PreserveUnknownFields))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in *CustomResourceDefinitionSpec, out *apiextensions.CustomResourceDefinitionSpec, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec(in *apiextensions.CustomResourceDefinitionSpec, out *CustomResourceDefinitionSpec, s conversion.Scope) error {
+	out.Group = in.Group
+	out.Version = in.Version
+	if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(&in.Names, &out.Names, s); err != nil {
+		return err
+	}
+	out.Scope = ResourceScope(in.Scope)
+	if in.Validation != nil {
+		in, out := &in.Validation, &out.Validation
+		*out = new(CustomResourceValidation)
+		if err := Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Validation = nil
+	}
+	out.Subresources = (*CustomResourceSubresources)(unsafe.Pointer(in.Subresources))
+	if in.Versions != nil {
+		in, out := &in.Versions, &out.Versions
+		*out = make([]CustomResourceDefinitionVersion, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Versions = nil
+	}
+	out.AdditionalPrinterColumns = *(*[]CustomResourceColumnDefinition)(unsafe.Pointer(&in.AdditionalPrinterColumns))
+	out.SelectableFields = *(*[]SelectableField)(unsafe.Pointer(&in.SelectableFields))
+	if in.Conversion != nil {
+		in, out := &in.Conversion, &out.Conversion
+		*out = new(CustomResourceConversion)
+		if err := Convert_apiextensions_CustomResourceConversion_To_v1beta1_CustomResourceConversion(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Conversion = nil
+	}
+	out.PreserveUnknownFields = (*bool)(unsafe.Pointer(in.PreserveUnknownFields))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec(in *apiextensions.CustomResourceDefinitionSpec, out *CustomResourceDefinitionSpec, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourceDefinitionSpec(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error {
+	out.Conditions = *(*[]apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions))
+	if err := Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil {
+		return err
+	}
+	out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error {
+	out.Conditions = *(*[]CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions))
+	if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil {
+		return err
+	}
+	out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion(in *CustomResourceDefinitionVersion, out *apiextensions.CustomResourceDefinitionVersion, s conversion.Scope) error {
+	out.Name = in.Name
+	out.Served = in.Served
+	out.Storage = in.Storage
+	out.Deprecated = in.Deprecated
+	out.DeprecationWarning = (*string)(unsafe.Pointer(in.DeprecationWarning))
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(apiextensions.CustomResourceValidation)
+		if err := Convert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	out.Subresources = (*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in.Subresources))
+	out.AdditionalPrinterColumns = *(*[]apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(&in.AdditionalPrinterColumns))
+	out.SelectableFields = *(*[]apiextensions.SelectableField)(unsafe.Pointer(&in.SelectableFields))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion(in *CustomResourceDefinitionVersion, out *apiextensions.CustomResourceDefinitionVersion, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceDefinitionVersion_To_apiextensions_CustomResourceDefinitionVersion(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion(in *apiextensions.CustomResourceDefinitionVersion, out *CustomResourceDefinitionVersion, s conversion.Scope) error {
+	out.Name = in.Name
+	out.Served = in.Served
+	out.Storage = in.Storage
+	out.Deprecated = in.Deprecated
+	out.DeprecationWarning = (*string)(unsafe.Pointer(in.DeprecationWarning))
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(CustomResourceValidation)
+		if err := Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	out.Subresources = (*CustomResourceSubresources)(unsafe.Pointer(in.Subresources))
+	out.AdditionalPrinterColumns = *(*[]CustomResourceColumnDefinition)(unsafe.Pointer(&in.AdditionalPrinterColumns))
+	out.SelectableFields = *(*[]SelectableField)(unsafe.Pointer(&in.SelectableFields))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion(in *apiextensions.CustomResourceDefinitionVersion, out *CustomResourceDefinitionVersion, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomResourceDefinitionVersion(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error {
+	out.SpecReplicasPath = in.SpecReplicasPath
+	out.StatusReplicasPath = in.StatusReplicasPath
+	out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error {
+	out.SpecReplicasPath = in.SpecReplicasPath
+	out.StatusReplicasPath = in.StatusReplicasPath
+	out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error {
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error {
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error {
+	out.Status = (*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status))
+	out.Scale = (*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale))
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error {
+	out.Status = (*CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status))
+	out.Scale = (*CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale))
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(in, out, s)
+}
+
+func autoConvert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(in *CustomResourceValidation, out *apiextensions.CustomResourceValidation, s conversion.Scope) error {
+	if in.OpenAPIV3Schema != nil {
+		in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema
+		*out = new(apiextensions.JSONSchemaProps)
+		if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.OpenAPIV3Schema = nil
+	}
+	return nil
+}
+
+// Convert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation is an autogenerated conversion function.
+func Convert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(in *CustomResourceValidation, out *apiextensions.CustomResourceValidation, s conversion.Scope) error {
+	return autoConvert_v1beta1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(in, out, s)
+}
+
+func autoConvert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(in *apiextensions.CustomResourceValidation, out *CustomResourceValidation, s conversion.Scope) error {
+	if in.OpenAPIV3Schema != nil {
+		in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema
+		*out = new(JSONSchemaProps)
+		if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.OpenAPIV3Schema = nil
+	}
+	return nil
+}
+
+// Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation is an autogenerated conversion function.
+func Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(in *apiextensions.CustomResourceValidation, out *CustomResourceValidation, s conversion.Scope) error {
+	return autoConvert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceValidation(in, out, s)
+}
+
+func autoConvert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error {
+	out.Description = in.Description
+	out.URL = in.URL
+	return nil
+}
+
+// Convert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation is an autogenerated conversion function.
+func Convert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error {
+	return autoConvert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in, out, s)
+}
+
+func autoConvert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error {
+	out.Description = in.Description
+	out.URL = in.URL
+	return nil
+}
+
+// Convert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation is an autogenerated conversion function.
+func Convert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error {
+	return autoConvert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(in, out, s)
+}
+
+func autoConvert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {
+	// WARNING: in.Raw requires manual conversion: does not exist in peer-type
+	return nil
+}
+
+func autoConvert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error {
+	// FIXME: Type apiextensions.JSON is unsupported.
+	return nil
+}
+
+func autoConvert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(in *JSONSchemaProps, out *apiextensions.JSONSchemaProps, s conversion.Scope) error {
+	out.ID = in.ID
+	out.Schema = apiextensions.JSONSchemaURL(in.Schema)
+	out.Ref = (*string)(unsafe.Pointer(in.Ref))
+	out.Description = in.Description
+	out.Type = in.Type
+	out.Format = in.Format
+	out.Title = in.Title
+	if in.Default != nil {
+		in, out := &in.Default, &out.Default
+		*out = new(apiextensions.JSON)
+		if err := Convert_v1beta1_JSON_To_apiextensions_JSON(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Default = nil
+	}
+	out.Maximum = (*float64)(unsafe.Pointer(in.Maximum))
+	out.ExclusiveMaximum = in.ExclusiveMaximum
+	out.Minimum = (*float64)(unsafe.Pointer(in.Minimum))
+	out.ExclusiveMinimum = in.ExclusiveMinimum
+	out.MaxLength = (*int64)(unsafe.Pointer(in.MaxLength))
+	out.MinLength = (*int64)(unsafe.Pointer(in.MinLength))
+	out.Pattern = in.Pattern
+	out.MaxItems = (*int64)(unsafe.Pointer(in.MaxItems))
+	out.MinItems = (*int64)(unsafe.Pointer(in.MinItems))
+	out.UniqueItems = in.UniqueItems
+	out.MultipleOf = (*float64)(unsafe.Pointer(in.MultipleOf))
+	if in.Enum != nil {
+		in, out := &in.Enum, &out.Enum
+		*out = make([]apiextensions.JSON, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_JSON_To_apiextensions_JSON(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Enum = nil
+	}
+	out.MaxProperties = (*int64)(unsafe.Pointer(in.MaxProperties))
+	out.MinProperties = (*int64)(unsafe.Pointer(in.MinProperties))
+	out.Required = *(*[]string)(unsafe.Pointer(&in.Required))
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		*out = new(apiextensions.JSONSchemaPropsOrArray)
+		if err := Convert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Items = nil
+	}
+	if in.AllOf != nil {
+		in, out := &in.AllOf, &out.AllOf
+		*out = make([]apiextensions.JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.AllOf = nil
+	}
+	if in.OneOf != nil {
+		in, out := &in.OneOf, &out.OneOf
+		*out = make([]apiextensions.JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.OneOf = nil
+	}
+	if in.AnyOf != nil {
+		in, out := &in.AnyOf, &out.AnyOf
+		*out = make([]apiextensions.JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.AnyOf = nil
+	}
+	if in.Not != nil {
+		in, out := &in.Not, &out.Not
+		*out = new(apiextensions.JSONSchemaProps)
+		if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Not = nil
+	}
+	if in.Properties != nil {
+		in, out := &in.Properties, &out.Properties
+		*out = make(map[string]apiextensions.JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			newVal := new(apiextensions.JSONSchemaProps)
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Properties = nil
+	}
+	if in.AdditionalProperties != nil {
+		in, out := &in.AdditionalProperties, &out.AdditionalProperties
+		*out = new(apiextensions.JSONSchemaPropsOrBool)
+		if err := Convert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.AdditionalProperties = nil
+	}
+	if in.PatternProperties != nil {
+		in, out := &in.PatternProperties, &out.PatternProperties
+		*out = make(map[string]apiextensions.JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			newVal := new(apiextensions.JSONSchemaProps)
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.PatternProperties = nil
+	}
+	if in.Dependencies != nil {
+		in, out := &in.Dependencies, &out.Dependencies
+		*out = make(apiextensions.JSONSchemaDependencies, len(*in))
+		for key, val := range *in {
+			newVal := new(apiextensions.JSONSchemaPropsOrStringArray)
+			if err := Convert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Dependencies = nil
+	}
+	if in.AdditionalItems != nil {
+		in, out := &in.AdditionalItems, &out.AdditionalItems
+		*out = new(apiextensions.JSONSchemaPropsOrBool)
+		if err := Convert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.AdditionalItems = nil
+	}
+	if in.Definitions != nil {
+		in, out := &in.Definitions, &out.Definitions
+		*out = make(apiextensions.JSONSchemaDefinitions, len(*in))
+		for key, val := range *in {
+			newVal := new(apiextensions.JSONSchemaProps)
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Definitions = nil
+	}
+	out.ExternalDocs = (*apiextensions.ExternalDocumentation)(unsafe.Pointer(in.ExternalDocs))
+	if in.Example != nil {
+		in, out := &in.Example, &out.Example
+		*out = new(apiextensions.JSON)
+		if err := Convert_v1beta1_JSON_To_apiextensions_JSON(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Example = nil
+	}
+	out.Nullable = in.Nullable
+	out.XPreserveUnknownFields = (*bool)(unsafe.Pointer(in.XPreserveUnknownFields))
+	out.XEmbeddedResource = in.XEmbeddedResource
+	out.XIntOrString = in.XIntOrString
+	out.XListMapKeys = *(*[]string)(unsafe.Pointer(&in.XListMapKeys))
+	out.XListType = (*string)(unsafe.Pointer(in.XListType))
+	out.XMapType = (*string)(unsafe.Pointer(in.XMapType))
+	out.XValidations = *(*apiextensions.ValidationRules)(unsafe.Pointer(&in.XValidations))
+	return nil
+}
+
+// Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps is an autogenerated conversion function.
+func Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(in *JSONSchemaProps, out *apiextensions.JSONSchemaProps, s conversion.Scope) error {
+	return autoConvert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(in, out, s)
+}
+
+func autoConvert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {
+	out.ID = in.ID
+	out.Schema = JSONSchemaURL(in.Schema)
+	out.Ref = (*string)(unsafe.Pointer(in.Ref))
+	out.Description = in.Description
+	out.Type = in.Type
+	out.Nullable = in.Nullable
+	out.Format = in.Format
+	out.Title = in.Title
+	if in.Default != nil {
+		in, out := &in.Default, &out.Default
+		*out = new(JSON)
+		if err := Convert_apiextensions_JSON_To_v1beta1_JSON(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Default = nil
+	}
+	out.Maximum = (*float64)(unsafe.Pointer(in.Maximum))
+	out.ExclusiveMaximum = in.ExclusiveMaximum
+	out.Minimum = (*float64)(unsafe.Pointer(in.Minimum))
+	out.ExclusiveMinimum = in.ExclusiveMinimum
+	out.MaxLength = (*int64)(unsafe.Pointer(in.MaxLength))
+	out.MinLength = (*int64)(unsafe.Pointer(in.MinLength))
+	out.Pattern = in.Pattern
+	out.MaxItems = (*int64)(unsafe.Pointer(in.MaxItems))
+	out.MinItems = (*int64)(unsafe.Pointer(in.MinItems))
+	out.UniqueItems = in.UniqueItems
+	out.MultipleOf = (*float64)(unsafe.Pointer(in.MultipleOf))
+	if in.Enum != nil {
+		in, out := &in.Enum, &out.Enum
+		*out = make([]JSON, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_JSON_To_v1beta1_JSON(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.Enum = nil
+	}
+	out.MaxProperties = (*int64)(unsafe.Pointer(in.MaxProperties))
+	out.MinProperties = (*int64)(unsafe.Pointer(in.MinProperties))
+	out.Required = *(*[]string)(unsafe.Pointer(&in.Required))
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		*out = new(JSONSchemaPropsOrArray)
+		if err := Convert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Items = nil
+	}
+	if in.AllOf != nil {
+		in, out := &in.AllOf, &out.AllOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.AllOf = nil
+	}
+	if in.OneOf != nil {
+		in, out := &in.OneOf, &out.OneOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.OneOf = nil
+	}
+	if in.AnyOf != nil {
+		in, out := &in.AnyOf, &out.AnyOf
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.AnyOf = nil
+	}
+	if in.Not != nil {
+		in, out := &in.Not, &out.Not
+		*out = new(JSONSchemaProps)
+		if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Not = nil
+	}
+	if in.Properties != nil {
+		in, out := &in.Properties, &out.Properties
+		*out = make(map[string]JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			newVal := new(JSONSchemaProps)
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Properties = nil
+	}
+	if in.AdditionalProperties != nil {
+		in, out := &in.AdditionalProperties, &out.AdditionalProperties
+		*out = new(JSONSchemaPropsOrBool)
+		if err := Convert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.AdditionalProperties = nil
+	}
+	if in.PatternProperties != nil {
+		in, out := &in.PatternProperties, &out.PatternProperties
+		*out = make(map[string]JSONSchemaProps, len(*in))
+		for key, val := range *in {
+			newVal := new(JSONSchemaProps)
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.PatternProperties = nil
+	}
+	if in.Dependencies != nil {
+		in, out := &in.Dependencies, &out.Dependencies
+		*out = make(JSONSchemaDependencies, len(*in))
+		for key, val := range *in {
+			newVal := new(JSONSchemaPropsOrStringArray)
+			if err := Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Dependencies = nil
+	}
+	if in.AdditionalItems != nil {
+		in, out := &in.AdditionalItems, &out.AdditionalItems
+		*out = new(JSONSchemaPropsOrBool)
+		if err := Convert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.AdditionalItems = nil
+	}
+	if in.Definitions != nil {
+		in, out := &in.Definitions, &out.Definitions
+		*out = make(JSONSchemaDefinitions, len(*in))
+		for key, val := range *in {
+			newVal := new(JSONSchemaProps)
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&val, newVal, s); err != nil {
+				return err
+			}
+			(*out)[key] = *newVal
+		}
+	} else {
+		out.Definitions = nil
+	}
+	out.ExternalDocs = (*ExternalDocumentation)(unsafe.Pointer(in.ExternalDocs))
+	if in.Example != nil {
+		in, out := &in.Example, &out.Example
+		*out = new(JSON)
+		if err := Convert_apiextensions_JSON_To_v1beta1_JSON(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Example = nil
+	}
+	out.XPreserveUnknownFields = (*bool)(unsafe.Pointer(in.XPreserveUnknownFields))
+	out.XEmbeddedResource = in.XEmbeddedResource
+	out.XIntOrString = in.XIntOrString
+	out.XListMapKeys = *(*[]string)(unsafe.Pointer(&in.XListMapKeys))
+	out.XListType = (*string)(unsafe.Pointer(in.XListType))
+	out.XMapType = (*string)(unsafe.Pointer(in.XMapType))
+	out.XValidations = *(*ValidationRules)(unsafe.Pointer(&in.XValidations))
+	return nil
+}
+
+func autoConvert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray(in *JSONSchemaPropsOrArray, out *apiextensions.JSONSchemaPropsOrArray, s conversion.Scope) error {
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(apiextensions.JSONSchemaProps)
+		if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	if in.JSONSchemas != nil {
+		in, out := &in.JSONSchemas, &out.JSONSchemas
+		*out = make([]apiextensions.JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.JSONSchemas = nil
+	}
+	return nil
+}
+
+// Convert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray is an autogenerated conversion function.
+func Convert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray(in *JSONSchemaPropsOrArray, out *apiextensions.JSONSchemaPropsOrArray, s conversion.Scope) error {
+	return autoConvert_v1beta1_JSONSchemaPropsOrArray_To_apiextensions_JSONSchemaPropsOrArray(in, out, s)
+}
+
+func autoConvert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray(in *apiextensions.JSONSchemaPropsOrArray, out *JSONSchemaPropsOrArray, s conversion.Scope) error {
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(JSONSchemaProps)
+		if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	if in.JSONSchemas != nil {
+		in, out := &in.JSONSchemas, &out.JSONSchemas
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil {
+				return err
+			}
+		}
+	} else {
+		out.JSONSchemas = nil
+	}
+	return nil
+}
+
+// Convert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray is an autogenerated conversion function.
+func Convert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray(in *apiextensions.JSONSchemaPropsOrArray, out *JSONSchemaPropsOrArray, s conversion.Scope) error {
+	return autoConvert_apiextensions_JSONSchemaPropsOrArray_To_v1beta1_JSONSchemaPropsOrArray(in, out, s)
+}
+
+func autoConvert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(in *JSONSchemaPropsOrBool, out *apiextensions.JSONSchemaPropsOrBool, s conversion.Scope) error {
+	out.Allows = in.Allows
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(apiextensions.JSONSchemaProps)
+		if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	return nil
+}
+
+// Convert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool is an autogenerated conversion function.
+func Convert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(in *JSONSchemaPropsOrBool, out *apiextensions.JSONSchemaPropsOrBool, s conversion.Scope) error {
+	return autoConvert_v1beta1_JSONSchemaPropsOrBool_To_apiextensions_JSONSchemaPropsOrBool(in, out, s)
+}
+
+func autoConvert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(in *apiextensions.JSONSchemaPropsOrBool, out *JSONSchemaPropsOrBool, s conversion.Scope) error {
+	out.Allows = in.Allows
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(JSONSchemaProps)
+		if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	return nil
+}
+
+// Convert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool is an autogenerated conversion function.
+func Convert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(in *apiextensions.JSONSchemaPropsOrBool, out *JSONSchemaPropsOrBool, s conversion.Scope) error {
+	return autoConvert_apiextensions_JSONSchemaPropsOrBool_To_v1beta1_JSONSchemaPropsOrBool(in, out, s)
+}
+
+func autoConvert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray(in *JSONSchemaPropsOrStringArray, out *apiextensions.JSONSchemaPropsOrStringArray, s conversion.Scope) error {
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(apiextensions.JSONSchemaProps)
+		if err := Convert_v1beta1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	out.Property = *(*[]string)(unsafe.Pointer(&in.Property))
+	return nil
+}
+
+// Convert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray is an autogenerated conversion function.
+func Convert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray(in *JSONSchemaPropsOrStringArray, out *apiextensions.JSONSchemaPropsOrStringArray, s conversion.Scope) error {
+	return autoConvert_v1beta1_JSONSchemaPropsOrStringArray_To_apiextensions_JSONSchemaPropsOrStringArray(in, out, s)
+}
+
+func autoConvert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray(in *apiextensions.JSONSchemaPropsOrStringArray, out *JSONSchemaPropsOrStringArray, s conversion.Scope) error {
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(JSONSchemaProps)
+		if err := Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Schema = nil
+	}
+	out.Property = *(*[]string)(unsafe.Pointer(&in.Property))
+	return nil
+}
+
+// Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray is an autogenerated conversion function.
+func Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray(in *apiextensions.JSONSchemaPropsOrStringArray, out *JSONSchemaPropsOrStringArray, s conversion.Scope) error {
+	return autoConvert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPropsOrStringArray(in, out, s)
+}
+
+func autoConvert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error {
+	out.JSONPath = in.JSONPath
+	return nil
+}
+
+// Convert_v1beta1_SelectableField_To_apiextensions_SelectableField is an autogenerated conversion function.
+func Convert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error {
+	return autoConvert_v1beta1_SelectableField_To_apiextensions_SelectableField(in, out, s)
+}
+
+func autoConvert_apiextensions_SelectableField_To_v1beta1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error {
+	out.JSONPath = in.JSONPath
+	return nil
+}
+
+// Convert_apiextensions_SelectableField_To_v1beta1_SelectableField is an autogenerated conversion function.
+func Convert_apiextensions_SelectableField_To_v1beta1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error {
+	return autoConvert_apiextensions_SelectableField_To_v1beta1_SelectableField(in, out, s)
+}
+
+func autoConvert_v1beta1_ServiceReference_To_apiextensions_ServiceReference(in *ServiceReference, out *apiextensions.ServiceReference, s conversion.Scope) error {
+	out.Namespace = in.Namespace
+	out.Name = in.Name
+	out.Path = (*string)(unsafe.Pointer(in.Path))
+	if err := v1.Convert_Pointer_int32_To_int32(&in.Port, &out.Port, s); err != nil {
+		return err
+	}
+	return nil
+}
+
+// Convert_v1beta1_ServiceReference_To_apiextensions_ServiceReference is an autogenerated conversion function.
+func Convert_v1beta1_ServiceReference_To_apiextensions_ServiceReference(in *ServiceReference, out *apiextensions.ServiceReference, s conversion.Scope) error {
+	return autoConvert_v1beta1_ServiceReference_To_apiextensions_ServiceReference(in, out, s)
+}
+
+func autoConvert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(in *apiextensions.ServiceReference, out *ServiceReference, s conversion.Scope) error {
+	out.Namespace = in.Namespace
+	out.Name = in.Name
+	out.Path = (*string)(unsafe.Pointer(in.Path))
+	if err := v1.Convert_int32_To_Pointer_int32(&in.Port, &out.Port, s); err != nil {
+		return err
+	}
+	return nil
+}
+
+// Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference is an autogenerated conversion function.
+func Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(in *apiextensions.ServiceReference, out *ServiceReference, s conversion.Scope) error {
+	return autoConvert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(in, out, s)
+}
+
+func autoConvert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error {
+	out.Rule = in.Rule
+	out.Message = in.Message
+	out.MessageExpression = in.MessageExpression
+	out.Reason = (*apiextensions.FieldValueErrorReason)(unsafe.Pointer(in.Reason))
+	out.FieldPath = in.FieldPath
+	out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf))
+	return nil
+}
+
+// Convert_v1beta1_ValidationRule_To_apiextensions_ValidationRule is an autogenerated conversion function.
+func Convert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error {
+	return autoConvert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in, out, s)
+}
+
+func autoConvert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error {
+	out.Rule = in.Rule
+	out.Message = in.Message
+	out.MessageExpression = in.MessageExpression
+	out.Reason = (*FieldValueErrorReason)(unsafe.Pointer(in.Reason))
+	out.FieldPath = in.FieldPath
+	out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf))
+	return nil
+}
+
+// Convert_apiextensions_ValidationRule_To_v1beta1_ValidationRule is an autogenerated conversion function.
+func Convert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error {
+	return autoConvert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(in, out, s)
+}
+
+func autoConvert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(in *WebhookClientConfig, out *apiextensions.WebhookClientConfig, s conversion.Scope) error {
+	out.URL = (*string)(unsafe.Pointer(in.URL))
+	if in.Service != nil {
+		in, out := &in.Service, &out.Service
+		*out = new(apiextensions.ServiceReference)
+		if err := Convert_v1beta1_ServiceReference_To_apiextensions_ServiceReference(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Service = nil
+	}
+	out.CABundle = *(*[]byte)(unsafe.Pointer(&in.CABundle))
+	return nil
+}
+
+// Convert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig is an autogenerated conversion function.
+func Convert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(in *WebhookClientConfig, out *apiextensions.WebhookClientConfig, s conversion.Scope) error {
+	return autoConvert_v1beta1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(in, out, s)
+}
+
+func autoConvert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig(in *apiextensions.WebhookClientConfig, out *WebhookClientConfig, s conversion.Scope) error {
+	out.URL = (*string)(unsafe.Pointer(in.URL))
+	if in.Service != nil {
+		in, out := &in.Service, &out.Service
+		*out = new(ServiceReference)
+		if err := Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(*in, *out, s); err != nil {
+			return err
+		}
+	} else {
+		out.Service = nil
+	}
+	out.CABundle = *(*[]byte)(unsafe.Pointer(&in.CABundle))
+	return nil
+}
+
+// Convert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig is an autogenerated conversion function.
+func Convert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig(in *apiextensions.WebhookClientConfig, out *WebhookClientConfig, s conversion.Scope) error {
+	return autoConvert_apiextensions_WebhookClientConfig_To_v1beta1_WebhookClientConfig(in, out, s)
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.deepcopy.go
new file mode 100644
index 000000000..18740925c
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.deepcopy.go
@@ -0,0 +1,742 @@
+//go:build !ignore_autogenerated
+// +build !ignore_autogenerated
+
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by deepcopy-gen. DO NOT EDIT.
+
+package v1beta1
+
+import (
+	runtime "k8s.io/apimachinery/pkg/runtime"
+)
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ConversionRequest) DeepCopyInto(out *ConversionRequest) {
+	*out = *in
+	if in.Objects != nil {
+		in, out := &in.Objects, &out.Objects
+		*out = make([]runtime.RawExtension, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionRequest.
+func (in *ConversionRequest) DeepCopy() *ConversionRequest {
+	if in == nil {
+		return nil
+	}
+	out := new(ConversionRequest)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ConversionResponse) DeepCopyInto(out *ConversionResponse) {
+	*out = *in
+	if in.ConvertedObjects != nil {
+		in, out := &in.ConvertedObjects, &out.ConvertedObjects
+		*out = make([]runtime.RawExtension, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	in.Result.DeepCopyInto(&out.Result)
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionResponse.
+func (in *ConversionResponse) DeepCopy() *ConversionResponse {
+	if in == nil {
+		return nil
+	}
+	out := new(ConversionResponse)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ConversionReview) DeepCopyInto(out *ConversionReview) {
+	*out = *in
+	out.TypeMeta = in.TypeMeta
+	if in.Request != nil {
+		in, out := &in.Request, &out.Request
+		*out = new(ConversionRequest)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.Response != nil {
+		in, out := &in.Response, &out.Response
+		*out = new(ConversionResponse)
+		(*in).DeepCopyInto(*out)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionReview.
+func (in *ConversionReview) DeepCopy() *ConversionReview {
+	if in == nil {
+		return nil
+	}
+	out := new(ConversionReview)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
+func (in *ConversionReview) DeepCopyObject() runtime.Object {
+	if c := in.DeepCopy(); c != nil {
+		return c
+	}
+	return nil
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceColumnDefinition) DeepCopyInto(out *CustomResourceColumnDefinition) {
+	*out = *in
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceColumnDefinition.
+func (in *CustomResourceColumnDefinition) DeepCopy() *CustomResourceColumnDefinition {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceColumnDefinition)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceConversion) DeepCopyInto(out *CustomResourceConversion) {
+	*out = *in
+	if in.WebhookClientConfig != nil {
+		in, out := &in.WebhookClientConfig, &out.WebhookClientConfig
+		*out = new(WebhookClientConfig)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.ConversionReviewVersions != nil {
+		in, out := &in.ConversionReviewVersions, &out.ConversionReviewVersions
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceConversion.
+func (in *CustomResourceConversion) DeepCopy() *CustomResourceConversion {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceConversion)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinition) DeepCopyInto(out *CustomResourceDefinition) {
+	*out = *in
+	out.TypeMeta = in.TypeMeta
+	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
+	in.Spec.DeepCopyInto(&out.Spec)
+	in.Status.DeepCopyInto(&out.Status)
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinition.
+func (in *CustomResourceDefinition) DeepCopy() *CustomResourceDefinition {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinition)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
+func (in *CustomResourceDefinition) DeepCopyObject() runtime.Object {
+	if c := in.DeepCopy(); c != nil {
+		return c
+	}
+	return nil
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionCondition) DeepCopyInto(out *CustomResourceDefinitionCondition) {
+	*out = *in
+	in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime)
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionCondition.
+func (in *CustomResourceDefinitionCondition) DeepCopy() *CustomResourceDefinitionCondition {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionCondition)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionList) DeepCopyInto(out *CustomResourceDefinitionList) {
+	*out = *in
+	out.TypeMeta = in.TypeMeta
+	in.ListMeta.DeepCopyInto(&out.ListMeta)
+	if in.Items != nil {
+		in, out := &in.Items, &out.Items
+		*out = make([]CustomResourceDefinition, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionList.
+func (in *CustomResourceDefinitionList) DeepCopy() *CustomResourceDefinitionList {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionList)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
+func (in *CustomResourceDefinitionList) DeepCopyObject() runtime.Object {
+	if c := in.DeepCopy(); c != nil {
+		return c
+	}
+	return nil
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionNames) DeepCopyInto(out *CustomResourceDefinitionNames) {
+	*out = *in
+	if in.ShortNames != nil {
+		in, out := &in.ShortNames, &out.ShortNames
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+	if in.Categories != nil {
+		in, out := &in.Categories, &out.Categories
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionNames.
+func (in *CustomResourceDefinitionNames) DeepCopy() *CustomResourceDefinitionNames {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionNames)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionSpec) DeepCopyInto(out *CustomResourceDefinitionSpec) {
+	*out = *in
+	in.Names.DeepCopyInto(&out.Names)
+	if in.Validation != nil {
+		in, out := &in.Validation, &out.Validation
+		*out = new(CustomResourceValidation)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.Subresources != nil {
+		in, out := &in.Subresources, &out.Subresources
+		*out = new(CustomResourceSubresources)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.Versions != nil {
+		in, out := &in.Versions, &out.Versions
+		*out = make([]CustomResourceDefinitionVersion, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	if in.AdditionalPrinterColumns != nil {
+		in, out := &in.AdditionalPrinterColumns, &out.AdditionalPrinterColumns
+		*out = make([]CustomResourceColumnDefinition, len(*in))
+		copy(*out, *in)
+	}
+	if in.SelectableFields != nil {
+		in, out := &in.SelectableFields, &out.SelectableFields
+		*out = make([]SelectableField, len(*in))
+		copy(*out, *in)
+	}
+	if in.Conversion != nil {
+		in, out := &in.Conversion, &out.Conversion
+		*out = new(CustomResourceConversion)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.PreserveUnknownFields != nil {
+		in, out := &in.PreserveUnknownFields, &out.PreserveUnknownFields
+		*out = new(bool)
+		**out = **in
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionSpec.
+func (in *CustomResourceDefinitionSpec) DeepCopy() *CustomResourceDefinitionSpec {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionSpec)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionStatus) DeepCopyInto(out *CustomResourceDefinitionStatus) {
+	*out = *in
+	if in.Conditions != nil {
+		in, out := &in.Conditions, &out.Conditions
+		*out = make([]CustomResourceDefinitionCondition, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	in.AcceptedNames.DeepCopyInto(&out.AcceptedNames)
+	if in.StoredVersions != nil {
+		in, out := &in.StoredVersions, &out.StoredVersions
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionStatus.
+func (in *CustomResourceDefinitionStatus) DeepCopy() *CustomResourceDefinitionStatus {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionStatus)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceDefinitionVersion) DeepCopyInto(out *CustomResourceDefinitionVersion) {
+	*out = *in
+	if in.DeprecationWarning != nil {
+		in, out := &in.DeprecationWarning, &out.DeprecationWarning
+		*out = new(string)
+		**out = **in
+	}
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = new(CustomResourceValidation)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.Subresources != nil {
+		in, out := &in.Subresources, &out.Subresources
+		*out = new(CustomResourceSubresources)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.AdditionalPrinterColumns != nil {
+		in, out := &in.AdditionalPrinterColumns, &out.AdditionalPrinterColumns
+		*out = make([]CustomResourceColumnDefinition, len(*in))
+		copy(*out, *in)
+	}
+	if in.SelectableFields != nil {
+		in, out := &in.SelectableFields, &out.SelectableFields
+		*out = make([]SelectableField, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionVersion.
+func (in *CustomResourceDefinitionVersion) DeepCopy() *CustomResourceDefinitionVersion {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceDefinitionVersion)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceSubresourceScale) DeepCopyInto(out *CustomResourceSubresourceScale) {
+	*out = *in
+	if in.LabelSelectorPath != nil {
+		in, out := &in.LabelSelectorPath, &out.LabelSelectorPath
+		*out = new(string)
+		**out = **in
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresourceScale.
+func (in *CustomResourceSubresourceScale) DeepCopy() *CustomResourceSubresourceScale {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceSubresourceScale)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceSubresourceStatus) DeepCopyInto(out *CustomResourceSubresourceStatus) {
+	*out = *in
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresourceStatus.
+func (in *CustomResourceSubresourceStatus) DeepCopy() *CustomResourceSubresourceStatus {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceSubresourceStatus)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceSubresources) DeepCopyInto(out *CustomResourceSubresources) {
+	*out = *in
+	if in.Status != nil {
+		in, out := &in.Status, &out.Status
+		*out = new(CustomResourceSubresourceStatus)
+		**out = **in
+	}
+	if in.Scale != nil {
+		in, out := &in.Scale, &out.Scale
+		*out = new(CustomResourceSubresourceScale)
+		(*in).DeepCopyInto(*out)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresources.
+func (in *CustomResourceSubresources) DeepCopy() *CustomResourceSubresources {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceSubresources)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CustomResourceValidation) DeepCopyInto(out *CustomResourceValidation) {
+	*out = *in
+	if in.OpenAPIV3Schema != nil {
+		in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema
+		*out = (*in).DeepCopy()
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceValidation.
+func (in *CustomResourceValidation) DeepCopy() *CustomResourceValidation {
+	if in == nil {
+		return nil
+	}
+	out := new(CustomResourceValidation)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ExternalDocumentation) DeepCopyInto(out *ExternalDocumentation) {
+	*out = *in
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalDocumentation.
+func (in *ExternalDocumentation) DeepCopy() *ExternalDocumentation {
+	if in == nil {
+		return nil
+	}
+	out := new(ExternalDocumentation)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *JSON) DeepCopyInto(out *JSON) {
+	*out = *in
+	if in.Raw != nil {
+		in, out := &in.Raw, &out.Raw
+		*out = make([]byte, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSON.
+func (in *JSON) DeepCopy() *JSON {
+	if in == nil {
+		return nil
+	}
+	out := new(JSON)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in JSONSchemaDefinitions) DeepCopyInto(out *JSONSchemaDefinitions) {
+	{
+		in := &in
+		*out = make(JSONSchemaDefinitions, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+		return
+	}
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaDefinitions.
+func (in JSONSchemaDefinitions) DeepCopy() JSONSchemaDefinitions {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaDefinitions)
+	in.DeepCopyInto(out)
+	return *out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in JSONSchemaDependencies) DeepCopyInto(out *JSONSchemaDependencies) {
+	{
+		in := &in
+		*out = make(JSONSchemaDependencies, len(*in))
+		for key, val := range *in {
+			(*out)[key] = *val.DeepCopy()
+		}
+		return
+	}
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaDependencies.
+func (in JSONSchemaDependencies) DeepCopy() JSONSchemaDependencies {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaDependencies)
+	in.DeepCopyInto(out)
+	return *out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *JSONSchemaProps) DeepCopyInto(out *JSONSchemaProps) {
+	clone := in.DeepCopy()
+	*out = *clone
+	return
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *JSONSchemaPropsOrArray) DeepCopyInto(out *JSONSchemaPropsOrArray) {
+	*out = *in
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = (*in).DeepCopy()
+	}
+	if in.JSONSchemas != nil {
+		in, out := &in.JSONSchemas, &out.JSONSchemas
+		*out = make([]JSONSchemaProps, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrArray.
+func (in *JSONSchemaPropsOrArray) DeepCopy() *JSONSchemaPropsOrArray {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaPropsOrArray)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *JSONSchemaPropsOrBool) DeepCopyInto(out *JSONSchemaPropsOrBool) {
+	*out = *in
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = (*in).DeepCopy()
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrBool.
+func (in *JSONSchemaPropsOrBool) DeepCopy() *JSONSchemaPropsOrBool {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaPropsOrBool)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *JSONSchemaPropsOrStringArray) DeepCopyInto(out *JSONSchemaPropsOrStringArray) {
+	*out = *in
+	if in.Schema != nil {
+		in, out := &in.Schema, &out.Schema
+		*out = (*in).DeepCopy()
+	}
+	if in.Property != nil {
+		in, out := &in.Property, &out.Property
+		*out = make([]string, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrStringArray.
+func (in *JSONSchemaPropsOrStringArray) DeepCopy() *JSONSchemaPropsOrStringArray {
+	if in == nil {
+		return nil
+	}
+	out := new(JSONSchemaPropsOrStringArray)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *SelectableField) DeepCopyInto(out *SelectableField) {
+	*out = *in
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SelectableField.
+func (in *SelectableField) DeepCopy() *SelectableField {
+	if in == nil {
+		return nil
+	}
+	out := new(SelectableField)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ServiceReference) DeepCopyInto(out *ServiceReference) {
+	*out = *in
+	if in.Path != nil {
+		in, out := &in.Path, &out.Path
+		*out = new(string)
+		**out = **in
+	}
+	if in.Port != nil {
+		in, out := &in.Port, &out.Port
+		*out = new(int32)
+		**out = **in
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceReference.
+func (in *ServiceReference) DeepCopy() *ServiceReference {
+	if in == nil {
+		return nil
+	}
+	out := new(ServiceReference)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *ValidationRule) DeepCopyInto(out *ValidationRule) {
+	*out = *in
+	if in.Reason != nil {
+		in, out := &in.Reason, &out.Reason
+		*out = new(FieldValueErrorReason)
+		**out = **in
+	}
+	if in.OptionalOldSelf != nil {
+		in, out := &in.OptionalOldSelf, &out.OptionalOldSelf
+		*out = new(bool)
+		**out = **in
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidationRule.
+func (in *ValidationRule) DeepCopy() *ValidationRule {
+	if in == nil {
+		return nil
+	}
+	out := new(ValidationRule)
+	in.DeepCopyInto(out)
+	return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in ValidationRules) DeepCopyInto(out *ValidationRules) {
+	{
+		in := &in
+		*out = make(ValidationRules, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+		return
+	}
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidationRules.
+func (in ValidationRules) DeepCopy() ValidationRules {
+	if in == nil {
+		return nil
+	}
+	out := new(ValidationRules)
+	in.DeepCopyInto(out)
+	return *out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *WebhookClientConfig) DeepCopyInto(out *WebhookClientConfig) {
+	*out = *in
+	if in.URL != nil {
+		in, out := &in.URL, &out.URL
+		*out = new(string)
+		**out = **in
+	}
+	if in.Service != nil {
+		in, out := &in.Service, &out.Service
+		*out = new(ServiceReference)
+		(*in).DeepCopyInto(*out)
+	}
+	if in.CABundle != nil {
+		in, out := &in.CABundle, &out.CABundle
+		*out = make([]byte, len(*in))
+		copy(*out, *in)
+	}
+	return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookClientConfig.
+func (in *WebhookClientConfig) DeepCopy() *WebhookClientConfig {
+	if in == nil {
+		return nil
+	}
+	out := new(WebhookClientConfig)
+	in.DeepCopyInto(out)
+	return out
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.defaults.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.defaults.go
new file mode 100644
index 000000000..225c6ff51
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.defaults.go
@@ -0,0 +1,56 @@
+//go:build !ignore_autogenerated
+// +build !ignore_autogenerated
+
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by defaulter-gen. DO NOT EDIT.
+
+package v1beta1
+
+import (
+	runtime "k8s.io/apimachinery/pkg/runtime"
+)
+
+// RegisterDefaults adds defaulters functions to the given scheme.
+// Public to allow building arbitrary schemes.
+// All generated defaulters are covering - they call all nested defaulters.
+func RegisterDefaults(scheme *runtime.Scheme) error {
+	scheme.AddTypeDefaultingFunc(&CustomResourceDefinition{}, func(obj interface{}) { SetObjectDefaults_CustomResourceDefinition(obj.(*CustomResourceDefinition)) })
+	scheme.AddTypeDefaultingFunc(&CustomResourceDefinitionList{}, func(obj interface{}) {
+		SetObjectDefaults_CustomResourceDefinitionList(obj.(*CustomResourceDefinitionList))
+	})
+	return nil
+}
+
+func SetObjectDefaults_CustomResourceDefinition(in *CustomResourceDefinition) {
+	SetDefaults_CustomResourceDefinition(in)
+	SetDefaults_CustomResourceDefinitionSpec(&in.Spec)
+	if in.Spec.Conversion != nil {
+		if in.Spec.Conversion.WebhookClientConfig != nil {
+			if in.Spec.Conversion.WebhookClientConfig.Service != nil {
+				SetDefaults_ServiceReference(in.Spec.Conversion.WebhookClientConfig.Service)
+			}
+		}
+	}
+}
+
+func SetObjectDefaults_CustomResourceDefinitionList(in *CustomResourceDefinitionList) {
+	for i := range in.Items {
+		a := &in.Items[i]
+		SetObjectDefaults_CustomResourceDefinition(a)
+	}
+}
diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.prerelease-lifecycle.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.prerelease-lifecycle.go
new file mode 100644
index 000000000..9c22ae5c1
--- /dev/null
+++ b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.prerelease-lifecycle.go
@@ -0,0 +1,98 @@
+//go:build !ignore_autogenerated
+// +build !ignore_autogenerated
+
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by prerelease-lifecycle-gen. DO NOT EDIT.
+
+package v1beta1
+
+import (
+	schema "k8s.io/apimachinery/pkg/runtime/schema"
+)
+
+// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go.
+func (in *ConversionReview) APILifecycleIntroduced() (major, minor int) {
+	return 1, 13
+}
+
+// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or  "k8s:prerelease-lifecycle-gen:introduced" plus three minor.
+func (in *ConversionReview) APILifecycleDeprecated() (major, minor int) {
+	return 1, 19
+}
+
+// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type.
+// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go.
+func (in *ConversionReview) APILifecycleReplacement() schema.GroupVersionKind {
+	return schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "ConversionReview"}
+}
+
+// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or  "k8s:prerelease-lifecycle-gen:deprecated" plus three minor.
+func (in *ConversionReview) APILifecycleRemoved() (major, minor int) {
+	return 1, 22
+}
+
+// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go.
+func (in *CustomResourceDefinition) APILifecycleIntroduced() (major, minor int) {
+	return 1, 7
+}
+
+// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or  "k8s:prerelease-lifecycle-gen:introduced" plus three minor.
+func (in *CustomResourceDefinition) APILifecycleDeprecated() (major, minor int) {
+	return 1, 16
+}
+
+// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type.
+// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go.
+func (in *CustomResourceDefinition) APILifecycleReplacement() schema.GroupVersionKind {
+	return schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition"}
+}
+
+// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or  "k8s:prerelease-lifecycle-gen:deprecated" plus three minor.
+func (in *CustomResourceDefinition) APILifecycleRemoved() (major, minor int) {
+	return 1, 22
+}
+
+// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go.
+func (in *CustomResourceDefinitionList) APILifecycleIntroduced() (major, minor int) {
+	return 1, 7
+}
+
+// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or  "k8s:prerelease-lifecycle-gen:introduced" plus three minor.
+func (in *CustomResourceDefinitionList) APILifecycleDeprecated() (major, minor int) {
+	return 1, 16
+}
+
+// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type.
+// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go.
+func (in *CustomResourceDefinitionList) APILifecycleReplacement() schema.GroupVersionKind {
+	return schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinitionList"}
+}
+
+// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison.
+// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or  "k8s:prerelease-lifecycle-gen:deprecated" plus three minor.
+func (in *CustomResourceDefinitionList) APILifecycleRemoved() (major, minor int) {
+	return 1, 22
+}
diff --git a/vendor/k8s.io/code-generator/LICENSE b/vendor/k8s.io/code-generator/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/vendor/k8s.io/code-generator/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go
new file mode 100644
index 000000000..36aa7a371
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go
@@ -0,0 +1,88 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package args
+
+import (
+	"fmt"
+
+	"github.com/spf13/pflag"
+	"k8s.io/gengo/v2/types"
+)
+
+// Args is a wrapper for arguments to applyconfiguration-gen.
+type Args struct {
+	OutputDir string // must be a directory path
+	OutputPkg string // must be a Go import-path
+
+	GoHeaderFile string
+
+	// ExternalApplyConfigurations provides the locations of externally generated
+	// apply configuration types for types referenced by the go structs provided as input.
+	// Locations are provided as a comma separated list of .:
+	// entries.
+	//
+	// E.g. if a type references appsv1.Deployment, the location of its apply configuration should
+	// be provided:
+	//   k8s.io/api/apps/v1.Deployment:k8s.io/client-go/applyconfigurations/apps/v1
+	//
+	// meta/v1 types (TypeMeta and ObjectMeta) are always included and do not need to be passed in.
+	ExternalApplyConfigurations map[types.Name]string
+
+	OpenAPISchemaFilePath string
+}
+
+// New returns default arguments for the generator.
+func New() *Args {
+	return &Args{
+		ExternalApplyConfigurations: map[types.Name]string{
+			// Always include the applyconfigurations we've generated in client-go. They are sufficient for the vast majority of use cases.
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "Condition"}:                "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "DeleteOptions"}:            "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "LabelSelector"}:            "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "LabelSelectorRequirement"}: "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ManagedFieldsEntry"}:       "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ObjectMeta"}:               "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "OwnerReference"}:           "k8s.io/client-go/applyconfigurations/meta/v1",
+			{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "TypeMeta"}:                 "k8s.io/client-go/applyconfigurations/meta/v1",
+		},
+	}
+}
+
+func (args *Args) AddFlags(fs *pflag.FlagSet, inputBase string) {
+	fs.StringVar(&args.OutputDir, "output-dir", "",
+		"the base directory under which to generate results")
+	fs.StringVar(&args.OutputPkg, "output-pkg", args.OutputPkg,
+		"the Go import-path of the generated results")
+	fs.StringVar(&args.GoHeaderFile, "go-header-file", "",
+		"the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year")
+	fs.Var(NewExternalApplyConfigurationValue(&args.ExternalApplyConfigurations, nil), "external-applyconfigurations",
+		"list of comma separated external apply configurations locations in .: form."+
+			"For example: k8s.io/api/apps/v1.Deployment:k8s.io/client-go/applyconfigurations/apps/v1")
+	fs.StringVar(&args.OpenAPISchemaFilePath, "openapi-schema", "",
+		"path to the openapi schema containing all the types that apply configurations will be generated for")
+}
+
+// Validate checks the given arguments.
+func (args *Args) Validate() error {
+	if len(args.OutputDir) == 0 {
+		return fmt.Errorf("--output-dir must be specified")
+	}
+	if len(args.OutputPkg) == 0 {
+		return fmt.Errorf("--output-pkg must be specified")
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go
new file mode 100644
index 000000000..fd9b60989
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go
@@ -0,0 +1,122 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package args
+
+import (
+	"bytes"
+	"encoding/csv"
+	"flag"
+	"fmt"
+	"strings"
+
+	"k8s.io/gengo/v2/types"
+)
+
+type externalApplyConfigurationValue struct {
+	externals *map[types.Name]string
+}
+
+func NewExternalApplyConfigurationValue(externals *map[types.Name]string, def []string) *externalApplyConfigurationValue {
+	val := new(externalApplyConfigurationValue)
+	val.externals = externals
+	if def != nil {
+		if err := val.set(def); err != nil {
+			panic(err)
+		}
+	}
+	return val
+}
+
+var _ flag.Value = &externalApplyConfigurationValue{}
+
+func (s *externalApplyConfigurationValue) set(vs []string) error {
+	for _, input := range vs {
+		typ, pkg, err := parseExternalMapping(input)
+		if err != nil {
+			return err
+		}
+		if _, ok := (*s.externals)[typ]; ok {
+			return fmt.Errorf("duplicate type found in --external-applyconfigurations: %v", typ)
+		}
+		(*s.externals)[typ] = pkg
+	}
+
+	return nil
+}
+
+func (s *externalApplyConfigurationValue) Set(val string) error {
+	vs, err := readAsCSV(val)
+	if err != nil {
+		return err
+	}
+	if err := s.set(vs); err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func (s *externalApplyConfigurationValue) Type() string {
+	return "string"
+}
+
+func (s *externalApplyConfigurationValue) String() string {
+	var strs []string
+	for k, v := range *s.externals {
+		strs = append(strs, fmt.Sprintf("%s.%s:%s", k.Package, k.Name, v))
+	}
+	str, _ := writeAsCSV(strs)
+	return "[" + str + "]"
+}
+
+func readAsCSV(val string) ([]string, error) {
+	if val == "" {
+		return []string{}, nil
+	}
+	stringReader := strings.NewReader(val)
+	csvReader := csv.NewReader(stringReader)
+	return csvReader.Read()
+}
+
+func writeAsCSV(vals []string) (string, error) {
+	b := &bytes.Buffer{}
+	w := csv.NewWriter(b)
+	err := w.Write(vals)
+	if err != nil {
+		return "", err
+	}
+	w.Flush()
+	return strings.TrimSuffix(b.String(), "\n"), nil
+}
+
+func parseExternalMapping(mapping string) (typ types.Name, pkg string, err error) {
+	parts := strings.Split(mapping, ":")
+	if len(parts) != 2 {
+		return types.Name{}, "", fmt.Errorf("expected string of the form .: but got %s", mapping)
+	}
+	packageTypeStr := parts[0]
+	pkg = parts[1]
+	// need to split on the *last* dot, since k8s.io (and other valid packages) have a dot in it
+	lastDot := strings.LastIndex(packageTypeStr, ".")
+	if lastDot == -1 || lastDot == len(packageTypeStr)-1 {
+		return types.Name{}, "", fmt.Errorf("expected package and type of the form . but got %s", packageTypeStr)
+	}
+	structPkg := packageTypeStr[:lastDot]
+	structType := packageTypeStr[lastDot+1:]
+
+	return types.Name{Package: structPkg, Name: structType}, pkg, nil
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go
new file mode 100644
index 000000000..9b6aa7cec
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go
@@ -0,0 +1,479 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"io"
+	"path"
+	"slices"
+	"strings"
+
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+
+	"k8s.io/code-generator/cmd/client-gen/generators/util"
+	clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
+)
+
+// applyConfigurationGenerator produces apply configurations for a given GroupVersion and type.
+type applyConfigurationGenerator struct {
+	generator.GoGenerator
+	// outPkgBase is the base package, under which the "internal" and GV-specific subdirs live
+	outPkgBase   string // must be a Go import-path
+	localPkg     string
+	groupVersion clientgentypes.GroupVersion
+	applyConfig  applyConfig
+	imports      namer.ImportTracker
+	refGraph     refGraph
+	openAPIType  *string // if absent, extraction function cannot be generated
+}
+
+var _ generator.Generator = &applyConfigurationGenerator{}
+
+func (g *applyConfigurationGenerator) Filter(_ *generator.Context, t *types.Type) bool {
+	return t == g.applyConfig.Type
+}
+
+func (g *applyConfigurationGenerator) Namers(*generator.Context) namer.NameSystems {
+	return namer.NameSystems{
+		"raw":          namer.NewRawNamer(g.localPkg, g.imports),
+		"singularKind": namer.NewPublicNamer(0),
+	}
+}
+
+func (g *applyConfigurationGenerator) Imports(*generator.Context) (imports []string) {
+	return g.imports.ImportLines()
+}
+
+// TypeParams provides a struct that an apply configuration
+// is generated for as well as the apply configuration details
+// and types referenced by the struct.
+type TypeParams struct {
+	Struct      *types.Type
+	ApplyConfig applyConfig
+	Tags        util.Tags
+	APIVersion  string
+	ExtractInto *types.Type
+	ParserFunc  *types.Type
+	OpenAPIType *string
+}
+
+type memberParams struct {
+	TypeParams
+	Member     types.Member
+	MemberType *types.Type
+	JSONTags   JSONTags
+	ArgType    *types.Type   // only set for maps and slices
+	EmbeddedIn *memberParams // parent embedded member, if any
+}
+
+func (g *applyConfigurationGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
+	sw := generator.NewSnippetWriter(w, c, "$", "$")
+
+	klog.V(5).Infof("processing type %v", t)
+	typeParams := TypeParams{
+		Struct:      t,
+		ApplyConfig: g.applyConfig,
+		Tags:        genclientTags(t),
+		APIVersion:  g.groupVersion.ToAPIVersion(),
+		ExtractInto: extractInto,
+		ParserFunc:  types.Ref(path.Join(g.outPkgBase, "internal"), "Parser"),
+		OpenAPIType: g.openAPIType,
+	}
+
+	g.generateStruct(sw, typeParams)
+
+	if typeParams.Tags.GenerateClient {
+		if typeParams.Tags.NonNamespaced {
+			sw.Do(clientgenTypeConstructorNonNamespaced, typeParams)
+		} else {
+			sw.Do(clientgenTypeConstructorNamespaced, typeParams)
+		}
+		if typeParams.OpenAPIType != nil {
+			g.generateClientgenExtract(sw, typeParams, !typeParams.Tags.NoStatus)
+		}
+	} else {
+		if hasTypeMetaField(t) {
+			sw.Do(constructorWithTypeMeta, typeParams)
+		} else {
+			sw.Do(constructor, typeParams)
+		}
+	}
+	g.generateWithFuncs(t, typeParams, sw, nil, &[]string{})
+	g.generateGetters(t, typeParams, sw, nil)
+	return sw.Error()
+}
+
+func hasTypeMetaField(t *types.Type) bool {
+	for _, member := range t.Members {
+		if typeMeta.Name == member.Type.Name && member.Embedded {
+			return true
+		}
+	}
+	return false
+}
+
+func blocklisted(t *types.Type, member types.Member) bool {
+	if objectMeta.Name == t.Name && member.Name == "ManagedFields" {
+		return true
+	}
+	if objectMeta.Name == t.Name && member.Name == "SelfLink" {
+		return true
+	}
+	// Hide any fields which are en route to deletion.
+	if strings.HasPrefix(member.Name, "ZZZ_") {
+		return true
+	}
+	return false
+}
+
+func needsGetter(t *types.Type, member types.Member) bool {
+	// Needed when applying an ApplyConfiguration
+	return objectMeta.Name == t.Name && member.Name == "Name"
+}
+
+func (g *applyConfigurationGenerator) generateGetters(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams) {
+	for _, member := range t.Members {
+		if blocklisted(t, member) {
+			continue
+		}
+		memberType := g.refGraph.applyConfigForType(member.Type)
+		if g.refGraph.isApplyConfig(member.Type) {
+			memberType = &types.Type{Kind: types.Pointer, Elem: memberType}
+		}
+		if jsonTags, ok := lookupJSONTags(member); ok {
+			memberParams := memberParams{
+				TypeParams: typeParams,
+				Member:     member,
+				MemberType: memberType,
+				JSONTags:   jsonTags,
+				EmbeddedIn: embed,
+			}
+			if memberParams.Member.Embedded {
+				g.generateGetters(member.Type, typeParams, sw, &memberParams)
+				continue
+			}
+
+			if needsGetter(t, member) {
+				g.generateMemberGetter(sw, memberParams)
+			}
+		}
+	}
+}
+
+func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams,
+	generated *[]string) {
+	for _, member := range t.Members {
+		if blocklisted(t, member) {
+			continue
+		}
+		memberType := g.refGraph.applyConfigForType(member.Type)
+		if g.refGraph.isApplyConfig(member.Type) {
+			memberType = &types.Type{Kind: types.Pointer, Elem: memberType}
+		}
+		if jsonTags, ok := lookupJSONTags(member); ok {
+			if slices.Contains(*generated, member.Name) {
+				klog.V(5).Infof("With%s already generated on %s, skipping\n", member.Name, t.Name)
+				continue
+			}
+			*generated = append(*generated, member.Name)
+			memberParams := memberParams{
+				TypeParams: typeParams,
+				Member:     member,
+				MemberType: memberType,
+				JSONTags:   jsonTags,
+				EmbeddedIn: embed,
+			}
+			if memberParams.Member.Embedded {
+				g.generateWithFuncs(member.Type, typeParams, sw, &memberParams, generated)
+				if !jsonTags.inline {
+					// non-inlined embeds are nillable and need a "ensure exists" utility function
+					sw.Do(ensureEmbedExists, memberParams)
+				}
+				continue
+			}
+
+			// For slices where the items are generated apply configuration types, accept varargs of
+			// pointers of the type as "with" function arguments so the "with" function can be used like so:
+			// WithFoos(Foo().WithName("x"), Foo().WithName("y"))
+			if t := deref(member.Type); t.Kind == types.Slice && g.refGraph.isApplyConfig(t.Elem) {
+				memberParams.ArgType = &types.Type{Kind: types.Pointer, Elem: memberType.Elem}
+				g.generateMemberWithForSlice(sw, member, memberParams)
+				continue
+			}
+			// Note: There are no maps where the values are generated apply configurations (because
+			// associative lists are used instead). So if a type like this is ever introduced, the
+			// default "with" function generator will produce a working (but not entirely convenient "with" function)
+			// that would be used like so:
+			// WithMap(map[string]FooApplyConfiguration{*Foo().WithName("x")})
+
+			switch memberParams.Member.Type.Kind {
+			case types.Slice:
+				memberParams.ArgType = memberType.Elem
+				g.generateMemberWithForSlice(sw, member, memberParams)
+			case types.Map:
+				g.generateMemberWithForMap(sw, memberParams)
+			default:
+				g.generateMemberWith(sw, memberParams)
+			}
+		}
+	}
+}
+
+func (g *applyConfigurationGenerator) generateStruct(sw *generator.SnippetWriter, typeParams TypeParams) {
+	sw.Do("// $.ApplyConfig.ApplyConfiguration|public$ represents a declarative configuration of the $.ApplyConfig.Type|public$ type for use\n", typeParams)
+	sw.Do("// with apply.\n", typeParams)
+	sw.Do("type $.ApplyConfig.ApplyConfiguration|public$ struct {\n", typeParams)
+	for _, structMember := range typeParams.Struct.Members {
+		if blocklisted(typeParams.Struct, structMember) {
+			continue
+		}
+		if structMemberTags, ok := lookupJSONTags(structMember); ok {
+			if !structMemberTags.inline {
+				structMemberTags.omitempty = true
+			}
+			params := memberParams{
+				TypeParams: typeParams,
+				Member:     structMember,
+				MemberType: g.refGraph.applyConfigForType(structMember.Type),
+				JSONTags:   structMemberTags,
+			}
+			if structMember.Embedded {
+				if structMemberTags.inline {
+					sw.Do("$.MemberType|raw$ `json:\"$.JSONTags$\"`\n", params)
+				} else {
+					sw.Do("*$.MemberType|raw$ `json:\"$.JSONTags$\"`\n", params)
+				}
+			} else if isNillable(structMember.Type) {
+				sw.Do("$.Member.Name$ $.MemberType|raw$ `json:\"$.JSONTags$\"`\n", params)
+			} else {
+				sw.Do("$.Member.Name$ *$.MemberType|raw$ `json:\"$.JSONTags$\"`\n", params)
+			}
+		}
+	}
+	sw.Do("}\n", typeParams)
+}
+
+func deref(t *types.Type) *types.Type {
+	for t.Kind == types.Pointer {
+		t = t.Elem
+	}
+	return t
+}
+
+func isNillable(t *types.Type) bool {
+	return t.Kind == types.Slice || t.Kind == types.Map
+}
+
+func (g *applyConfigurationGenerator) generateMemberWith(sw *generator.SnippetWriter, memberParams memberParams) {
+	sw.Do("// With$.Member.Name$ sets the $.Member.Name$ field in the declarative configuration to the given value\n", memberParams)
+	sw.Do("// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n", memberParams)
+	sw.Do("// If called multiple times, the $.Member.Name$ field is set to the value of the last call.\n", memberParams)
+	sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(value $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\n", memberParams)
+	g.ensureEmbedExistsIfApplicable(sw, memberParams)
+	if g.refGraph.isApplyConfig(memberParams.Member.Type) || isNillable(memberParams.Member.Type) {
+		sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = value\n", memberParams)
+	} else {
+		sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = &value\n", memberParams)
+	}
+	sw.Do("  return b\n", memberParams)
+	sw.Do("}\n", memberParams)
+}
+
+func (g *applyConfigurationGenerator) generateMemberGetter(sw *generator.SnippetWriter, memberParams memberParams) {
+	sw.Do("// Get$.Member.Name$ retrieves the value of the $.Member.Name$ field in the declarative configuration.\n", memberParams)
+	if g.refGraph.isApplyConfig(memberParams.Member.Type) || isNillable(memberParams.Member.Type) {
+		sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) Get$.Member.Name$() $.MemberType|raw$ {\n", memberParams)
+	} else {
+		sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) Get$.Member.Name$() *$.MemberType|raw$ {\n", memberParams)
+	}
+	g.ensureEmbedExistsIfApplicable(sw, memberParams)
+	sw.Do("  return b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$\n", memberParams)
+	sw.Do("}\n", memberParams)
+}
+
+func (g *applyConfigurationGenerator) generateMemberWithForSlice(sw *generator.SnippetWriter, member types.Member, memberParams memberParams) {
+	memberIsPointerToSlice := member.Type.Kind == types.Pointer
+	if memberIsPointerToSlice {
+		sw.Do(ensureNonEmbedSliceExists, memberParams)
+	}
+
+	sw.Do("// With$.Member.Name$ adds the given value to the $.Member.Name$ field in the declarative configuration\n", memberParams)
+	sw.Do("// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n", memberParams)
+	sw.Do("// If called multiple times, values provided by each call will be appended to the $.Member.Name$ field.\n", memberParams)
+	sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(values ...$.ArgType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\n", memberParams)
+	g.ensureEmbedExistsIfApplicable(sw, memberParams)
+
+	if memberIsPointerToSlice {
+		sw.Do("b.ensure$.MemberType.Elem|public$Exists()\n", memberParams)
+	}
+
+	sw.Do("  for i := range values {\n", memberParams)
+	if memberParams.ArgType.Kind == types.Pointer {
+		sw.Do("if values[i] == nil {\n", memberParams)
+		sw.Do("  panic(\"nil value passed to With$.Member.Name$\")\n", memberParams)
+		sw.Do("}\n", memberParams)
+
+		if memberIsPointerToSlice {
+			sw.Do("*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, *values[i])\n", memberParams)
+		} else {
+			sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, *values[i])\n", memberParams)
+		}
+	} else {
+		if memberIsPointerToSlice {
+			sw.Do("*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, values[i])\n", memberParams)
+		} else {
+			sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, values[i])\n", memberParams)
+		}
+	}
+	sw.Do("  }\n", memberParams)
+	sw.Do("  return b\n", memberParams)
+	sw.Do("}\n", memberParams)
+}
+
+func (g *applyConfigurationGenerator) generateMemberWithForMap(sw *generator.SnippetWriter, memberParams memberParams) {
+	sw.Do("// With$.Member.Name$ puts the entries into the $.Member.Name$ field in the declarative configuration\n", memberParams)
+	sw.Do("// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n", memberParams)
+	sw.Do("// If called multiple times, the entries provided by each call will be put on the $.Member.Name$ field,\n", memberParams)
+	sw.Do("// overwriting an existing map entries in $.Member.Name$ field with the same key.\n", memberParams)
+	sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(entries $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\n", memberParams)
+	g.ensureEmbedExistsIfApplicable(sw, memberParams)
+	sw.Do("  if b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ == nil && len(entries) > 0 {\n", memberParams)
+	sw.Do("    b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = make($.MemberType|raw$, len(entries))\n", memberParams)
+	sw.Do("  }\n", memberParams)
+	sw.Do("  for k, v := range entries {\n", memberParams)
+	sw.Do("    b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$[k] = v\n", memberParams)
+	sw.Do("  }\n", memberParams)
+	sw.Do("  return b\n", memberParams)
+	sw.Do("}\n", memberParams)
+}
+
+func (g *applyConfigurationGenerator) ensureEmbedExistsIfApplicable(sw *generator.SnippetWriter, memberParams memberParams) {
+	// Embedded types that are not inlined must be nillable so they are not included in the apply configuration
+	// when all their fields are omitted.
+	if memberParams.EmbeddedIn != nil && !memberParams.EmbeddedIn.JSONTags.inline {
+		sw.Do("b.ensure$.MemberType.Elem|public$Exists()\n", memberParams.EmbeddedIn)
+	}
+}
+
+var ensureEmbedExists = `
+func (b *$.ApplyConfig.ApplyConfiguration|public$) ensure$.MemberType.Elem|public$Exists() {
+  if b.$.MemberType.Elem|public$ == nil {
+    b.$.MemberType.Elem|public$ = &$.MemberType.Elem|raw${}
+  }
+}
+`
+
+var ensureNonEmbedSliceExists = `
+func (b *$.ApplyConfig.ApplyConfiguration|public$) ensure$.MemberType.Elem|public$Exists() {
+  if b.$.Member.Name$ == nil {
+    b.$.Member.Name$ = &[]$.MemberType.Elem|raw${}
+  }
+}
+`
+
+var clientgenTypeConstructorNamespaced = `
+// $.ApplyConfig.Type|public$ constructs a declarative configuration of the $.ApplyConfig.Type|public$ type for use with
+// apply.
+func $.ApplyConfig.Type|public$(name, namespace string) *$.ApplyConfig.ApplyConfiguration|public$ {
+  b := &$.ApplyConfig.ApplyConfiguration|public${}
+  b.WithName(name)
+  b.WithNamespace(namespace)
+  b.WithKind("$.ApplyConfig.Type|singularKind$")
+  b.WithAPIVersion("$.APIVersion$")
+  return b
+}
+`
+
+var clientgenTypeConstructorNonNamespaced = `
+// $.ApplyConfig.Type|public$ constructs a declarative configuration of the $.ApplyConfig.Type|public$ type for use with
+// apply.
+func $.ApplyConfig.Type|public$(name string) *$.ApplyConfig.ApplyConfiguration|public$ {
+  b := &$.ApplyConfig.ApplyConfiguration|public${}
+  b.WithName(name)
+  b.WithKind("$.ApplyConfig.Type|singularKind$")
+  b.WithAPIVersion("$.APIVersion$")
+  return b
+}
+`
+
+var constructorWithTypeMeta = `
+// $.ApplyConfig.ApplyConfiguration|public$ constructs a declarative configuration of the $.ApplyConfig.Type|public$ type for use with
+// apply.
+func $.ApplyConfig.Type|public$() *$.ApplyConfig.ApplyConfiguration|public$ {
+  b := &$.ApplyConfig.ApplyConfiguration|public${}
+  b.WithKind("$.ApplyConfig.Type|singularKind$")
+  b.WithAPIVersion("$.APIVersion$")
+  return b
+}
+`
+
+var constructor = `
+// $.ApplyConfig.ApplyConfiguration|public$ constructs a declarative configuration of the $.ApplyConfig.Type|public$ type for use with
+// apply.
+func $.ApplyConfig.Type|public$() *$.ApplyConfig.ApplyConfiguration|public$ {
+  return &$.ApplyConfig.ApplyConfiguration|public${}
+}
+`
+
+func (g *applyConfigurationGenerator) generateClientgenExtract(sw *generator.SnippetWriter, typeParams TypeParams, includeStatus bool) {
+	sw.Do(`
+// Extract$.ApplyConfig.Type|public$ extracts the applied configuration owned by fieldManager from
+// $.Struct|private$. If no managedFields are found in $.Struct|private$ for fieldManager, a
+// $.ApplyConfig.ApplyConfiguration|public$ is returned with only the Name, Namespace (if applicable),
+// APIVersion and Kind populated. It is possible that no managed fields were found for because other
+// field managers have taken ownership of all the fields previously owned by fieldManager, or because
+// the fieldManager never owned fields any fields.
+// $.Struct|private$ must be a unmodified $.Struct|public$ API object that was retrieved from the Kubernetes API.
+// Extract$.ApplyConfig.Type|public$ provides a way to perform a extract/modify-in-place/apply workflow.
+// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously
+// applied if another fieldManager has updated or force applied any of the previously applied fields.
+// Experimental!
+func Extract$.ApplyConfig.Type|public$($.Struct|private$ *$.Struct|raw$, fieldManager string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {
+	return extract$.ApplyConfig.Type|public$($.Struct|private$, fieldManager, "")
+}`, typeParams)
+	if includeStatus {
+		sw.Do(`
+// Extract$.ApplyConfig.Type|public$Status is the same as Extract$.ApplyConfig.Type|public$ except
+// that it extracts the status subresource applied configuration.
+// Experimental!
+func Extract$.ApplyConfig.Type|public$Status($.Struct|private$ *$.Struct|raw$, fieldManager string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {
+	return extract$.ApplyConfig.Type|public$($.Struct|private$, fieldManager, "status")
+}
+`, typeParams)
+	}
+	sw.Do(`
+func extract$.ApplyConfig.Type|public$($.Struct|private$ *$.Struct|raw$, fieldManager string, subresource string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {
+	b := &$.ApplyConfig.ApplyConfiguration|public${}
+	err := $.ExtractInto|raw$($.Struct|private$, $.ParserFunc|raw$().Type("$.OpenAPIType$"), fieldManager, b, subresource)
+	if err != nil {
+		return nil, err
+	}
+	b.WithName($.Struct|private$.Name)
+`, typeParams)
+	if !typeParams.Tags.NonNamespaced {
+		sw.Do("b.WithNamespace($.Struct|private$.Namespace)\n", typeParams)
+	}
+	sw.Do(`
+	b.WithKind("$.ApplyConfig.Type|singularKind$")
+	b.WithAPIVersion("$.APIVersion$")
+	return b, nil
+}
+`, typeParams)
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go
new file mode 100644
index 000000000..3ccc7ce83
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go
@@ -0,0 +1,98 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"io"
+
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/kube-openapi/pkg/schemaconv"
+	yaml "sigs.k8s.io/yaml/goyaml.v2"
+)
+
+// utilGenerator generates the ForKind() utility function.
+type internalGenerator struct {
+	generator.GoGenerator
+	outputPackage string
+	imports       namer.ImportTracker
+	typeModels    *typeModels
+	filtered      bool
+}
+
+var _ generator.Generator = &internalGenerator{}
+
+func (g *internalGenerator) Filter(*generator.Context, *types.Type) bool {
+	// generate file exactly once
+	if !g.filtered {
+		g.filtered = true
+		return true
+	}
+	return false
+}
+
+func (g *internalGenerator) Namers(*generator.Context) namer.NameSystems {
+	return namer.NameSystems{
+		"raw":          namer.NewRawNamer(g.outputPackage, g.imports),
+		"singularKind": namer.NewPublicNamer(0),
+	}
+}
+
+func (g *internalGenerator) Imports(*generator.Context) (imports []string) {
+	return g.imports.ImportLines()
+}
+
+func (g *internalGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error {
+	sw := generator.NewSnippetWriter(w, c, "{{", "}}")
+
+	schema, err := schemaconv.ToSchema(g.typeModels.models)
+	if err != nil {
+		return err
+	}
+	schemaYAML, err := yaml.Marshal(schema)
+	if err != nil {
+		return err
+	}
+	sw.Do(schemaBlock, map[string]interface{}{
+		"schemaYAML":   string(schemaYAML),
+		"smdParser":    smdParser,
+		"smdNewParser": smdNewParser,
+		"fmtSprintf":   fmtSprintf,
+		"syncOnce":     syncOnce,
+		"yamlObject":   yamlObject,
+	})
+
+	return sw.Error()
+}
+
+var schemaBlock = `
+func Parser() *{{.smdParser|raw}} {
+	parserOnce.Do(func() {
+		var err error
+		parser, err = {{.smdNewParser|raw}}(schemaYAML)
+		if err != nil {
+			panic({{.fmtSprintf|raw}}("Failed to parse schema: %v", err))
+		}
+	})
+	return parser
+}
+
+var parserOnce {{.syncOnce|raw}}
+var parser *{{.smdParser|raw}}
+var schemaYAML = {{.yamlObject|raw}}(` + "`{{.schemaYAML}}`" + `)
+`
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go
new file mode 100644
index 000000000..c11d05dee
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go
@@ -0,0 +1,99 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"reflect"
+	"strings"
+
+	"k8s.io/gengo/v2/types"
+)
+
+// TODO: This implements the same functionality as https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/runtime/converter.go#L236
+// but is based on the highly efficient approach from https://golang.org/src/encoding/json/encode.go
+
+// JSONTags represents a go json field tag.
+type JSONTags struct {
+	name      string
+	omit      bool
+	inline    bool
+	omitempty bool
+}
+
+func (t JSONTags) String() string {
+	var tag string
+	if !t.inline {
+		tag += t.name
+	}
+	if t.omitempty {
+		tag += ",omitempty"
+	}
+	if t.inline {
+		tag += ",inline"
+	}
+	return tag
+}
+
+func lookupJSONTags(m types.Member) (JSONTags, bool) {
+	tag := reflect.StructTag(m.Tags).Get("json")
+	if tag == "" || tag == "-" {
+		return JSONTags{}, false
+	}
+	name, opts := parseTag(tag)
+	if name == "" {
+		name = m.Name
+	}
+	return JSONTags{
+		name:      name,
+		omit:      false,
+		inline:    opts.Contains("inline"),
+		omitempty: opts.Contains("omitempty"),
+	}, true
+}
+
+type tagOptions string
+
+// parseTag splits a struct field's json tag into its name and
+// comma-separated options.
+func parseTag(tag string) (string, tagOptions) {
+	if idx := strings.Index(tag, ","); idx != -1 {
+		return tag[:idx], tagOptions(tag[idx+1:])
+	}
+	return tag, ""
+}
+
+// Contains reports whether a comma-separated listAlias of options
+// contains a particular substr flag. substr must be surrounded by a
+// string boundary or commas.
+func (o tagOptions) Contains(optionName string) bool {
+	if len(o) == 0 {
+		return false
+	}
+	s := string(o)
+	for s != "" {
+		var next string
+		i := strings.Index(s, ",")
+		if i >= 0 {
+			s, next = s[:i], s[i+1:]
+		}
+		if s == optionName {
+			return true
+		}
+		s = next
+	}
+	return false
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go
new file mode 100644
index 000000000..674413602
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go
@@ -0,0 +1,192 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"encoding/json"
+	"fmt"
+	"os"
+	"strings"
+
+	openapiv2 "github.com/google/gnostic-models/openapiv2"
+
+	clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
+	"k8s.io/gengo/v2/types"
+	utilproto "k8s.io/kube-openapi/pkg/util/proto"
+	"k8s.io/kube-openapi/pkg/validation/spec"
+)
+
+type typeModels struct {
+	models           utilproto.Models
+	gvkToOpenAPIType map[clientgentypes.GroupVersionKind]string
+}
+
+func newTypeModels(openAPISchemaFilePath string, pkgTypes map[string]*types.Package) (*typeModels, error) {
+	if len(openAPISchemaFilePath) == 0 {
+		return emptyModels, nil // No Extract() functions will be generated.
+	}
+
+	rawOpenAPISchema, err := os.ReadFile(openAPISchemaFilePath)
+	if err != nil {
+		return nil, fmt.Errorf("failed to read openapi-schema file: %w", err)
+	}
+
+	// Read in the provided openAPI schema.
+	openAPISchema := &spec.Swagger{}
+	err = json.Unmarshal(rawOpenAPISchema, openAPISchema)
+	if err != nil {
+		return nil, fmt.Errorf("failed to unmarshal typeModels JSON: %w", err)
+	}
+
+	// Build a mapping from openAPI type name to GVK.
+	// Find the root types needed by by client-go for apply.
+	gvkToOpenAPIType := map[clientgentypes.GroupVersionKind]string{}
+	rootDefs := map[string]spec.Schema{}
+	for _, p := range pkgTypes {
+		gv := groupVersion(p)
+		for _, t := range p.Types {
+			tags := genclientTags(t)
+			hasApply := tags.HasVerb("apply") || tags.HasVerb("applyStatus")
+			if tags.GenerateClient && hasApply {
+				openAPIType := friendlyName(typeName(t))
+				gvk := gv.WithKind(clientgentypes.Kind(t.Name.Name))
+				rootDefs[openAPIType] = openAPISchema.Definitions[openAPIType]
+				gvkToOpenAPIType[gvk] = openAPIType
+			}
+		}
+	}
+
+	// Trim the schema down to just the types needed by client-go for apply.
+	requiredDefs := make(map[string]spec.Schema)
+	for name, def := range rootDefs {
+		requiredDefs[name] = def
+		findReferenced(&def, openAPISchema.Definitions, requiredDefs)
+	}
+	openAPISchema.Definitions = requiredDefs
+
+	// Convert the openAPI schema to the models format and validate it.
+	models, err := toValidatedModels(openAPISchema)
+	if err != nil {
+		return nil, err
+	}
+	return &typeModels{models: models, gvkToOpenAPIType: gvkToOpenAPIType}, nil
+}
+
+var emptyModels = &typeModels{
+	models:           &utilproto.Definitions{},
+	gvkToOpenAPIType: map[clientgentypes.GroupVersionKind]string{},
+}
+
+func toValidatedModels(openAPISchema *spec.Swagger) (utilproto.Models, error) {
+	// openapi_v2.ParseDocument only accepts a []byte of the JSON or YAML file to be parsed.
+	// so we do an inefficient marshal back to json and then read it back in as yaml
+	// but get the benefit of running the models through utilproto.NewOpenAPIData to
+	// validate all the references between types
+	rawMinimalOpenAPISchema, err := json.Marshal(openAPISchema)
+	if err != nil {
+		return nil, fmt.Errorf("failed to unmarshal openAPI as JSON: %w", err)
+	}
+
+	document, err := openapiv2.ParseDocument(rawMinimalOpenAPISchema)
+	if err != nil {
+		return nil, fmt.Errorf("failed to parse OpenAPI document for file: %w", err)
+	}
+	// Construct the models and validate all references are valid.
+	models, err := utilproto.NewOpenAPIData(document)
+	if err != nil {
+		return nil, fmt.Errorf("failed to create OpenAPI models for file: %w", err)
+	}
+	return models, nil
+}
+
+// findReferenced recursively finds all schemas referenced from the given def.
+// toValidatedModels makes sure no references get missed.
+func findReferenced(def *spec.Schema, allSchemas, referencedOut map[string]spec.Schema) {
+	// follow $ref, if any
+	refPtr := def.Ref.GetPointer()
+	if refPtr != nil && !refPtr.IsEmpty() {
+		name := refPtr.String()
+		if !strings.HasPrefix(name, "/definitions/") {
+			return
+		}
+		name = strings.TrimPrefix(name, "/definitions/")
+		schema, ok := allSchemas[name]
+		if !ok {
+			panic(fmt.Sprintf("allSchemas schema is missing referenced type: %s", name))
+		}
+		if _, ok := referencedOut[name]; !ok {
+			referencedOut[name] = schema
+			findReferenced(&schema, allSchemas, referencedOut)
+		}
+	}
+
+	// follow any nested schemas
+	if def.Items != nil {
+		if def.Items.Schema != nil {
+			findReferenced(def.Items.Schema, allSchemas, referencedOut)
+		}
+		for _, item := range def.Items.Schemas {
+			findReferenced(&item, allSchemas, referencedOut)
+		}
+	}
+	if def.AllOf != nil {
+		for _, s := range def.AllOf {
+			findReferenced(&s, allSchemas, referencedOut)
+		}
+	}
+	if def.AnyOf != nil {
+		for _, s := range def.AnyOf {
+			findReferenced(&s, allSchemas, referencedOut)
+		}
+	}
+	if def.OneOf != nil {
+		for _, s := range def.OneOf {
+			findReferenced(&s, allSchemas, referencedOut)
+		}
+	}
+	if def.Not != nil {
+		findReferenced(def.Not, allSchemas, referencedOut)
+	}
+	if def.Properties != nil {
+		for _, prop := range def.Properties {
+			findReferenced(&prop, allSchemas, referencedOut)
+		}
+	}
+	if def.AdditionalProperties != nil && def.AdditionalProperties.Schema != nil {
+		findReferenced(def.AdditionalProperties.Schema, allSchemas, referencedOut)
+	}
+	if def.PatternProperties != nil {
+		for _, s := range def.PatternProperties {
+			findReferenced(&s, allSchemas, referencedOut)
+		}
+	}
+	if def.Dependencies != nil {
+		for _, d := range def.Dependencies {
+			if d.Schema != nil {
+				findReferenced(d.Schema, allSchemas, referencedOut)
+			}
+		}
+	}
+	if def.AdditionalItems != nil && def.AdditionalItems.Schema != nil {
+		findReferenced(def.AdditionalItems.Schema, allSchemas, referencedOut)
+	}
+	if def.Definitions != nil {
+		for _, s := range def.Definitions {
+			findReferenced(&s, allSchemas, referencedOut)
+		}
+	}
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go
new file mode 100644
index 000000000..8b4675529
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go
@@ -0,0 +1,175 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"k8s.io/gengo/v2/types"
+
+	"k8s.io/code-generator/cmd/client-gen/generators/util"
+)
+
+// refGraph maps existing types to the package the corresponding applyConfig types will be generated in
+// so that references between apply configurations can be correctly generated.
+type refGraph map[types.Name]string
+
+// refGraphForReachableTypes returns a refGraph that contains all reachable types from
+// the root clientgen types of the provided packages.
+func refGraphForReachableTypes(universe types.Universe, pkgTypes map[string]*types.Package, initialTypes map[types.Name]string) refGraph {
+	var refs refGraph = initialTypes
+
+	// Include only types that are reachable from the root clientgen types.
+	// We don't want to generate apply configurations for types that are not reachable from a root
+	// clientgen type.
+	reachableTypes := map[types.Name]*types.Type{}
+	for _, p := range pkgTypes {
+		for _, t := range p.Types {
+			tags := genclientTags(t)
+			hasApply := tags.HasVerb("apply") || tags.HasVerb("applyStatus")
+			if tags.GenerateClient && hasApply {
+				findReachableTypes(t, reachableTypes)
+			}
+			// If any apply extensions have custom inputs, add them.
+			for _, extension := range tags.Extensions {
+				if extension.HasVerb("apply") {
+					if len(extension.InputTypeOverride) > 0 {
+						inputType := *t
+						if name, pkg := extension.Input(); len(pkg) > 0 {
+							inputType = *(universe.Type(types.Name{Package: pkg, Name: name}))
+						} else {
+							inputType.Name.Name = extension.InputTypeOverride
+						}
+						findReachableTypes(&inputType, reachableTypes)
+					}
+				}
+			}
+		}
+	}
+	for pkg, p := range pkgTypes {
+		for _, t := range p.Types {
+			if _, ok := reachableTypes[t.Name]; !ok {
+				continue
+			}
+			if requiresApplyConfiguration(t) {
+				refs[t.Name] = pkg
+			}
+		}
+	}
+
+	return refs
+}
+
+// applyConfigForType find the type used in the generate apply configurations for a field.
+// This may either be an existing type or one of the other generated applyConfig types.
+func (t refGraph) applyConfigForType(field *types.Type) *types.Type {
+	switch field.Kind {
+	case types.Struct:
+		if pkg, ok := t[field.Name]; ok { // TODO(jpbetz): Refs to types defined in a separate system (e.g. TypeMeta if generating a 3rd party controller) end up referencing the go struct, not the apply configuration type
+			return types.Ref(pkg, field.Name.Name+ApplyConfigurationTypeSuffix)
+		}
+		return field
+	case types.Map:
+		if _, ok := t[field.Elem.Name]; ok {
+			return &types.Type{
+				Kind: types.Map,
+				Elem: t.applyConfigForType(field.Elem),
+				Key:  t.applyConfigForType(field.Key),
+			}
+		}
+		return field
+	case types.Slice:
+		if _, ok := t[field.Elem.Name]; ok {
+			return &types.Type{
+				Kind: types.Slice,
+				Elem: t.applyConfigForType(field.Elem),
+			}
+		}
+		return field
+	case types.Pointer:
+		return t.applyConfigForType(field.Elem)
+	default:
+		return field
+	}
+}
+
+func (t refGraph) isApplyConfig(field *types.Type) bool {
+	switch field.Kind {
+	case types.Struct:
+		_, ok := t[field.Name]
+		return ok
+	case types.Pointer:
+		return t.isApplyConfig(field.Elem)
+	}
+	return false
+}
+
+// genclientTags returns the genclient Tags for the given type.
+func genclientTags(t *types.Type) util.Tags {
+	return util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))
+}
+
+// findReachableTypes finds all types transitively reachable from a given root type, including
+// the root type itself.
+func findReachableTypes(t *types.Type, referencedTypes map[types.Name]*types.Type) {
+	if _, ok := referencedTypes[t.Name]; ok {
+		return
+	}
+	referencedTypes[t.Name] = t
+
+	if t.Elem != nil {
+		findReachableTypes(t.Elem, referencedTypes)
+	}
+	if t.Underlying != nil {
+		findReachableTypes(t.Underlying, referencedTypes)
+	}
+	if t.Key != nil {
+		findReachableTypes(t.Key, referencedTypes)
+	}
+	for _, m := range t.Members {
+		findReachableTypes(m.Type, referencedTypes)
+	}
+}
+
+// excludeTypes contains well known types that we do not generate apply configurations for.
+// Hard coding because we only have two, very specific types that serve a special purpose
+// in the type system here.
+var excludeTypes = map[types.Name]struct{}{
+	rawExtension.Name: {},
+	unknown.Name:      {},
+	// DO NOT ADD TO THIS LIST. If we need to exclude other types, we should consider allowing the
+	// go type declarations to be annotated as excluded from this generator.
+}
+
+// requiresApplyConfiguration returns true if a type applyConfig should be generated for the given type.
+// types applyConfig are only generated for struct types that contain fields with json tags.
+func requiresApplyConfiguration(t *types.Type) bool {
+	for t.Kind == types.Alias {
+		t = t.Underlying
+	}
+	if t.Kind != types.Struct {
+		return false
+	}
+	if _, ok := excludeTypes[t.Name]; ok {
+		return false
+	}
+	var hasJSONTaggedMembers bool
+	for _, member := range t.Members {
+		if _, ok := lookupJSONTags(member); ok {
+			hasJSONTaggedMembers = true
+		}
+	}
+	return hasJSONTaggedMembers
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/targets.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/targets.go
new file mode 100644
index 000000000..b033d22d8
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/targets.go
@@ -0,0 +1,314 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"fmt"
+	"path"
+	"path/filepath"
+	"sort"
+	"strings"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+
+	"k8s.io/code-generator/cmd/applyconfiguration-gen/args"
+	"k8s.io/code-generator/cmd/client-gen/generators/util"
+	clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
+)
+
+const (
+	// ApplyConfigurationTypeSuffix is the suffix of generated apply configuration types.
+	ApplyConfigurationTypeSuffix = "ApplyConfiguration"
+)
+
+// NameSystems returns the name system used by the generators in this package.
+func NameSystems() namer.NameSystems {
+	return namer.NameSystems{
+		"public":  namer.NewPublicNamer(0),
+		"private": namer.NewPrivateNamer(0),
+		"raw":     namer.NewRawNamer("", nil),
+	}
+}
+
+// DefaultNameSystem returns the default name system for ordering the types to be
+// processed by the generators in this package.
+func DefaultNameSystem() string {
+	return "public"
+}
+
+// GetTargets makes the client target definition.
+func GetTargets(context *generator.Context, args *args.Args) []generator.Target {
+	boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, "", gengo.StdGeneratedBy)
+	if err != nil {
+		klog.Fatalf("Failed loading boilerplate: %v", err)
+	}
+
+	pkgTypes := packageTypesForInputs(context, args.OutputPkg)
+	initialTypes := args.ExternalApplyConfigurations
+	refs := refGraphForReachableTypes(context.Universe, pkgTypes, initialTypes)
+	typeModels, err := newTypeModels(args.OpenAPISchemaFilePath, pkgTypes)
+	if err != nil {
+		klog.Fatalf("Failed build type models from typeModels %s: %v", args.OpenAPISchemaFilePath, err)
+	}
+
+	groupVersions := make(map[string]clientgentypes.GroupVersions)
+	groupGoNames := make(map[string]string)
+	applyConfigsForGroupVersion := make(map[clientgentypes.GroupVersion][]applyConfig)
+
+	var targetList []generator.Target
+	for pkg, p := range pkgTypes {
+		gv := groupVersion(p)
+
+		var toGenerate []applyConfig
+		for _, t := range p.Types {
+			// If we don't have an ObjectMeta field, we lack the information required to make the Apply or ApplyStatus call
+			// to the kube-apiserver, so we don't need to generate the type at all
+			clientTags := genclientTags(t)
+			if clientTags.GenerateClient && !hasObjectMetaField(t) {
+				klog.V(5).Infof("skipping type %v because does not have ObjectMeta", t)
+				continue
+			}
+			gvk := gv.WithKind(clientgentypes.Kind(t.Name.Name))
+			openAPIName := typeModels.gvkToOpenAPIType[gvk]
+
+			if typePkg, ok := refs[t.Name]; ok {
+				toGenerate = append(toGenerate, applyConfig{
+					Type:               t,
+					ApplyConfiguration: types.Ref(typePkg, t.Name.Name+ApplyConfigurationTypeSuffix),
+					OpenAPIName:        openAPIName,
+				})
+			}
+		}
+		if len(toGenerate) == 0 {
+			continue // Don't generate empty packages
+		}
+		sort.Sort(applyConfigSort(toGenerate))
+
+		// Apparently we allow the groupName to be overridden in a way that it
+		// no longer maps to a Go package by name.  So we have to figure out
+		// the offset of this particular output package (pkg) from the base
+		// output package (args.OutputPkg).
+		pkgSubdir := strings.TrimPrefix(pkg, args.OutputPkg+"/")
+
+		// generate the apply configurations
+		targetList = append(targetList,
+			targetForApplyConfigurationsPackage(
+				args.OutputDir, args.OutputPkg, pkgSubdir,
+				boilerplate, gv, toGenerate, refs, typeModels))
+
+		// group all the generated apply configurations by gv so ForKind() can be generated
+		groupPackageName := gv.Group.NonEmpty()
+		groupVersionsEntry, ok := groupVersions[groupPackageName]
+		if !ok {
+			groupVersionsEntry = clientgentypes.GroupVersions{
+				PackageName: groupPackageName,
+				Group:       gv.Group,
+			}
+		}
+		groupVersionsEntry.Versions = append(groupVersionsEntry.Versions, clientgentypes.PackageVersion{
+			Version: gv.Version,
+			Package: path.Clean(p.Path),
+		})
+
+		groupGoNames[groupPackageName] = goName(gv, p)
+		applyConfigsForGroupVersion[gv] = toGenerate
+		groupVersions[groupPackageName] = groupVersionsEntry
+	}
+
+	// generate ForKind() utility function
+	targetList = append(targetList,
+		targetForUtils(args.OutputDir, args.OutputPkg,
+			boilerplate, groupVersions, applyConfigsForGroupVersion, groupGoNames, typeModels))
+	// generate internal embedded schema, required for generated Extract functions
+	targetList = append(targetList,
+		targetForInternal(args.OutputDir, args.OutputPkg,
+			boilerplate, typeModels))
+
+	return targetList
+}
+
+func friendlyName(name string) string {
+	nameParts := strings.Split(name, "/")
+	// Reverse first part. e.g., io.k8s... instead of k8s.io...
+	if len(nameParts) > 0 && strings.Contains(nameParts[0], ".") {
+		parts := strings.Split(nameParts[0], ".")
+		for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
+			parts[i], parts[j] = parts[j], parts[i]
+		}
+		nameParts[0] = strings.Join(parts, ".")
+	}
+	return strings.Join(nameParts, ".")
+}
+
+func typeName(t *types.Type) string {
+	typePackage := t.Name.Package
+	return fmt.Sprintf("%s.%s", typePackage, t.Name.Name)
+}
+
+func targetForApplyConfigurationsPackage(outputDirBase, outputPkgBase, pkgSubdir string, boilerplate []byte, gv clientgentypes.GroupVersion, typesToGenerate []applyConfig, refs refGraph, models *typeModels) generator.Target {
+	outputDir := filepath.Join(outputDirBase, pkgSubdir)
+	outputPkg := path.Join(outputPkgBase, pkgSubdir)
+
+	return &generator.SimpleTarget{
+		PkgName:       gv.Version.PackageName(),
+		PkgPath:       outputPkg,
+		PkgDir:        outputDir,
+		HeaderComment: boilerplate,
+		GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) {
+			for _, toGenerate := range typesToGenerate {
+				var openAPIType *string
+				gvk := gv.WithKind(clientgentypes.Kind(toGenerate.Type.Name.Name))
+				if v, ok := models.gvkToOpenAPIType[gvk]; ok {
+					openAPIType = &v
+				}
+
+				generators = append(generators, &applyConfigurationGenerator{
+					GoGenerator: generator.GoGenerator{
+						OutputFilename: strings.ToLower(toGenerate.Type.Name.Name) + ".go",
+					},
+					outPkgBase:   outputPkgBase,
+					localPkg:     outputPkg,
+					groupVersion: gv,
+					applyConfig:  toGenerate,
+					imports:      generator.NewImportTrackerForPackage(outputPkg),
+					refGraph:     refs,
+					openAPIType:  openAPIType,
+				})
+			}
+			return generators
+		},
+	}
+}
+
+func targetForUtils(outputDirBase, outputPkgBase string, boilerplate []byte, groupVersions map[string]clientgentypes.GroupVersions,
+	applyConfigsForGroupVersion map[clientgentypes.GroupVersion][]applyConfig, groupGoNames map[string]string, models *typeModels) generator.Target {
+	return &generator.SimpleTarget{
+		PkgName:       path.Base(outputPkgBase),
+		PkgPath:       outputPkgBase,
+		PkgDir:        outputDirBase,
+		HeaderComment: boilerplate,
+		GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) {
+			generators = append(generators, &utilGenerator{
+				GoGenerator: generator.GoGenerator{
+					OutputFilename: "utils.go",
+				},
+				outputPackage:        outputPkgBase,
+				imports:              generator.NewImportTrackerForPackage(outputPkgBase),
+				groupVersions:        groupVersions,
+				typesForGroupVersion: applyConfigsForGroupVersion,
+				groupGoNames:         groupGoNames,
+				typeModels:           models,
+			})
+			return generators
+		},
+	}
+}
+
+func targetForInternal(outputDirBase, outputPkgBase string, boilerplate []byte, models *typeModels) generator.Target {
+	outputDir := filepath.Join(outputDirBase, "internal")
+	outputPkg := path.Join(outputPkgBase, "internal")
+	return &generator.SimpleTarget{
+		PkgName:       path.Base(outputPkg),
+		PkgPath:       outputPkg,
+		PkgDir:        outputDir,
+		HeaderComment: boilerplate,
+		GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) {
+			generators = append(generators, &internalGenerator{
+				GoGenerator: generator.GoGenerator{
+					OutputFilename: "internal.go",
+				},
+				outputPackage: outputPkgBase,
+				imports:       generator.NewImportTrackerForPackage(outputPkg),
+				typeModels:    models,
+			})
+			return generators
+		},
+	}
+}
+
+func goName(gv clientgentypes.GroupVersion, p *types.Package) string {
+	goName := namer.IC(strings.Split(gv.Group.NonEmpty(), ".")[0])
+	if override := gengo.ExtractCommentTags("+", p.Comments)["groupGoName"]; override != nil {
+		goName = namer.IC(override[0])
+	}
+	return goName
+}
+
+func packageTypesForInputs(context *generator.Context, outPkgBase string) map[string]*types.Package {
+	pkgTypes := map[string]*types.Package{}
+	for _, inputDir := range context.Inputs {
+		p := context.Universe.Package(inputDir)
+		internal := isInternalPackage(p)
+		if internal {
+			klog.Warningf("Skipping internal package: %s", p.Path)
+			continue
+		}
+		// This is how the client generator finds the package we are creating. It uses the API package name, not the group name.
+		// This matches the approach of the client-gen, so the two generator can work together.
+		// For example, if openshift/api/cloudnetwork/v1 contains an apigroup cloud.network.openshift.io, the client-gen
+		// builds a package called cloudnetwork/v1 to contain it. This change makes the applyconfiguration-gen use the same.
+		_, gvPackageString := util.ParsePathGroupVersion(p.Path)
+		pkg := path.Join(outPkgBase, strings.ToLower(gvPackageString))
+		pkgTypes[pkg] = p
+	}
+	return pkgTypes
+}
+
+func groupVersion(p *types.Package) (gv clientgentypes.GroupVersion) {
+	parts := strings.Split(p.Path, "/")
+	gv.Group = clientgentypes.Group(parts[len(parts)-2])
+	gv.Version = clientgentypes.Version(parts[len(parts)-1])
+
+	// If there's a comment of the form "// +groupName=somegroup" or
+	// "// +groupName=somegroup.foo.bar.io", use the first field (somegroup) as the name of the
+	// group when generating.
+	if override := gengo.ExtractCommentTags("+", p.Comments)["groupName"]; override != nil {
+		gv.Group = clientgentypes.Group(override[0])
+	}
+	return gv
+}
+
+// isInternalPackage returns true if the package is an internal package
+func isInternalPackage(p *types.Package) bool {
+	for _, t := range p.Types {
+		for _, member := range t.Members {
+			if member.Name == "ObjectMeta" {
+				return isInternal(member)
+			}
+		}
+	}
+	return false
+}
+
+// isInternal returns true if the tags for a member do not contain a json tag
+func isInternal(m types.Member) bool {
+	_, ok := lookupJSONTags(m)
+	return !ok
+}
+
+func hasObjectMetaField(t *types.Type) bool {
+	for _, member := range t.Members {
+		if objectMeta.Name == member.Type.Name && member.Embedded {
+			return true
+		}
+	}
+	return false
+}
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/types.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/types.go
new file mode 100644
index 000000000..08c53c2a4
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/types.go
@@ -0,0 +1,36 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import "k8s.io/gengo/v2/types"
+
+var (
+	fmtSprintf           = types.Ref("fmt", "Sprintf")
+	syncOnce             = types.Ref("sync", "Once")
+	applyConfiguration   = types.Ref("k8s.io/apimachinery/pkg/runtime", "ApplyConfiguration")
+	groupVersionKind     = types.Ref("k8s.io/apimachinery/pkg/runtime/schema", "GroupVersionKind")
+	typeMeta             = types.Ref("k8s.io/apimachinery/pkg/apis/meta/v1", "TypeMeta")
+	objectMeta           = types.Ref("k8s.io/apimachinery/pkg/apis/meta/v1", "ObjectMeta")
+	rawExtension         = types.Ref("k8s.io/apimachinery/pkg/runtime", "RawExtension")
+	unknown              = types.Ref("k8s.io/apimachinery/pkg/runtime", "Unknown")
+	extractInto          = types.Ref("k8s.io/apimachinery/pkg/util/managedfields", "ExtractInto")
+	runtimeScheme        = types.Ref("k8s.io/apimachinery/pkg/runtime", "Scheme")
+	smdNewParser         = types.Ref("sigs.k8s.io/structured-merge-diff/v4/typed", "NewParser")
+	smdParser            = types.Ref("sigs.k8s.io/structured-merge-diff/v4/typed", "Parser")
+	testingTypeConverter = types.Ref("k8s.io/client-go/testing", "TypeConverter")
+	yamlObject           = types.Ref("sigs.k8s.io/structured-merge-diff/v4/typed", "YAMLObject")
+)
diff --git a/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go
new file mode 100644
index 000000000..136d9c495
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go
@@ -0,0 +1,176 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"io"
+	"path"
+	"sort"
+	"strings"
+
+	clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
+
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+)
+
+// utilGenerator generates the ForKind() utility function.
+type utilGenerator struct {
+	generator.GoGenerator
+	outputPackage        string
+	imports              namer.ImportTracker
+	groupVersions        map[string]clientgentypes.GroupVersions
+	groupGoNames         map[string]string
+	typesForGroupVersion map[clientgentypes.GroupVersion][]applyConfig
+	filtered             bool
+	typeModels           *typeModels
+}
+
+var _ generator.Generator = &utilGenerator{}
+
+func (g *utilGenerator) Filter(*generator.Context, *types.Type) bool {
+	// generate file exactly once
+	if !g.filtered {
+		g.filtered = true
+		return true
+	}
+	return false
+}
+
+func (g *utilGenerator) Namers(*generator.Context) namer.NameSystems {
+	return namer.NameSystems{
+		"raw":          namer.NewRawNamer(g.outputPackage, g.imports),
+		"singularKind": namer.NewPublicNamer(0),
+	}
+}
+
+func (g *utilGenerator) Imports(*generator.Context) (imports []string) {
+	return g.imports.ImportLines()
+}
+
+type group struct {
+	GroupGoName string
+	Name        string
+	Versions    []*version
+}
+
+type groupSort []group
+
+func (g groupSort) Len() int { return len(g) }
+func (g groupSort) Less(i, j int) bool {
+	return strings.ToLower(g[i].Name) < strings.ToLower(g[j].Name)
+}
+func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
+
+type version struct {
+	Name      string
+	GoName    string
+	Resources []applyConfig
+}
+
+type versionSort []*version
+
+func (v versionSort) Len() int { return len(v) }
+func (v versionSort) Less(i, j int) bool {
+	return strings.ToLower(v[i].Name) < strings.ToLower(v[j].Name)
+}
+func (v versionSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
+
+type applyConfig struct {
+	Type               *types.Type
+	ApplyConfiguration *types.Type
+	OpenAPIName        string
+}
+
+type applyConfigSort []applyConfig
+
+func (v applyConfigSort) Len() int { return len(v) }
+func (v applyConfigSort) Less(i, j int) bool {
+	return strings.ToLower(v[i].Type.Name.Name) < strings.ToLower(v[j].Type.Name.Name)
+}
+func (v applyConfigSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
+
+func (g *utilGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error {
+	sw := generator.NewSnippetWriter(w, c, "{{", "}}")
+
+	var groups []group
+	schemeGVs := make(map[*version]*types.Type)
+
+	for groupPackageName, groupVersions := range g.groupVersions {
+		group := group{
+			GroupGoName: g.groupGoNames[groupPackageName],
+			Name:        groupVersions.Group.NonEmpty(),
+			Versions:    []*version{},
+		}
+		for _, v := range groupVersions.Versions {
+			gv := clientgentypes.GroupVersion{Group: groupVersions.Group, Version: v.Version}
+			version := &version{
+				Name:      v.Version.NonEmpty(),
+				GoName:    namer.IC(v.Version.NonEmpty()),
+				Resources: g.typesForGroupVersion[gv],
+			}
+			schemeGVs[version] = c.Universe.Variable(types.Name{
+				Package: g.typesForGroupVersion[gv][0].Type.Name.Package,
+				Name:    "SchemeGroupVersion",
+			})
+			group.Versions = append(group.Versions, version)
+		}
+		sort.Sort(versionSort(group.Versions))
+		groups = append(groups, group)
+	}
+	sort.Sort(groupSort(groups))
+
+	m := map[string]interface{}{
+		"applyConfiguration":     applyConfiguration,
+		"groups":                 groups,
+		"internalParser":         types.Ref(path.Join(g.outputPackage, "internal"), "Parser"),
+		"runtimeScheme":          runtimeScheme,
+		"schemeGVs":              schemeGVs,
+		"schemaGroupVersionKind": groupVersionKind,
+		"testingTypeConverter":   testingTypeConverter,
+	}
+	sw.Do(forKindFunc, m)
+	sw.Do(typeConverter, m)
+
+	return sw.Error()
+}
+
+var typeConverter = `
+func NewTypeConverter(scheme *{{.runtimeScheme|raw}}) *{{.testingTypeConverter|raw}} {
+	return &{{.testingTypeConverter|raw}}{Scheme: scheme, TypeResolver: {{.internalParser|raw}}()}
+}
+`
+
+var forKindFunc = `
+// ForKind returns an apply configuration type for the given GroupVersionKind, or nil if no
+// apply configuration type exists for the given GroupVersionKind.
+func ForKind(kind {{.schemaGroupVersionKind|raw}}) interface{} {
+	switch kind {
+		{{range $group := .groups -}}{{$GroupGoName := .GroupGoName -}}
+			{{range $version := .Versions -}}
+	// Group={{$group.Name}}, Version={{.Name}}
+				{{range .Resources -}}
+	case {{index $.schemeGVs $version|raw}}.WithKind("{{.Type|singularKind}}"):
+		return &{{.ApplyConfiguration|raw}}{}
+				{{end}}
+			{{end}}
+		{{end -}}
+	}
+	return nil
+}
+`
diff --git a/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/gvpackages.go b/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/gvpackages.go
new file mode 100644
index 000000000..fcc195090
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/gvpackages.go
@@ -0,0 +1,30 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package util
+
+import "strings"
+
+func ParsePathGroupVersion(pgvString string) (gvPath string, gvString string) {
+	subs := strings.Split(pgvString, "/")
+	length := len(subs)
+	switch length {
+	case 0, 1, 2:
+		return "", pgvString
+	default:
+		return strings.Join(subs[:length-2], "/"), strings.Join(subs[length-2:], "/")
+	}
+}
diff --git a/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go b/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go
new file mode 100644
index 000000000..5218dfad3
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go
@@ -0,0 +1,344 @@
+/*
+Copyright 2016 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package util
+
+import (
+	"errors"
+	"fmt"
+	"strings"
+
+	"k8s.io/gengo/v2"
+)
+
+var supportedTags = []string{
+	"genclient",
+	"genclient:nonNamespaced",
+	"genclient:noVerbs",
+	"genclient:onlyVerbs",
+	"genclient:skipVerbs",
+	"genclient:noStatus",
+	"genclient:readonly",
+	"genclient:method",
+}
+
+// SupportedVerbs is a list of supported verbs for +onlyVerbs and +skipVerbs.
+var SupportedVerbs = []string{
+	"create",
+	"update",
+	"updateStatus",
+	"delete",
+	"deleteCollection",
+	"get",
+	"list",
+	"watch",
+	"patch",
+	"apply",
+	"applyStatus",
+}
+
+// ReadonlyVerbs represents a list of read-only verbs.
+var ReadonlyVerbs = []string{
+	"get",
+	"list",
+	"watch",
+}
+
+// genClientPrefix is the default prefix for all genclient tags.
+const genClientPrefix = "genclient:"
+
+// unsupportedExtensionVerbs is a list of verbs we don't support generating
+// extension client functions for.
+var unsupportedExtensionVerbs = []string{
+	"updateStatus",
+	"deleteCollection",
+	"watch",
+	"delete",
+}
+
+// inputTypeSupportedVerbs is a list of verb types that supports overriding the
+// input argument type.
+var inputTypeSupportedVerbs = []string{
+	"create",
+	"update",
+	"apply",
+}
+
+// resultTypeSupportedVerbs is a list of verb types that supports overriding the
+// resulting type.
+var resultTypeSupportedVerbs = []string{
+	"create",
+	"update",
+	"get",
+	"list",
+	"patch",
+	"apply",
+}
+
+// Extensions allows to extend the default set of client verbs
+// (CRUD+watch+patch+list+deleteCollection) for a given type with custom defined
+// verbs. Custom verbs can have custom input and result types and also allow to
+// use a sub-resource in a request instead of top-level resource type.
+//
+// Example:
+//
+// +genclient:method=UpdateScale,verb=update,subresource=scale,input=Scale,result=Scale
+//
+// type ReplicaSet struct { ... }
+//
+// The 'method=UpdateScale' is the name of the client function.
+// The 'verb=update' here means the client function will use 'PUT' action.
+// The 'subresource=scale' means we will use SubResource template to generate this client function.
+// The 'input' is the input type used for creation (function argument).
+// The 'result' (not needed in this case) is the result type returned from the
+// client function.
+type extension struct {
+	// VerbName is the name of the custom verb (Scale, Instantiate, etc..)
+	VerbName string
+	// VerbType is the type of the verb (only verbs from SupportedVerbs are
+	// supported)
+	VerbType string
+	// SubResourcePath defines a path to a sub-resource to use in the request.
+	// (optional)
+	SubResourcePath string
+	// InputTypeOverride overrides the input parameter type for the verb. By
+	// default the original type is used. Overriding the input type only works for
+	// "create" and "update" verb types. The given type must exists in the same
+	// package as the original type.
+	// (optional)
+	InputTypeOverride string
+	// ResultTypeOverride overrides the resulting object type for the verb. By
+	// default the original type is used. Overriding the result type works.
+	// (optional)
+	ResultTypeOverride string
+}
+
+// IsSubresource indicates if this extension should generate the sub-resource.
+func (e *extension) IsSubresource() bool {
+	return len(e.SubResourcePath) > 0
+}
+
+// HasVerb checks if the extension matches the given verb.
+func (e *extension) HasVerb(verb string) bool {
+	return e.VerbType == verb
+}
+
+// Input returns the input override package path and the type.
+func (e *extension) Input() (string, string) {
+	parts := strings.Split(e.InputTypeOverride, ".")
+	return parts[len(parts)-1], strings.Join(parts[0:len(parts)-1], ".")
+}
+
+// Result returns the result override package path and the type.
+func (e *extension) Result() (string, string) {
+	parts := strings.Split(e.ResultTypeOverride, ".")
+	return parts[len(parts)-1], strings.Join(parts[0:len(parts)-1], ".")
+}
+
+// Tags represents a genclient configuration for a single type.
+type Tags struct {
+	// +genclient
+	GenerateClient bool
+	// +genclient:nonNamespaced
+	NonNamespaced bool
+	// +genclient:noStatus
+	NoStatus bool
+	// +genclient:noVerbs
+	NoVerbs bool
+	// +genclient:skipVerbs=get,update
+	// +genclient:onlyVerbs=create,delete
+	SkipVerbs []string
+	// +genclient:method=UpdateScale,verb=update,subresource=scale,input=Scale,result=Scale
+	Extensions []extension
+}
+
+// HasVerb returns true if we should include the given verb in final client interface and
+// generate the function for it.
+func (t Tags) HasVerb(verb string) bool {
+	if len(t.SkipVerbs) == 0 {
+		return true
+	}
+	for _, s := range t.SkipVerbs {
+		if verb == s {
+			return false
+		}
+	}
+	return true
+}
+
+// MustParseClientGenTags calls ParseClientGenTags but instead of returning error it panics.
+func MustParseClientGenTags(lines []string) Tags {
+	tags, err := ParseClientGenTags(lines)
+	if err != nil {
+		panic(err.Error())
+	}
+	return tags
+}
+
+// ParseClientGenTags parse the provided genclient tags and validates that no unknown
+// tags are provided.
+func ParseClientGenTags(lines []string) (Tags, error) {
+	ret := Tags{}
+	values := gengo.ExtractCommentTags("+", lines)
+	var value []string
+	value, ret.GenerateClient = values["genclient"]
+	// Check the old format and error when used to avoid generating client when //+genclient=false
+	if len(value) > 0 && len(value[0]) > 0 {
+		return ret, fmt.Errorf("+genclient=%s is invalid, use //+genclient if you want to generate client or omit it when you want to disable generation", value)
+	}
+	_, ret.NonNamespaced = values[genClientPrefix+"nonNamespaced"]
+	// Check the old format and error when used
+	if value := values["nonNamespaced"]; len(value) > 0 && len(value[0]) > 0 {
+		return ret, fmt.Errorf("+nonNamespaced=%s is invalid, use //+genclient:nonNamespaced instead", value[0])
+	}
+	_, ret.NoVerbs = values[genClientPrefix+"noVerbs"]
+	_, ret.NoStatus = values[genClientPrefix+"noStatus"]
+	onlyVerbs := []string{}
+	if _, isReadonly := values[genClientPrefix+"readonly"]; isReadonly {
+		onlyVerbs = ReadonlyVerbs
+	}
+	// Check the old format and error when used
+	if value := values["readonly"]; len(value) > 0 && len(value[0]) > 0 {
+		return ret, fmt.Errorf("+readonly=%s is invalid, use //+genclient:readonly instead", value[0])
+	}
+	if v, exists := values[genClientPrefix+"skipVerbs"]; exists {
+		ret.SkipVerbs = strings.Split(v[0], ",")
+	}
+	if v, exists := values[genClientPrefix+"onlyVerbs"]; exists || len(onlyVerbs) > 0 {
+		if len(v) > 0 {
+			onlyVerbs = append(onlyVerbs, strings.Split(v[0], ",")...)
+		}
+		skipVerbs := []string{}
+		for _, m := range SupportedVerbs {
+			skip := true
+			for _, o := range onlyVerbs {
+				if o == m {
+					skip = false
+					break
+				}
+			}
+			// Check for conflicts
+			for _, v := range skipVerbs {
+				if v == m {
+					return ret, fmt.Errorf("verb %q used both in genclient:skipVerbs and genclient:onlyVerbs", v)
+				}
+			}
+			if skip {
+				skipVerbs = append(skipVerbs, m)
+			}
+		}
+		ret.SkipVerbs = skipVerbs
+	}
+	var err error
+	if ret.Extensions, err = parseClientExtensions(values); err != nil {
+		return ret, err
+	}
+	return ret, validateClientGenTags(values)
+}
+
+func parseClientExtensions(tags map[string][]string) ([]extension, error) {
+	var ret []extension
+	for name, values := range tags {
+		if !strings.HasPrefix(name, genClientPrefix+"method") {
+			continue
+		}
+		for _, value := range values {
+			// the value comes in this form: "Foo,verb=create"
+			ext := extension{}
+			parts := strings.Split(value, ",")
+			if len(parts) == 0 {
+				return nil, fmt.Errorf("invalid of empty extension verb name: %q", value)
+			}
+			// The first part represents the name of the extension
+			ext.VerbName = parts[0]
+			if len(ext.VerbName) == 0 {
+				return nil, fmt.Errorf("must specify a verb name (// +genclient:method=Foo,verb=create)")
+			}
+			// Parse rest of the arguments
+			params := parts[1:]
+			for _, p := range params {
+				parts := strings.Split(p, "=")
+				if len(parts) != 2 {
+					return nil, fmt.Errorf("invalid extension tag specification %q", p)
+				}
+				key, val := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
+				if len(val) == 0 {
+					return nil, fmt.Errorf("empty value of %q for %q extension", key, ext.VerbName)
+				}
+				switch key {
+				case "verb":
+					ext.VerbType = val
+				case "subresource":
+					ext.SubResourcePath = val
+				case "input":
+					ext.InputTypeOverride = val
+				case "result":
+					ext.ResultTypeOverride = val
+				default:
+					return nil, fmt.Errorf("unknown extension configuration key %q", key)
+				}
+			}
+			// Validate resulting extension configuration
+			if len(ext.VerbType) == 0 {
+				return nil, fmt.Errorf("verb type must be specified (use '// +genclient:method=%s,verb=create')", ext.VerbName)
+			}
+			if len(ext.ResultTypeOverride) > 0 {
+				supported := false
+				for _, v := range resultTypeSupportedVerbs {
+					if ext.VerbType == v {
+						supported = true
+						break
+					}
+				}
+				if !supported {
+					return nil, fmt.Errorf("%s: result type is not supported for %q verbs (supported verbs: %#v)", ext.VerbName, ext.VerbType, resultTypeSupportedVerbs)
+				}
+			}
+			if len(ext.InputTypeOverride) > 0 {
+				supported := false
+				for _, v := range inputTypeSupportedVerbs {
+					if ext.VerbType == v {
+						supported = true
+						break
+					}
+				}
+				if !supported {
+					return nil, fmt.Errorf("%s: input type is not supported for %q verbs (supported verbs: %#v)", ext.VerbName, ext.VerbType, inputTypeSupportedVerbs)
+				}
+			}
+			for _, t := range unsupportedExtensionVerbs {
+				if ext.VerbType == t {
+					return nil, fmt.Errorf("verb %q is not supported by extension generator", ext.VerbType)
+				}
+			}
+			ret = append(ret, ext)
+		}
+	}
+	return ret, nil
+}
+
+// validateTags validates that only supported genclient tags were provided.
+func validateClientGenTags(values map[string][]string) error {
+	for _, k := range supportedTags {
+		delete(values, k)
+	}
+	for key := range values {
+		if strings.HasPrefix(key, strings.TrimSuffix(genClientPrefix, ":")) {
+			return errors.New("unknown tag detected: " + key)
+		}
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/code-generator/cmd/client-gen/types/helpers.go b/vendor/k8s.io/code-generator/cmd/client-gen/types/helpers.go
new file mode 100644
index 000000000..c84a77531
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/client-gen/types/helpers.go
@@ -0,0 +1,121 @@
+/*
+Copyright 2016 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package types
+
+import (
+	"fmt"
+	"regexp"
+	"sort"
+	"strings"
+
+	"k8s.io/gengo/v2/namer"
+)
+
+// ToGroupVersion turns "group/version" string into a GroupVersion struct. It reports error
+// if it cannot parse the string.
+func ToGroupVersion(gv string) (GroupVersion, error) {
+	// this can be the internal version for the legacy kube types
+	// TODO once we've cleared the last uses as strings, this special case should be removed.
+	if (len(gv) == 0) || (gv == "/") {
+		return GroupVersion{}, nil
+	}
+
+	switch strings.Count(gv, "/") {
+	case 0:
+		return GroupVersion{Group(gv), ""}, nil
+	case 1:
+		i := strings.Index(gv, "/")
+		return GroupVersion{Group(gv[:i]), Version(gv[i+1:])}, nil
+	default:
+		return GroupVersion{}, fmt.Errorf("unexpected GroupVersion string: %v", gv)
+	}
+}
+
+type sortableSliceOfVersions []string
+
+func (a sortableSliceOfVersions) Len() int      { return len(a) }
+func (a sortableSliceOfVersions) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a sortableSliceOfVersions) Less(i, j int) bool {
+	vi, vj := strings.TrimLeft(a[i], "v"), strings.TrimLeft(a[j], "v")
+	major := regexp.MustCompile("^[0-9]+")
+	viMajor, vjMajor := major.FindString(vi), major.FindString(vj)
+	viRemaining, vjRemaining := strings.TrimLeft(vi, viMajor), strings.TrimLeft(vj, vjMajor)
+	switch {
+	case len(viRemaining) == 0 && len(vjRemaining) == 0:
+		return viMajor < vjMajor
+	case len(viRemaining) == 0 && len(vjRemaining) != 0:
+		// stable version is greater than unstable version
+		return false
+	case len(viRemaining) != 0 && len(vjRemaining) == 0:
+		// stable version is greater than unstable version
+		return true
+	}
+	// neither are stable versions
+	if viMajor != vjMajor {
+		return viMajor < vjMajor
+	}
+	// assuming at most we have one alpha or one beta version, so if vi contains "alpha", it's the lesser one.
+	return strings.Contains(viRemaining, "alpha")
+}
+
+// Determine the default version among versions. If a user calls a group client
+// without specifying the version (e.g., c.CoreV1(), instead of c.CoreV1()), the
+// default version will be returned.
+func defaultVersion(versions []PackageVersion) Version {
+	var versionStrings []string
+	for _, version := range versions {
+		versionStrings = append(versionStrings, version.Version.String())
+	}
+	sort.Sort(sortableSliceOfVersions(versionStrings))
+	return Version(versionStrings[len(versionStrings)-1])
+}
+
+// ToGroupVersionInfo is a helper function used by generators for groups.
+func ToGroupVersionInfo(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupVersionInfo {
+	var groupVersionPackages []GroupVersionInfo
+	for _, group := range groups {
+		for _, version := range group.Versions {
+			groupGoName := groupGoNames[GroupVersion{Group: group.Group, Version: version.Version}]
+			groupVersionPackages = append(groupVersionPackages, GroupVersionInfo{
+				Group:                Group(namer.IC(group.Group.NonEmpty())),
+				Version:              Version(namer.IC(version.Version.String())),
+				PackageAlias:         strings.ToLower(groupGoName + version.Version.NonEmpty()),
+				GroupGoName:          groupGoName,
+				LowerCaseGroupGoName: namer.IL(groupGoName),
+			})
+		}
+	}
+	return groupVersionPackages
+}
+
+func ToGroupInstallPackages(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupInstallPackage {
+	var groupInstallPackages []GroupInstallPackage
+	for _, group := range groups {
+		defaultVersion := defaultVersion(group.Versions)
+		groupGoName := groupGoNames[GroupVersion{Group: group.Group, Version: defaultVersion}]
+		groupInstallPackages = append(groupInstallPackages, GroupInstallPackage{
+			Group:               Group(namer.IC(group.Group.NonEmpty())),
+			InstallPackageAlias: strings.ToLower(groupGoName),
+		})
+	}
+	return groupInstallPackages
+}
+
+// NormalizeGroupVersion calls normalizes the GroupVersion.
+// func NormalizeGroupVersion(gv GroupVersion) GroupVersion {
+// 	 return GroupVersion{Group: gv.Group.NonEmpty(), Version: gv.Version, NonEmptyVersion: normalization.Version(gv.Version)}
+// }
diff --git a/vendor/k8s.io/code-generator/cmd/client-gen/types/types.go b/vendor/k8s.io/code-generator/cmd/client-gen/types/types.go
new file mode 100644
index 000000000..df030e845
--- /dev/null
+++ b/vendor/k8s.io/code-generator/cmd/client-gen/types/types.go
@@ -0,0 +1,109 @@
+/*
+Copyright 2016 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package types
+
+import "strings"
+
+type Version string
+
+func (v Version) String() string {
+	return string(v)
+}
+
+func (v Version) NonEmpty() string {
+	if v == "" {
+		return "internalVersion"
+	}
+	return v.String()
+}
+
+func (v Version) PackageName() string {
+	return strings.ToLower(v.NonEmpty())
+}
+
+type Group string
+
+func (g Group) String() string {
+	return string(g)
+}
+
+func (g Group) NonEmpty() string {
+	if g == "" {
+		return "core"
+	}
+	return string(g)
+}
+
+func (g Group) PackageName() string {
+	parts := strings.Split(g.NonEmpty(), ".")
+	if parts[0] == "internal" && len(parts) > 1 {
+		return strings.ToLower(parts[1] + parts[0])
+	}
+	return strings.ToLower(parts[0])
+}
+
+type Kind string
+
+type PackageVersion struct {
+	Version
+	// The fully qualified package, e.g. k8s.io/kubernetes/pkg/apis/apps, where the types.go is found.
+	Package string
+}
+
+type GroupVersion struct {
+	Group   Group
+	Version Version
+}
+
+type GroupVersionKind struct {
+	Group   Group
+	Version Version
+	Kind    Kind
+}
+
+func (gv GroupVersion) ToAPIVersion() string {
+	if len(gv.Group) > 0 && gv.Group != "" {
+		return gv.Group.String() + "/" + gv.Version.String()
+	} else {
+		return gv.Version.String()
+	}
+}
+
+func (gv GroupVersion) WithKind(kind Kind) GroupVersionKind {
+	return GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: kind}
+}
+
+type GroupVersions struct {
+	// The name of the package for this group, e.g. apps.
+	PackageName string
+	Group       Group
+	Versions    []PackageVersion
+}
+
+// GroupVersionInfo contains all the info around a group version.
+type GroupVersionInfo struct {
+	Group                Group
+	Version              Version
+	PackageAlias         string
+	GroupGoName          string
+	LowerCaseGroupGoName string
+}
+
+type GroupInstallPackage struct {
+	Group               Group
+	InstallPackageAlias string
+}
diff --git a/vendor/k8s.io/gengo/v2/LICENSE b/vendor/k8s.io/gengo/v2/LICENSE
new file mode 100644
index 000000000..00b240110
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2014 The Kubernetes Authors.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/vendor/k8s.io/gengo/v2/Makefile b/vendor/k8s.io/gengo/v2/Makefile
new file mode 100644
index 000000000..8d0fbdaa8
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/Makefile
@@ -0,0 +1,14 @@
+all:
+	go build ./...
+
+test:
+	GODEBUG=gotypesalias=0 go test -race ./... -count=1
+	GODEBUG=gotypesalias=1 go test -race ./... -count=1
+
+# We verify for the maximum version of the go directive as 1.20
+# here because the oldest go directive that exists on our supported
+# release branches in k/k is 1.20.
+verify:
+	GODEBUG=gotypesalias=0 ./hack/verify-examples.sh
+	GODEBUG=gotypesalias=1 ./hack/verify-examples.sh
+	./hack/verify-go-directive.sh 1.20
diff --git a/vendor/k8s.io/gengo/v2/README.md b/vendor/k8s.io/gengo/v2/README.md
new file mode 100644
index 000000000..e1dff4b4b
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/README.md
@@ -0,0 +1,53 @@
+[![GoDoc Widget]][GoDoc]  [![GoReport]][GoReportStatus]
+
+[GoDoc]: https://godoc.org/k8s.io/gengo
+[GoDoc Widget]: https://godoc.org/k8s.io/gengo?status.svg
+[GoReport]: https://goreportcard.com/badge/github.com/kubernetes/gengo
+[GoReportStatus]: https://goreportcard.com/report/github.com/kubernetes/gengo
+
+# Gengo: a framework for building simple code generators
+
+This repo is used by Kubernetes to build some codegen tooling.  It is not
+intended to be general-purpose and makes some assumptions that may not hold
+outside of Kubernetes.
+
+In the past this repo was partially supported for external use (outside of the
+Kubernetes project overall), but that is no longer true.  We may change the API
+in incompatible ways, without warning.
+
+If you are not building something that is part of Kubernetes, DO NOT DEPEND ON
+THIS REPO.
+
+## New usage within Kubernetes
+
+Gengo is a very opinionated framework.  It is primarily aimed at generating Go
+code derived from types defined in other Go code, but it is possible to use it
+for other things (e.g. proto files).  Net new tools should consider using
+`golang.org/x/tools/go/packages` directly.  Gengo can serve as an example of
+how to do that.
+
+If you still decide you want to use gengo, see the
+[simple examples](./examples) in this repo or the more extensive tools in the
+Kubernetes [code-generator](https://github.com/kubernetes/code-generator/)
+repo.
+
+## Overview
+
+Gengo is used to build tools (generally a tool is a binary).  Each tool
+describes some number of `Targets`. A target is a single output package, which
+may be the same as the inputs (if the tool generates code alongside the inputs)
+or different.  Each `Target` describes some number of `Generators`.  A
+generator is responsible for emitting a single file into the target directory.
+
+Gengo helps the tool to load and process input packages, e.g. extracting type
+information and associating comments.  Each target will be offered every known
+type, and can filter that down to the set of types it cares about.  Each
+generator will be offered the result of the target's filtering, and can filter
+the set of types further.  Finally, the generator will be called to emit code
+for all of the remaining types.
+
+The `tracer` example in this repo can be used to examine all of the hooks.
+
+## Contributing
+
+Please see [CONTRIBUTING.md](../CONTRIBUTING.md) for instructions on how to contribute.
diff --git a/vendor/k8s.io/gengo/v2/codetags/extractor.go b/vendor/k8s.io/gengo/v2/codetags/extractor.go
new file mode 100644
index 000000000..5e58b0083
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/codetags/extractor.go
@@ -0,0 +1,85 @@
+/*
+Copyright 2025 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package codetags
+
+import (
+	"strings"
+	"unicode/utf8"
+)
+
+// Extract identifies and collects lines containing special metadata tags.
+// It processes only lines that begin with the prefix.
+//
+// The portion of a line immediately following the prefix is treated as
+// a potential tag name. To be considered valid, this tag name must
+// match the regular expression `[a-zA-Z_][a-zA-Z0-9_.-:]*`.
+//
+// Extract returns a map where each key is a valid tag name found in
+// lines that begin with the prefix.
+// The value for each key is a slice of strings. Each string in this slice
+// represents the contents of an original line after the prefix has been removed.
+//
+// Example: When called with prefix "+k8s:", lines:
+//
+//	Comment line without marker
+//	+k8s:noArgs # comment
+//	+withValue=value1
+//	+withValue=value2
+//	+k8s:withArg(arg1)=value1
+//	+k8s:withArg(arg2)=value2 # comment
+//	+k8s:withNamedArgs(arg1=value1, arg2=value2)=value
+//
+// Then this function will return:
+//
+//	map[string][]string{
+//		"noArgs":        {"noArgs # comment"},
+//		"withArg":       {"withArg(arg1)=value1", "withArg(arg2)=value2 # comment"},
+//		"withNamedArgs": {"withNamedArgs(arg1=value1, arg2=value2)=value"},
+//	}
+func Extract(prefix string, lines []string) map[string][]string {
+	out := map[string][]string{}
+	for _, line := range lines {
+		line = strings.TrimLeft(line, " \t")
+		if !strings.HasPrefix(line, prefix) {
+			continue
+		}
+		line = line[len(prefix):]
+
+		// Find the end of the presumed tag name.
+		nameEnd := findNameEnd(line)
+		name := line[:nameEnd]
+		out[name] = append(out[name], line)
+	}
+	return out
+}
+
+// findNameEnd matches a tag in the same way as the parser.
+func findNameEnd(s string) int {
+	if len(s) == 0 {
+		return 0
+	}
+	if r, _ := utf8.DecodeRuneInString(s); !isIdentBegin(r) {
+		return 0
+	}
+	idx := strings.IndexFunc(s, func(r rune) bool {
+		return !(isTagNameInterior(r))
+	})
+	if idx == -1 {
+		return len(s)
+	}
+	return idx
+}
diff --git a/vendor/k8s.io/gengo/v2/codetags/parser.go b/vendor/k8s.io/gengo/v2/codetags/parser.go
new file mode 100644
index 000000000..8ff49b039
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/codetags/parser.go
@@ -0,0 +1,407 @@
+/*
+Copyright 2025 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package codetags
+
+import (
+	"fmt"
+	"strings"
+	"unicode"
+)
+
+// Parse parses a tag string into a Tag, or returns an error if the tag
+// string fails to parse.
+//
+// ParseOption may be provided to modify the behavior of the parser. The below
+// describes the default behavior.
+//
+// A tag consists of a name, optional arguments, and an optional scalar value or
+// tag value. For example,
+//
+//	"name"
+//	"name=50"
+//	"name("featureX")=50"
+//	"name(limit: 10, path: "/xyz")=text value"
+//	"name(limit: 10, path: "/xyz")=+anotherTag(size: 100)"
+//
+// Arguments are optional and may be either:
+//   - A single positional argument.
+//   - One or more named arguments (in the format `name: value`).
+//   - (Positional and named arguments cannot be mixed.)
+//
+// For example,
+//
+//	"name()"
+//	"name(arg)"
+//	"name(namedArg1: argValue1)"
+//	"name(namedArg1: argValue1, namedArg2: argValue2)"
+//
+// Argument values may be strings, ints, booleans, or identifiers.
+//
+// For example,
+//
+//	"name("double-quoted")"
+//	"name(`backtick-quoted`)"
+//	"name(100)"
+//	"name(true)"
+//	"name(arg1: identifier)"
+//	"name(arg1:`string value`)"
+//	"name(arg1: 100)"
+//	"name(arg1: true)"
+//
+// Note: When processing Go source code comments, the Extract function is
+// typically used first to find and isolate tag strings matching a specific
+// prefix. Those extracted strings can then be parsed using this function.
+//
+// The value part of the tag is optional and follows an equals sign "=". If a
+// value is present, it must be a string, int, boolean, identifier, or tag.
+//
+// For example,
+//
+//	"name" # no value
+//	"name=identifier"
+//	"name="double-quoted value""
+//	"name=`backtick-quoted value`"
+//	"name(100)"
+//	"name(true)"
+//	"name=+anotherTag"
+//	"name=+anotherTag(size: 100)"
+//
+// Trailing comments are ignored unless the RawValues option is enabled, in which
+// case they are treated as part of the value.
+//
+// For example,
+//
+//	"key=value # This comment is ignored"
+//
+// Formal Grammar:
+//
+//              ::=  [ "(" [  ] ")" ] [ ( "="  | "=+"  ) ]
+//             ::=  | 
+//        ::=  [ ","  ]*
+//  ::=  ":" 
+//            ::=  |  |  | 
+//
+//        ::= [a-zA-Z_][a-zA-Z0-9_-.:]*
+//     ::= [a-zA-Z_][a-zA-Z0-9_-.]*
+//         ::= /* Go-style double-quoted or backtick-quoted strings,
+// ...                    with standard Go escape sequences for double-quoted strings. */
+//            ::= /* Standard Go integer literals (decimal, 0x hex, 0o octal, 0b binary),
+// ...                    with an optional +/- prefix. */
+//           ::= "true" | "false"
+func Parse(tag string, options ...ParseOption) (Tag, error) {
+	opts := parseOpts{}
+	for _, o := range options {
+		o(&opts)
+	}
+
+	tag = strings.TrimSpace(tag)
+	return parseTag(tag, opts)
+}
+
+// ParseAll calls Parse on each tag in the input slice.
+func ParseAll(tags []string, options ...ParseOption) ([]Tag, error) {
+	var out []Tag
+	for _, tag := range tags {
+		parsed, err := Parse(tag, options...)
+		if err != nil {
+			return nil, err
+		}
+		out = append(out, parsed)
+	}
+	return out, nil
+}
+
+type parseOpts struct {
+	rawValues bool
+}
+
+// ParseOption provides a parser option.
+type ParseOption func(*parseOpts)
+
+// RawValues skips parsing of the value part of the tag. If enabled, the Value
+// in the parse response will contain all text following the "=" sign, up to the last
+// non-whitespace character, and ValueType will be set to ValueTypeRaw.
+// Default: disabled
+func RawValues(enabled bool) ParseOption {
+	return func(opts *parseOpts) {
+		opts.rawValues = enabled
+	}
+}
+
+func parseTag(input string, opts parseOpts) (Tag, error) {
+	const (
+		stTag           = "stTag"
+		stMaybeArgs     = "stMaybeArgs"
+		stArg           = "stArg"
+		stArgEndOfToken = "stArgEndOfToken"
+		stMaybeValue    = "stMaybeValue"
+		stValue         = "stValue"
+		stMaybeComment  = "stMaybeComment"
+	)
+	var startTag, endTag *Tag // both ends of the chain when parsing chained tags
+
+	// accumulators
+	var tagName string      // current tag name
+	var value string        // current value
+	var valueType ValueType // current value type
+	cur := Arg{}            // current argument
+	var args []Arg          // current arguments slice
+
+	s := scanner{buf: []rune(input)} // scanner for parsing the tag string
+	var incomplete bool              // tracks if a token is incomplete
+
+	// These are defined outside the loop to make errors easier.
+	saveArg := func(v string, t ArgType) {
+		cur.Value = v
+		cur.Type = t
+		args = append(args, cur)
+		cur = Arg{}
+	}
+	saveInt := func(v string) { saveArg(v, ArgTypeInt) }
+	saveString := func(v string) { saveArg(v, ArgTypeString) }
+	saveBoolOrString := func(value string) {
+		if value == "true" || value == "false" {
+			saveArg(value, ArgTypeBool)
+		} else {
+			saveArg(value, ArgTypeString)
+		}
+	}
+	saveName := func(value string) {
+		cur.Name = value
+	}
+	saveTag := func() error {
+		usingNamedArgs := false
+		for i, arg := range args {
+			if (usingNamedArgs && arg.Name == "") || (!usingNamedArgs && arg.Name != "" && i > 0) {
+				return fmt.Errorf("can't mix named and positional arguments")
+			}
+			if arg.Name != "" {
+				usingNamedArgs = true
+			}
+		}
+		if !usingNamedArgs && len(args) > 1 {
+			return fmt.Errorf("multiple arguments must use 'name: value' syntax")
+		}
+		newTag := &Tag{Name: tagName, Args: args}
+		if startTag == nil {
+			startTag = newTag
+			endTag = newTag
+		} else {
+			endTag.ValueTag = newTag
+			endTag.ValueType = ValueTypeTag
+			endTag = newTag
+		}
+		args = nil // Reset to nil instead of empty slice
+		return nil
+	}
+	saveValue := func() {
+		endTag.Value = value
+		endTag.ValueType = valueType
+	}
+	var err error
+	st := stTag
+parseLoop:
+	for r := s.peek(); r != EOF; r = s.peek() {
+		switch st {
+		case stTag: // Any leading whitespace is expected to be trimmed before parsing.
+			switch {
+			case isIdentBegin(r):
+				tagName, err = s.nextIdent(isTagNameInterior)
+				if err != nil {
+					return Tag{}, err
+				}
+				st = stMaybeArgs
+			default:
+				break parseLoop
+			}
+		case stMaybeArgs:
+			switch {
+			case r == '(':
+				s.next() // consume (
+				incomplete = true
+				st = stArg
+			case r == '=':
+				s.next() // consume =
+				if opts.rawValues {
+					// only raw values support empty values following =
+					valueType = ValueTypeRaw
+				} else {
+					incomplete = true
+				}
+				st = stValue
+			default:
+				st = stMaybeComment
+			}
+		case stArg:
+			switch {
+			case r == ')':
+				s.next() // consume )
+				incomplete = false
+				st = stMaybeValue
+			case r == '-' || r == '+' || unicode.IsDigit(r):
+				number, err := s.nextNumber()
+				if err != nil {
+					return Tag{}, err
+				}
+				saveInt(number)
+				st = stArgEndOfToken
+			case r == '"' || r == '`':
+				str, err := s.nextString()
+				if err != nil {
+					return Tag{}, err
+				}
+				saveString(str)
+				st = stArgEndOfToken
+			case isIdentBegin(r):
+				identifier, err := s.nextIdent(isIdentInterior)
+				if err != nil {
+					return Tag{}, err
+				}
+				r = s.peek() // reset r after nextIdent
+
+				switch {
+				case r == ',' || r == ')': // positional arg
+					if r == ',' {
+						r = s.skipWhitespace() // allow whitespace after ,
+					}
+					saveBoolOrString(identifier)
+					st = stArgEndOfToken
+				case r == ':': // named arg
+					s.next()               // consume :
+					r = s.skipWhitespace() // allow whitespace after :
+					saveName(identifier)
+					st = stArg
+				default:
+					break parseLoop
+				}
+			default:
+				break parseLoop
+			}
+		case stArgEndOfToken:
+			switch {
+			case r == ',':
+				s.next()               // consume ,
+				r = s.skipWhitespace() // allow whitespace after ,
+				st = stArg
+			case r == ')':
+				s.next() // consume )
+				incomplete = false
+				st = stMaybeValue
+			default:
+				break parseLoop
+			}
+		case stMaybeValue:
+			switch {
+			case r == '=':
+				s.next() // consume =
+				if opts.rawValues {
+					// Empty values are allowed for raw.
+					// Since = might be the last char in the input, we need
+					// to record the valueType as raw immediately.
+					valueType = ValueTypeRaw
+				}
+				st = stValue
+			default:
+				st = stMaybeComment
+			}
+		case stValue:
+			switch {
+			case opts.rawValues: // When enabled, consume all remaining chars
+				incomplete = false
+				value = s.remainder()
+				break parseLoop
+			case r == '+' && isIdentBegin(s.peekN(1)): // tag value
+				incomplete = false
+				s.next() // consume +
+				if err := saveTag(); err != nil {
+					return Tag{}, err
+				}
+				st = stTag
+			case r == '-' || r == '+' || unicode.IsDigit(r):
+				incomplete = false
+				number, err := s.nextNumber()
+				valueType = ValueTypeInt
+				if err != nil {
+					return Tag{}, err
+				}
+				value = number
+				st = stMaybeComment
+			case r == '"' || r == '`':
+				incomplete = false
+				str, err := s.nextString()
+				if err != nil {
+					return Tag{}, err
+				}
+				value = str
+				valueType = ValueTypeString
+				st = stMaybeComment
+			case isIdentBegin(r):
+				incomplete = false
+				str, err := s.nextIdent(isIdentInterior)
+				if err != nil {
+					return Tag{}, err
+				}
+				value = str
+				if str == "true" || str == "false" {
+					valueType = ValueTypeBool
+				} else {
+					valueType = ValueTypeString
+				}
+				st = stMaybeComment
+			default:
+				break parseLoop
+			}
+		case stMaybeComment:
+			switch {
+			case s.nextIsTrailingComment():
+				s.remainder()
+			default:
+				break parseLoop
+			}
+		default:
+			return Tag{}, fmt.Errorf("unexpected internal parser error: unknown state: %s at position %d", st, s.pos)
+		}
+	}
+	if s.peek() != EOF {
+		return Tag{}, fmt.Errorf("unexpected character %q at position %d", s.next(), s.pos)
+	}
+	if incomplete {
+		return Tag{}, fmt.Errorf("unexpected end of input")
+	}
+	if err := saveTag(); err != nil {
+		return Tag{}, err
+	}
+	if len(valueType) > 0 {
+		saveValue()
+	}
+	if startTag == nil {
+		return Tag{}, fmt.Errorf("unexpected internal parser error: no tags parsed")
+	}
+	return *startTag, nil
+}
+
+func isIdentBegin(r rune) bool {
+	return unicode.IsLetter(r) || r == '_'
+}
+
+func isIdentInterior(r rune) bool {
+	return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.' || r == '-'
+}
+
+func isTagNameInterior(r rune) bool {
+	return isIdentInterior(r) || r == ':'
+}
diff --git a/vendor/k8s.io/gengo/v2/codetags/scanner.go b/vendor/k8s.io/gengo/v2/codetags/scanner.go
new file mode 100644
index 000000000..5204e347f
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/codetags/scanner.go
@@ -0,0 +1,228 @@
+/*
+Copyright 2025 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package codetags
+
+import (
+	"bytes"
+	"fmt"
+	"strconv"
+	"strings"
+	"unicode"
+)
+
+type scanner struct {
+	buf []rune
+	pos int
+}
+
+func (s *scanner) next() rune {
+	if s.pos >= len(s.buf) {
+		return EOF
+	}
+	r := s.buf[s.pos]
+	s.pos++
+	return r
+}
+
+func (s *scanner) peek() rune {
+	return s.peekN(0)
+}
+
+func (s *scanner) peekN(n int) rune {
+	if s.pos+n >= len(s.buf) {
+		return EOF
+	}
+	return s.buf[s.pos+n]
+}
+
+func (s *scanner) skipWhitespace() rune {
+	for r := s.peek(); unicode.IsSpace(r); r = s.peek() {
+		s.next()
+	}
+	return s.peek()
+}
+
+func (s *scanner) remainder() string {
+	result := string(s.buf[s.pos:])
+	s.pos = len(s.buf)
+	return result
+}
+
+const (
+	EOF = -1
+)
+
+func (s *scanner) nextIsTrailingComment() bool {
+	i := 0
+	for ; unicode.IsSpace(s.peekN(i)); i++ {
+	}
+	return s.peekN(i) == '#'
+}
+
+func (s *scanner) nextNumber() (string, error) {
+	const (
+		stBegin  = "stBegin"
+		stPrefix = "stPrefix"
+		stPosNeg = "stPosNeg"
+		stNumber = "stNumber"
+	)
+	var buf bytes.Buffer
+	st := stBegin
+
+parseLoop:
+	for r := s.peek(); r != EOF; r = s.peek() {
+		switch st {
+		case stBegin:
+			switch {
+			case r == '0':
+				buf.WriteRune(s.next())
+				st = stPrefix
+			case r == '+' || r == '-':
+				buf.WriteRune(s.next())
+				st = stPosNeg
+			case unicode.IsDigit(r):
+				buf.WriteRune(s.next())
+				st = stNumber
+			default:
+				break parseLoop
+			}
+		case stPosNeg:
+			switch {
+			case r == '0':
+				buf.WriteRune(s.next())
+				st = stPrefix
+			case unicode.IsDigit(r):
+				buf.WriteRune(s.next())
+				st = stNumber
+			default:
+				break parseLoop
+			}
+		case stPrefix:
+			switch {
+			case unicode.IsDigit(r):
+				buf.WriteRune(s.next())
+				st = stNumber
+			case r == 'x' || r == 'o' || r == 'b':
+				buf.WriteRune(s.next())
+				st = stNumber
+			default:
+				break parseLoop
+			}
+		case stNumber:
+			const hexits = "abcdefABCDEF"
+			switch {
+			case unicode.IsDigit(r) || strings.Contains(hexits, string(r)):
+				buf.WriteRune(s.next())
+			default:
+				break parseLoop
+			}
+		default:
+			return "", fmt.Errorf("unexpected internal parser error: unknown state: %s at position %d", st, s.pos)
+		}
+	}
+	numStr := buf.String()
+	if _, err := strconv.ParseInt(numStr, 0, 64); err != nil {
+		return "", fmt.Errorf("invalid number %q at position %d", numStr, s.pos)
+	}
+	return numStr, nil
+}
+
+func (s *scanner) nextString() (string, error) {
+	const (
+		stBegin        = "stBegin"
+		stQuotedString = "stQuotedString"
+		stEscape       = "stEscape"
+	)
+	var buf bytes.Buffer
+	var quote rune
+	var incomplete bool
+	st := stBegin
+
+parseLoop:
+	for r := s.peek(); r != EOF; r = s.peek() {
+		switch st {
+		case stBegin:
+			switch {
+			case r == '"' || r == '`':
+				incomplete = true
+				quote = s.next() // consume quote
+				st = stQuotedString
+			default:
+				return "", fmt.Errorf("expected string at position %d", s.pos)
+			}
+		case stQuotedString:
+			switch {
+			case r == '\\':
+				s.next() // consume escape
+				st = stEscape
+			case r == quote:
+				incomplete = false
+				s.next()
+				break parseLoop
+			default:
+				buf.WriteRune(s.next())
+			}
+		case stEscape:
+			switch {
+			case r == quote || r == '\\':
+				buf.WriteRune(s.next())
+				st = stQuotedString
+			default:
+				return "", fmt.Errorf("unhandled escaped character %q", r)
+			}
+		default:
+			return "", fmt.Errorf("unexpected internal parser error: unknown state: %s at position %d", st, s.pos)
+		}
+	}
+	if incomplete {
+		return "", fmt.Errorf("unterminated string at position %d", s.pos)
+	}
+	return buf.String(), nil
+}
+
+func (s *scanner) nextIdent(isInteriorChar func(r rune) bool) (string, error) {
+	const (
+		stBegin    = "stBegin"
+		stInterior = "stInterior"
+	)
+	var buf bytes.Buffer
+	st := stBegin
+
+parseLoop:
+	for r := s.peek(); r != EOF; r = s.peek() {
+		switch st {
+		case stBegin:
+			switch {
+			case isIdentBegin(r):
+				buf.WriteRune(s.next())
+				st = stInterior
+			default:
+				return "", fmt.Errorf("expected identifier at position %d", s.pos)
+			}
+		case stInterior:
+			switch {
+			case isInteriorChar(r):
+				buf.WriteRune(s.next())
+			default:
+				break parseLoop
+			}
+		default:
+			return "", fmt.Errorf("unexpected internal parser error: unknown state: %s at position %d", st, s.pos)
+		}
+	}
+	return buf.String(), nil
+}
diff --git a/vendor/k8s.io/gengo/v2/codetags/types.go b/vendor/k8s.io/gengo/v2/codetags/types.go
new file mode 100644
index 000000000..d004f9bf2
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/codetags/types.go
@@ -0,0 +1,169 @@
+/*
+Copyright 2025 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package codetags
+
+import (
+	"strconv"
+	"strings"
+)
+
+// Tag represents a single comment tag with typed args.
+type Tag struct {
+	// Name is the name of the tag with no arguments.
+	Name string
+
+	// Args is a list of optional arguments to the tag.
+	Args []Arg
+
+	// Value is the string representation of the tag value.
+	// Provides the tag value when ValueType is ValueTypeString, ValueTypeBool, ValueTypeInt or ValueTypeRaw.
+	Value string
+
+	// ValueTag is another tag parsed from the value of this tag.
+	// Provides the tag value when ValueType is ValueTypeTag.
+	ValueTag *Tag
+
+	// ValueType is the type of the value.
+	ValueType ValueType
+}
+
+// PositionalArg returns the positional argument. If there is no positional
+// argument, it returns false.
+func (t Tag) PositionalArg() (Arg, bool) {
+	if len(t.Args) == 0 || len(t.Args[0].Name) > 0 {
+		return Arg{}, false
+	}
+	return t.Args[0], true
+}
+
+// NamedArg returns the named argument. If o named argument is found, it returns
+// false. Always returns false for empty name; use PositionalArg instead.
+func (t Tag) NamedArg(name string) (Arg, bool) {
+	if len(name) == 0 {
+		return Arg{}, false
+	}
+	for _, arg := range t.Args {
+		if arg.Name == name {
+			return arg, true
+		}
+	}
+	return Arg{}, false
+}
+
+// String returns the canonical string representation of the tag.
+// All strings are represented in double quotes. Spacing is normalized.
+func (t Tag) String() string {
+	buf := strings.Builder{}
+	buf.WriteString(t.Name)
+	if len(t.Args) > 0 {
+		buf.WriteString("(")
+		for i, a := range t.Args {
+			if i > 0 {
+				buf.WriteString(", ")
+			}
+			buf.WriteString(a.String())
+		}
+		buf.WriteString(")")
+	}
+	if t.ValueType != ValueTypeNone {
+		if t.ValueType == ValueTypeTag {
+			buf.WriteString("=+")
+			buf.WriteString(t.ValueTag.String())
+		} else {
+			buf.WriteString("=")
+			if t.ValueType == ValueTypeString {
+				buf.WriteString(strconv.Quote(t.Value))
+			} else {
+				buf.WriteString(t.Value)
+			}
+		}
+	}
+	return buf.String()
+}
+
+// Arg represents a argument.
+type Arg struct {
+	// Name is the name of a named argument. This is zero-valued for positional arguments.
+	Name string
+
+	// Value is the string value of an argument. It has been validated to match the Type.
+	// See the ArgType const godoc for further details on how to parse the value for the
+	// Type.
+	Value string
+
+	// Type identifies the type of the argument.
+	Type ArgType
+}
+
+func (a Arg) String() string {
+	buf := strings.Builder{}
+	if len(a.Name) > 0 {
+		buf.WriteString(a.Name)
+		buf.WriteString(": ")
+	}
+	if a.Type == ArgTypeString {
+		buf.WriteString(strconv.Quote(a.Value))
+	} else {
+		buf.WriteString(a.Value)
+	}
+	return buf.String()
+}
+
+// ArgType is an argument's type.
+type ArgType string
+
+const (
+	// ArgTypeString identifies string values.
+	ArgTypeString ArgType = "string"
+
+	// ArgTypeInt identifies int values. Values of this type may be in decimal,
+	// octal, hex or binary string representations. Consider using strconv.ParseInt
+	// to parse, as it supports all these string representations.
+	ArgTypeInt ArgType = "int"
+
+	// ArgTypeBool identifies bool values. Values of this type must either be the
+	// string "true" or "false".
+	ArgTypeBool ArgType = "bool"
+)
+
+// ValueType is a tag's value type.
+type ValueType string
+
+const (
+	// ValueTypeNone indicates that the tag has no value.
+	ValueTypeNone ValueType = ""
+
+	// ValueTypeString identifies string values.
+	ValueTypeString ValueType = "string"
+
+	// ValueTypeInt identifies int values. Values of this type may be in decimal,
+	// octal, hex or binary string representations. Consider using strconv.ParseInt
+	// to parse, as it supports all these string representations.
+	ValueTypeInt ValueType = "int"
+
+	// ValueTypeBool identifies bool values. Values of this type must either be the
+	// string "true" or "false".
+	ValueTypeBool ValueType = "bool"
+
+	// ValueTypeTag identifies that the value is another tag.
+	ValueTypeTag ValueType = "tag"
+
+	// ValueTypeRaw identifies that the value is raw, untyped content and contains
+	// all text from the tag declaration following the "=" sign, up to the last
+	// non-whitespace character.
+	ValueTypeRaw ValueType = "raw"
+)
diff --git a/vendor/k8s.io/gengo/v2/comments.go b/vendor/k8s.io/gengo/v2/comments.go
new file mode 100644
index 000000000..fbc41bed5
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/comments.go
@@ -0,0 +1,194 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package gengo
+
+import (
+	"bytes"
+	"fmt"
+	"slices"
+	"strings"
+
+	"k8s.io/gengo/v2/codetags"
+)
+
+// ExtractCommentTags parses comments for lines of the form:
+//
+//	'marker' + "key=value".
+//
+// Values are optional; "" is the default.  A tag can be specified more than
+// one time and all values are returned.  If the resulting map has an entry for
+// a key, the value (a slice) is guaranteed to have at least 1 element.
+//
+// Example: if you pass "+" for 'marker', and the following lines are in
+// the comments:
+//
+//	+foo=value1
+//	+bar
+//	+foo=value2
+//	+baz="qux"
+//
+// Then this function will return:
+//
+//	map[string][]string{"foo":{"value1, "value2"}, "bar": {""}, "baz": {`"qux"`}}
+//
+// Deprecated: Prefer codetags.Extract and codetags.Parse.
+func ExtractCommentTags(marker string, lines []string) map[string][]string {
+	out := map[string][]string{}
+	for _, line := range lines {
+		line = strings.Trim(line, " ")
+		if len(line) == 0 {
+			continue
+		}
+		if !strings.HasPrefix(line, marker) {
+			continue
+		}
+		kv := strings.SplitN(line[len(marker):], "=", 2)
+		if len(kv) == 2 {
+			out[kv[0]] = append(out[kv[0]], kv[1])
+		} else if len(kv) == 1 {
+			out[kv[0]] = append(out[kv[0]], "")
+		}
+	}
+	return out
+}
+
+// ExtractSingleBoolCommentTag parses comments for lines of the form:
+//
+//	'marker' + "key=value1"
+//
+// If the tag is not found, the default value is returned.  Values are asserted
+// to be boolean ("true" or "false"), and any other value will cause an error
+// to be returned.  If the key has multiple values, the first one will be used.
+//
+// This function is a wrapper around codetags.Extract and codetags.Parse, but only supports tags with
+// a single position arg of type string, and a value of type bool.
+func ExtractSingleBoolCommentTag(marker string, key string, defaultVal bool, lines []string) (bool, error) {
+	tags, err := ExtractFunctionStyleCommentTags(marker, []string{key}, lines, ParseValues(true))
+	if err != nil {
+		return false, err
+	}
+	values := tags[key]
+	if values == nil {
+		return defaultVal, nil
+	}
+	if values[0].Value == "true" {
+		return true, nil
+	}
+	if values[0].Value == "false" {
+		return false, nil
+	}
+	return false, fmt.Errorf("tag value for %q is not boolean: %q", key, values[0])
+}
+
+// ExtractFunctionStyleCommentTags parses comments for special metadata tags.
+//
+// This function is a wrapper around codetags.Extract and codetags.Parse, but only supports tags with
+// a single position arg of type string.
+func ExtractFunctionStyleCommentTags(marker string, tagNames []string, lines []string, options ...TagOption) (map[string][]Tag, error) {
+	opts := tagOpts{}
+	for _, o := range options {
+		o(&opts)
+	}
+
+	out := map[string][]Tag{}
+
+	tags := codetags.Extract(marker, lines)
+	for tagName, tagLines := range tags {
+		if len(tagNames) > 0 && !slices.Contains(tagNames, tagName) {
+			continue
+		}
+		for _, line := range tagLines {
+			typedTag, err := codetags.Parse(line, codetags.RawValues(!opts.parseValues))
+			if err != nil {
+				return nil, err
+			}
+			tag, err := toStringArgs(typedTag)
+			if err != nil {
+				return nil, err
+			}
+			out[tagName] = append(out[tagName], tag)
+		}
+	}
+
+	return out, nil
+}
+
+// TagOption provides an option for extracting tags.
+type TagOption func(opts *tagOpts)
+
+// ParseValues enables parsing of tag values. When enabled, tag values must
+// be valid quoted strings, ints, booleans, identifiers, or tags. Otherwise, a
+// parse error will be returned. Also, when enabled, trailing comments are
+// ignored.
+// Default: disabled
+func ParseValues(enabled bool) TagOption {
+	return func(opts *tagOpts) {
+		opts.parseValues = enabled
+	}
+}
+
+type tagOpts struct {
+	parseValues bool
+}
+
+func toStringArgs(tag codetags.Tag) (Tag, error) {
+	var stringArgs []string
+	if len(tag.Args) > 1 {
+		return Tag{}, fmt.Errorf("expected one argument, got: %v", tag.Args)
+	}
+	for _, arg := range tag.Args {
+		if len(arg.Name) > 0 {
+			return Tag{}, fmt.Errorf("unexpected named argument: %q", arg.Name)
+		}
+		if arg.Type != codetags.ArgTypeString {
+			return Tag{}, fmt.Errorf("unexpected argument type: %s", arg.Type)
+		} else {
+			stringArgs = append(stringArgs, arg.Value)
+		}
+	}
+	return Tag{
+		Name:  tag.Name,
+		Args:  stringArgs,
+		Value: tag.Value,
+	}, nil
+}
+
+// Tag represents a single comment tag.
+type Tag struct {
+	// Name is the name of the tag with no arguments.
+	Name string
+	// Args is a list of optional arguments to the tag.
+	Args []string
+	// Value is the value of the tag.
+	Value string
+}
+
+func (t Tag) String() string {
+	buf := bytes.Buffer{}
+	buf.WriteString(t.Name)
+	if len(t.Args) > 0 {
+		buf.WriteString("(")
+		for i, a := range t.Args {
+			if i > 0 {
+				buf.WriteString(", ")
+			}
+			buf.WriteString(a)
+		}
+		buf.WriteString(")")
+	}
+	return buf.String()
+}
diff --git a/vendor/k8s.io/gengo/v2/execute.go b/vendor/k8s.io/gengo/v2/execute.go
new file mode 100644
index 000000000..c4aba2b11
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/execute.go
@@ -0,0 +1,98 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package gengo is a code-generation framework.
+package gengo
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"time"
+
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/parser"
+)
+
+// StdBuildTag is a suggested build-tag which tools can use both as an argument
+// to GoBoilerplate and to Execute.
+const StdBuildTag = "ignore_autogenerated"
+
+// StdGeneratedBy is a suggested "generated by" line which tools can use as an
+// argument to GoBoilerplate.
+const StdGeneratedBy = "// Code generated by GENERATOR_NAME. DO NOT EDIT."
+
+// GoBoilerplate returns the Go file header:
+// - an optional build tag (negative, set it to ignore generated code)
+// - an optional boilerplate file
+// - an optional "generated by" comment
+func GoBoilerplate(headerFile, buildTag, generatedBy string) ([]byte, error) {
+	buf := bytes.Buffer{}
+
+	if buildTag != "" {
+		buf.WriteString(
+			fmt.Sprintf("//go:build !%s\n// +build !%s\n\n", buildTag, buildTag))
+	}
+
+	if headerFile != "" {
+		b, err := os.ReadFile(headerFile)
+		if err != nil {
+			return nil, err
+		}
+		b = bytes.ReplaceAll(b, []byte("YEAR"), []byte(strconv.Itoa(time.Now().UTC().Year())))
+		buf.Write(b)
+		buf.WriteByte('\n')
+	}
+
+	if generatedBy != "" {
+		generatorName := filepath.Base(os.Args[0])
+		// Strip the extension from the name to normalize output between *nix and Windows.
+		generatorName = generatorName[:len(generatorName)-len(filepath.Ext(generatorName))]
+		generatedByComment := strings.ReplaceAll(generatedBy, "GENERATOR_NAME", generatorName)
+		buf.WriteString(fmt.Sprintf("%s\n\n", generatedByComment))
+	}
+
+	return buf.Bytes(), nil
+}
+
+// Execute implements most of a tool's main loop.
+func Execute(nameSystems namer.NameSystems, defaultSystem string, getTargets func(*generator.Context) []generator.Target, buildTag string, patterns []string) error {
+	var buildTags []string
+	if buildTag != "" {
+		buildTags = append(buildTags, buildTag)
+	}
+
+	p := parser.NewWithOptions(parser.Options{BuildTags: buildTags})
+	if err := p.LoadPackages(patterns...); err != nil {
+		return fmt.Errorf("failed making a parser: %v", err)
+	}
+
+	c, err := generator.NewContext(p, nameSystems, defaultSystem)
+	if err != nil {
+		return fmt.Errorf("failed making a context: %v", err)
+	}
+
+	targets := getTargets(c)
+	if err := c.ExecuteTargets(targets); err != nil {
+		return fmt.Errorf("failed executing generator: %v", err)
+	}
+
+	return nil
+}
diff --git a/vendor/k8s.io/gengo/v2/generator/doc.go b/vendor/k8s.io/gengo/v2/generator/doc.go
new file mode 100644
index 000000000..ef0031cd6
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/doc.go
@@ -0,0 +1,31 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package generator defines an interface for code generators to implement.
+//
+// To use this package, you'll implement the "Package" and "Generator"
+// interfaces; you'll call NewContext to load up the types you want to work
+// with, and then you'll call one or more of the Execute methods. See the
+// interface definitions for explanations. All output will have gofmt called on
+// it automatically, so you do not need to worry about generating correct
+// indentation.
+//
+// This package also exposes SnippetWriter. SnippetWriter reduces to a minimum
+// the boilerplate involved in setting up a template from go's text/template
+// package. Additionally, all naming systems in the Context will be added as
+// functions to the parsed template, so that they can be called directly from
+// your templates!
+package generator // import "k8s.io/gengo/v2/generator"
diff --git a/vendor/k8s.io/gengo/v2/generator/error_tracker.go b/vendor/k8s.io/gengo/v2/generator/error_tracker.go
new file mode 100644
index 000000000..964dae37b
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/error_tracker.go
@@ -0,0 +1,50 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"io"
+)
+
+// ErrorTracker tracks errors to the underlying writer, so that you can ignore
+// them until you're ready to return.
+type ErrorTracker struct {
+	io.Writer
+	err error
+}
+
+// NewErrorTracker makes a new error tracker; note that it implements io.Writer.
+func NewErrorTracker(w io.Writer) *ErrorTracker {
+	return &ErrorTracker{Writer: w}
+}
+
+// Write intercepts calls to Write.
+func (et *ErrorTracker) Write(p []byte) (n int, err error) {
+	if et.err != nil {
+		return 0, et.err
+	}
+	n, err = et.Writer.Write(p)
+	if err != nil {
+		et.err = err
+	}
+	return n, err
+}
+
+// Error returns nil if no error has occurred, otherwise it returns the error.
+func (et *ErrorTracker) Error() error {
+	return et.err
+}
diff --git a/vendor/k8s.io/gengo/v2/generator/execute.go b/vendor/k8s.io/gengo/v2/generator/execute.go
new file mode 100644
index 000000000..a1e052f5c
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/execute.go
@@ -0,0 +1,273 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"strings"
+
+	"golang.org/x/tools/imports"
+
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+)
+
+// ExecuteTargets runs the generators for the provided targets.
+func (c *Context) ExecuteTargets(targets []Target) error {
+	klog.V(5).Infof("ExecuteTargets: %d targets", len(targets))
+
+	var errs []error
+	for _, tgt := range targets {
+		if err := c.ExecuteTarget(tgt); err != nil {
+			errs = append(errs, err)
+		}
+	}
+	if len(errs) > 0 {
+		return fmt.Errorf("some targets had errors: %w", errors.Join(errs...))
+	}
+	return nil
+}
+
+type DefaultFileType struct {
+	Format   func([]byte) ([]byte, error)
+	Assemble func(io.Writer, *File)
+}
+
+func (ft DefaultFileType) AssembleFile(f *File, pathname string) error {
+	klog.V(5).Infof("Assembling file %q", pathname)
+
+	destFile, err := os.Create(pathname)
+	if err != nil {
+		return err
+	}
+	defer destFile.Close()
+
+	b := &bytes.Buffer{}
+	et := NewErrorTracker(b)
+	ft.Assemble(et, f)
+	if et.Error() != nil {
+		return et.Error()
+	}
+	if formatted, err := ft.Format(b.Bytes()); err != nil {
+		err = fmt.Errorf("unable to format file %q (%v)", pathname, err)
+		// Write the file anyway, so they can see what's going wrong and fix the generator.
+		if _, err2 := destFile.Write(b.Bytes()); err2 != nil {
+			return err2
+		}
+		return err
+	} else {
+		_, err = destFile.Write(formatted)
+		return err
+	}
+}
+
+func assembleGoFile(w io.Writer, f *File) {
+	w.Write(f.Header)
+	fmt.Fprintf(w, "package %v\n\n", f.PackageName)
+
+	if len(f.Imports) > 0 {
+		fmt.Fprint(w, "import (\n")
+		for i := range f.Imports {
+			if strings.Contains(i, "\"") {
+				// they included quotes, or are using the
+				// `name "path/to/pkg"` format.
+				fmt.Fprintf(w, "\t%s\n", i)
+			} else {
+				fmt.Fprintf(w, "\t%q\n", i)
+			}
+		}
+		fmt.Fprint(w, ")\n\n")
+	}
+
+	if f.Vars.Len() > 0 {
+		fmt.Fprint(w, "var (\n")
+		w.Write(f.Vars.Bytes())
+		fmt.Fprint(w, ")\n\n")
+	}
+
+	if f.Consts.Len() > 0 {
+		fmt.Fprint(w, "const (\n")
+		w.Write(f.Consts.Bytes())
+		fmt.Fprint(w, ")\n\n")
+	}
+
+	w.Write(f.Body.Bytes())
+}
+
+func importsWrapper(src []byte) ([]byte, error) {
+	opt := imports.Options{
+		Comments:   true,
+		TabIndent:  true,
+		TabWidth:   8,
+		FormatOnly: true, // Disable the insertion and deletion of imports
+	}
+	return imports.Process("", src, &opt)
+}
+
+func NewGoFile() *DefaultFileType {
+	return &DefaultFileType{
+		Format:   importsWrapper,
+		Assemble: assembleGoFile,
+	}
+}
+
+// format should be one line only, and not end with \n.
+func addIndentHeaderComment(b *bytes.Buffer, format string, args ...interface{}) {
+	if b.Len() > 0 {
+		fmt.Fprintf(b, "\n// "+format+"\n", args...)
+	} else {
+		fmt.Fprintf(b, "// "+format+"\n", args...)
+	}
+}
+
+func (c *Context) filteredBy(f func(*Context, *types.Type) bool) *Context {
+	c2 := *c
+	c2.Order = []*types.Type{}
+	for _, t := range c.Order {
+		if f(c, t) {
+			c2.Order = append(c2.Order, t)
+		}
+	}
+	return &c2
+}
+
+// make a new context; inheret c.Namers, but add on 'namers'. In case of a name
+// collision, the namer in 'namers' wins.
+func (c *Context) addNameSystems(namers namer.NameSystems) *Context {
+	if namers == nil {
+		return c
+	}
+	c2 := *c
+	// Copy the existing name systems so we don't corrupt a parent context
+	c2.Namers = namer.NameSystems{}
+	for k, v := range c.Namers {
+		c2.Namers[k] = v
+	}
+
+	for name, namer := range namers {
+		c2.Namers[name] = namer
+	}
+	return &c2
+}
+
+// ExecuteTarget runs the generators for a single target.
+func (c *Context) ExecuteTarget(tgt Target) error {
+	tgtDir := tgt.Dir()
+	if tgtDir == "" {
+		return fmt.Errorf("no directory for target %s", tgt.Path())
+	}
+	klog.V(5).Infof("Executing target %q (%q)", tgt.Name(), tgtDir)
+
+	// Filter out any types the *package* doesn't care about.
+	packageContext := c.filteredBy(tgt.Filter)
+
+	if err := os.MkdirAll(tgtDir, 0755); err != nil {
+		return err
+	}
+
+	files := map[string]*File{}
+	for _, g := range tgt.Generators(packageContext) {
+		// Filter out types the *generator* doesn't care about.
+		genContext := packageContext.filteredBy(g.Filter)
+		// Now add any extra name systems defined by this generator
+		genContext = genContext.addNameSystems(g.Namers(genContext))
+
+		fileType := g.FileType()
+		if len(fileType) == 0 {
+			return fmt.Errorf("generator %q must specify a file type", g.Name())
+		}
+		f := files[g.Filename()]
+		if f == nil {
+			// This is the first generator to reference this file, so start it.
+			f = &File{
+				Name:        g.Filename(),
+				FileType:    fileType,
+				PackageName: tgt.Name(),
+				PackagePath: tgt.Path(),
+				PackageDir:  tgt.Dir(),
+				Header:      tgt.Header(g.Filename()),
+				Imports:     map[string]struct{}{},
+			}
+			files[f.Name] = f
+		} else if f.FileType != g.FileType() {
+			return fmt.Errorf("file %q already has type %q, but generator %q wants to use type %q", f.Name, f.FileType, g.Name(), g.FileType())
+		}
+
+		if vars := g.PackageVars(genContext); len(vars) > 0 {
+			addIndentHeaderComment(&f.Vars, "Package-wide variables from generator %q.", g.Name())
+			for _, v := range vars {
+				if _, err := fmt.Fprintf(&f.Vars, "%s\n", v); err != nil {
+					return err
+				}
+			}
+		}
+		if consts := g.PackageConsts(genContext); len(consts) > 0 {
+			addIndentHeaderComment(&f.Consts, "Package-wide consts from generator %q.", g.Name())
+			for _, v := range consts {
+				if _, err := fmt.Fprintf(&f.Consts, "%s\n", v); err != nil {
+					return err
+				}
+			}
+		}
+		if err := genContext.executeBody(&f.Body, g); err != nil {
+			return err
+		}
+		if imports := g.Imports(genContext); len(imports) > 0 {
+			for _, i := range imports {
+				f.Imports[i] = struct{}{}
+			}
+		}
+	}
+
+	var errs []error
+	for _, f := range files {
+		finalPath := filepath.Join(tgtDir, f.Name)
+		assembler, ok := c.FileTypes[f.FileType]
+		if !ok {
+			return fmt.Errorf("the file type %q registered for file %q does not exist in the context", f.FileType, f.Name)
+		}
+		if err := assembler.AssembleFile(f, finalPath); err != nil {
+			errs = append(errs, err)
+		}
+	}
+	if len(errs) > 0 {
+		return fmt.Errorf("errors in target %q: %w", tgt.Path(), errors.Join(errs...))
+	}
+	return nil
+}
+
+func (c *Context) executeBody(w io.Writer, generator Generator) error {
+	et := NewErrorTracker(w)
+	if err := generator.Init(c, et); err != nil {
+		return err
+	}
+	for _, t := range c.Order {
+		if err := generator.GenerateType(c, t, et); err != nil {
+			return err
+		}
+	}
+	if err := generator.Finalize(c, et); err != nil {
+		return err
+	}
+	return et.Error()
+}
diff --git a/vendor/k8s.io/gengo/v2/generator/generator.go b/vendor/k8s.io/gengo/v2/generator/generator.go
new file mode 100644
index 000000000..7dfb1b2be
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/generator.go
@@ -0,0 +1,214 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"bytes"
+	"io"
+
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/parser"
+	"k8s.io/gengo/v2/types"
+)
+
+// Target describes a Go package into which code will be generated.  A single
+// Target may have many Generators, each of which emits one file.
+type Target interface {
+	// Name returns the package short name (as in `package foo`).
+	Name() string
+	// Path returns the package import path (as in `import "example.com/foo"`).
+	Path() string
+	// Dir returns the location of the resulting package on disk.  This may be
+	// the same directory as an input package (when generating code in-place)
+	// or a different directory entirely.
+	Dir() string
+
+	// Filter should return true if this package cares about this type.
+	// Otherwise, this type will be omitted from the type ordering for
+	// this package.
+	Filter(*Context, *types.Type) bool
+
+	// Header should return a header for the file, including comment markers.
+	// Useful for copyright notices and doc strings. Include an
+	// autogeneration notice! Do not include the "package x" line.
+	Header(filename string) []byte
+
+	// Generators returns the list of generators for this package. It is
+	// allowed for more than one generator to write to the same file.
+	// A Context is passed in case the list of generators depends on the
+	// input types.
+	Generators(*Context) []Generator
+}
+
+type File struct {
+	Name        string
+	FileType    string
+	PackageName string
+	Header      []byte
+	PackagePath string
+	PackageDir  string
+	Imports     map[string]struct{}
+	Vars        bytes.Buffer
+	Consts      bytes.Buffer
+	Body        bytes.Buffer
+}
+
+type FileType interface {
+	AssembleFile(f *File, path string) error
+}
+
+// Generator is the contract for anything that wants to do auto-generation.
+// It's expected that the io.Writers passed to the below functions will be
+// ErrorTrackers; this allows implementations to not check for io errors,
+// making more readable code.
+//
+// The call order for the functions that take a Context is:
+// 1. Filter()        // Subsequent calls see only types that pass this.
+// 2. Namers()        // Subsequent calls see the namers provided by this.
+// 3. PackageVars()
+// 4. PackageConsts()
+// 5. Init()
+// 6. GenerateType()  // Called N times, once per type in the context's Order.
+// 7. Imports()
+//
+// You may have multiple generators for the same file.
+type Generator interface {
+	// The name of this generator. Will be included in generated comments.
+	Name() string
+
+	// Filter should return true if this generator cares about this type.
+	// (otherwise, GenerateType will not be called.)
+	//
+	// Filter is called before any of the generator's other functions;
+	// subsequent calls will get a context with only the types that passed
+	// this filter.
+	Filter(*Context, *types.Type) bool
+
+	// If this generator needs special namers, return them here. These will
+	// override the original namers in the context if there is a collision.
+	// You may return nil if you don't need special names. These names will
+	// be available in the context passed to the rest of the generator's
+	// functions.
+	//
+	// A use case for this is to return a namer that tracks imports.
+	Namers(*Context) namer.NameSystems
+
+	// Init should write an init function, and any other content that's not
+	// generated per-type. (It's not intended for generator specific
+	// initialization! Do that when your Target constructs the
+	// Generators.)
+	Init(*Context, io.Writer) error
+
+	// Finalize should write finish up functions, and any other content that's not
+	// generated per-type.
+	Finalize(*Context, io.Writer) error
+
+	// PackageVars should emit an array of variable lines. They will be
+	// placed in a var ( ... ) block. There's no need to include a leading
+	// \t or trailing \n.
+	PackageVars(*Context) []string
+
+	// PackageConsts should emit an array of constant lines. They will be
+	// placed in a const ( ... ) block. There's no need to include a leading
+	// \t or trailing \n.
+	PackageConsts(*Context) []string
+
+	// GenerateType should emit the code for a particular type.
+	GenerateType(*Context, *types.Type, io.Writer) error
+
+	// Imports should return a list of necessary imports. They will be
+	// formatted correctly. You do not need to include quotation marks,
+	// return only the package name; alternatively, you can also return
+	// imports in the format `name "path/to/pkg"`. Imports will be called
+	// after Init, PackageVars, PackageConsts, and GenerateType, to allow
+	// you to keep track of what imports you actually need.
+	Imports(*Context) []string
+
+	// Preferred file name of this generator, not including a path. It is
+	// allowed for multiple generators to use the same filename, but it's
+	// up to you to make sure they don't have colliding import names.
+	// TODO: provide per-file import tracking, removing the requirement
+	// that generators coordinate..
+	Filename() string
+
+	// A registered file type in the context to generate this file with. If
+	// the FileType is not found in the context, execution will stop.
+	FileType() string
+}
+
+// Context is global context for individual generators to consume.
+type Context struct {
+	// A map from the naming system to the names for that system. E.g., you
+	// might have public names and several private naming systems.
+	Namers namer.NameSystems
+
+	// All the types, in case you want to look up something.
+	Universe types.Universe
+
+	// All the user-specified packages.  This is after recursive expansion.
+	Inputs []string
+
+	// The canonical ordering of the types (will be filtered by both the
+	// Target's and Generator's Filter methods).
+	Order []*types.Type
+
+	// A set of types this context can process. If this is empty or nil,
+	// the default "go" filetype will be provided.
+	FileTypes map[string]FileType
+
+	// Allows generators to add packages at runtime.
+	parser *parser.Parser
+}
+
+// NewContext generates a context from the given parser, naming systems, and
+// the naming system you wish to construct the canonical ordering from.
+func NewContext(p *parser.Parser, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) {
+	universe, err := p.NewUniverse()
+	if err != nil {
+		return nil, err
+	}
+
+	c := &Context{
+		Namers:   namer.NameSystems{},
+		Universe: universe,
+		Inputs:   p.UserRequestedPackages(),
+		FileTypes: map[string]FileType{
+			GoFileType: NewGoFile(),
+		},
+		parser: p,
+	}
+
+	for name, systemNamer := range nameSystems {
+		c.Namers[name] = systemNamer
+		if name == canonicalOrderName {
+			orderer := namer.Orderer{Namer: systemNamer}
+			c.Order = orderer.OrderUniverse(universe)
+		}
+	}
+	return c, nil
+}
+
+// LoadPackages adds Go packages to the context.
+func (c *Context) LoadPackages(patterns ...string) ([]*types.Package, error) {
+	return c.parser.LoadPackagesTo(&c.Universe, patterns...)
+}
+
+// FindPackages expands Go package patterns into a list of package import
+// paths, akin to `go list -find`.
+func (c *Context) FindPackages(patterns ...string) ([]string, error) {
+	return c.parser.FindPackages(patterns...)
+}
diff --git a/vendor/k8s.io/gengo/v2/generator/go_generator.go b/vendor/k8s.io/gengo/v2/generator/go_generator.go
new file mode 100644
index 000000000..14d2148b9
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/go_generator.go
@@ -0,0 +1,61 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"io"
+
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+)
+
+const (
+	GoFileType = "go"
+)
+
+// GoGenerator implements a do-nothing Generator for Go files.  It can be
+// used as a base for custom Generators, which embed it and then define the
+// methods they need to specialize.
+type GoGenerator struct {
+	// OutputFilename is used as the Generator's name, and filename.
+	OutputFilename string
+
+	// Body, if present, will be used as the return from the "Init" method.
+	// This causes it to be static content for the entire file if no other
+	// generator touches the file.
+	OptionalBody []byte
+}
+
+func (gg GoGenerator) Name() string                                        { return gg.OutputFilename }
+func (gg GoGenerator) Filter(*Context, *types.Type) bool                   { return true }
+func (gg GoGenerator) Namers(*Context) namer.NameSystems                   { return nil }
+func (gg GoGenerator) Imports(*Context) []string                           { return []string{} }
+func (gg GoGenerator) PackageVars(*Context) []string                       { return []string{} }
+func (gg GoGenerator) PackageConsts(*Context) []string                     { return []string{} }
+func (gg GoGenerator) GenerateType(*Context, *types.Type, io.Writer) error { return nil }
+func (gg GoGenerator) Filename() string                                    { return gg.OutputFilename }
+func (gg GoGenerator) FileType() string                                    { return GoFileType }
+func (gg GoGenerator) Finalize(*Context, io.Writer) error                  { return nil }
+
+func (gg GoGenerator) Init(c *Context, w io.Writer) error {
+	_, err := w.Write(gg.OptionalBody)
+	return err
+}
+
+var (
+	_ = Generator(GoGenerator{})
+)
diff --git a/vendor/k8s.io/gengo/v2/generator/import_tracker.go b/vendor/k8s.io/gengo/v2/generator/import_tracker.go
new file mode 100644
index 000000000..22393e4d4
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/import_tracker.go
@@ -0,0 +1,96 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"go/token"
+	"path/filepath"
+	"strings"
+
+	"k8s.io/klog/v2"
+
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+)
+
+// NewImportTrackerForPackage creates a new import tracker which is aware
+// of a generator's output package. The tracker will not add import lines
+// when symbols or types are added from the same package, and LocalNameOf
+// will return empty string for the output package.
+//
+// e.g.:
+//
+//	tracker := NewImportTrackerForPackage("bar.com/pkg/foo")
+//	tracker.AddSymbol(types.Name{"bar.com/pkg/foo.MyType"})
+//	tracker.AddSymbol(types.Name{"bar.com/pkg/baz.MyType"})
+//	tracker.AddSymbol(types.Name{"bar.com/pkg/baz/baz.MyType"})
+//
+//	tracker.LocalNameOf("bar.com/pkg/foo") -> ""
+//	tracker.LocalNameOf("bar.com/pkg/baz") -> "baz"
+//	tracker.LocalNameOf("bar.com/pkg/baz/baz") -> "bazbaz"
+//	tracker.ImportLines() -> {`baz "bar.com/pkg/baz"`, `bazbaz "bar.com/pkg/baz/baz"`}
+func NewImportTrackerForPackage(local string, typesToAdd ...*types.Type) *namer.DefaultImportTracker {
+	tracker := namer.NewDefaultImportTracker(types.Name{Package: local})
+	tracker.IsInvalidType = func(*types.Type) bool { return false }
+	tracker.LocalName = func(name types.Name) string { return goTrackerLocalName(&tracker, local, name) }
+	tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
+
+	tracker.AddTypes(typesToAdd...)
+	return &tracker
+}
+
+func NewImportTracker(typesToAdd ...*types.Type) *namer.DefaultImportTracker {
+	return NewImportTrackerForPackage("", typesToAdd...)
+}
+
+func goTrackerLocalName(tracker namer.ImportTracker, localPkg string, t types.Name) string {
+	path := t.Package
+
+	// Using backslashes in package names causes gengo to produce Go code which
+	// will not compile with the gc compiler. See the comment on GoSeperator.
+	if strings.ContainsRune(path, '\\') {
+		klog.Warningf("Warning: backslash used in import path '%v', this is unsupported.\n", path)
+	}
+	localLeaf := filepath.Base(localPkg)
+
+	dirs := strings.Split(path, namer.GoSeperator)
+	for n := len(dirs) - 1; n >= 0; n-- {
+		// follow kube convention of not having anything between directory names
+		name := strings.Join(dirs[n:], "")
+		name = strings.ReplaceAll(name, "_", "")
+		// These characters commonly appear in import paths for go
+		// packages, but aren't legal go names. So we'll sanitize.
+		name = strings.ReplaceAll(name, ".", "")
+		name = strings.ReplaceAll(name, "-", "")
+		if _, found := tracker.PathOf(name); found || name == localLeaf {
+			// This name collides with some other package.
+			// Or, this name is tne same name as the local package,
+			// which we avoid because it can be confusing. For example,
+			// if the local package is v1, we to avoid importing
+			// another package using the v1 name, and instead import
+			// it with a more qualified name, such as metav1.
+			continue
+		}
+
+		// If the import name is a Go keyword, prefix with an underscore.
+		if token.Lookup(name).IsKeyword() {
+			name = "_" + name
+		}
+		return name
+	}
+	panic("can't find import for " + path)
+}
diff --git a/vendor/k8s.io/gengo/v2/generator/simple_target.go b/vendor/k8s.io/gengo/v2/generator/simple_target.go
new file mode 100644
index 000000000..34df8245d
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/simple_target.go
@@ -0,0 +1,77 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"k8s.io/gengo/v2/types"
+)
+
+// SimpleTarget is implements Target in terms of static configuration.
+// The package name, path, and dir are required to be non-empty.
+type SimpleTarget struct {
+	// PkgName is the name of the resulting package (as in "package xxxx").
+	// Required.
+	PkgName string
+	// PkgPath is the canonical Go import-path of the resulting package (as in
+	// "import example.com/xxxx/yyyy"). Required.
+	PkgPath string
+	// PkgDir is the location of the resulting package on disk (which may not
+	// exist yet). It may be absolute or relative to CWD. Required.
+	PkgDir string
+
+	// HeaderComment is emitted at the top of every output file. Optional.
+	HeaderComment []byte
+
+	// PkgDocComment is emitted after the header comment for a "doc.go" file.
+	// Optional.
+	PkgDocComment []byte
+
+	// FilterFunc will be called to implement Target.Filter. Optional.
+	FilterFunc func(*Context, *types.Type) bool
+
+	// GeneratorsFunc will be called to implement Target.Generators. Optional.
+	GeneratorsFunc func(*Context) []Generator
+}
+
+func (st SimpleTarget) Name() string { return st.PkgName }
+func (st SimpleTarget) Path() string { return st.PkgPath }
+func (st SimpleTarget) Dir() string  { return st.PkgDir }
+
+func (st SimpleTarget) Filter(c *Context, t *types.Type) bool {
+	if st.FilterFunc != nil {
+		return st.FilterFunc(c, t)
+	}
+	return true
+}
+
+func (st SimpleTarget) Generators(c *Context) []Generator {
+	if st.GeneratorsFunc != nil {
+		return st.GeneratorsFunc(c)
+	}
+	return nil
+}
+
+func (st SimpleTarget) Header(filename string) []byte {
+	if filename == "doc.go" {
+		return append(st.HeaderComment, st.PkgDocComment...)
+	}
+	return st.HeaderComment
+}
+
+var (
+	_ = Target(SimpleTarget{})
+)
diff --git a/vendor/k8s.io/gengo/v2/generator/snippet_writer.go b/vendor/k8s.io/gengo/v2/generator/snippet_writer.go
new file mode 100644
index 000000000..b0adcc28a
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/generator/snippet_writer.go
@@ -0,0 +1,188 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generator
+
+import (
+	"fmt"
+	"io"
+	"runtime"
+	"text/template"
+)
+
+// SnippetWriter is an attempt to make the template library usable.
+// Methods are chainable, and you don't have to check Error() until you're all
+// done.
+type SnippetWriter struct {
+	w       io.Writer
+	context *Context
+	// Left & right delimiters. text/template defaults to "{{" and "}}"
+	// which is totally unusable for go code based templates.
+	left, right string
+	funcMap     template.FuncMap
+	err         error
+}
+
+// w is the destination; left and right are the delimiters; @ and $ are both
+// reasonable choices.
+//
+// c is used to make a function for every naming system, to which you can pass
+// a type and get the corresponding name.
+func NewSnippetWriter(w io.Writer, c *Context, left, right string) *SnippetWriter {
+	sw := &SnippetWriter{
+		w:       w,
+		context: c,
+		left:    left,
+		right:   right,
+		funcMap: template.FuncMap{},
+	}
+	for name, namer := range c.Namers {
+		sw.funcMap[name] = namer.Name
+	}
+	return sw
+}
+
+// Do parses format and runs args through it. You can have arbitrary logic in
+// the format (see the text/template documentation), but consider running many
+// short templates with ordinary go logic in between--this may be more
+// readable. Do is chainable. Any error causes every other call to do to be
+// ignored, and the error will be returned by Error(). So you can check it just
+// once, at the end of your function.
+//
+// 'args' can be quite literally anything; read the text/template documentation
+// for details. Maps and structs work particularly nicely. Conveniently, the
+// types package is designed to have structs that are easily referencable from
+// the template language.
+//
+// Example:
+//
+// sw := generator.NewSnippetWriter(outBuffer, context, "$", "$")
+// sw.Do(`The public type name is: $.type|public$`, map[string]interface{}{"type": t})
+// return sw.Error()
+//
+// Where:
+//   - "$" starts a template directive
+//   - "." references the entire thing passed as args
+//   - "type" therefore sees a map and looks up the key "type"
+//   - "|" means "pass the thing on the left to the thing on the right"
+//   - "public" is the name of a naming system, so the SnippetWriter has given
+//     the template a function called "public" that takes a *types.Type and
+//     returns the naming system's name. E.g., if the type is "string" this might
+//     return "String".
+//   - the second "$" ends the template directive.
+//
+// The map is actually not necessary. The below does the same thing:
+//
+// sw.Do(`The public type name is: $.|public$`, t)
+//
+// You may or may not find it more readable to use the map with a descriptive
+// key, but if you want to pass more than one arg, the map or a custom struct
+// becomes a requirement. You can do arbitrary logic inside these templates,
+// but you should consider doing the logic in go and stitching them together
+// for the sake of your readers.
+//
+// TODO: Change Do() to optionally take a list of pairs of parameters (key, value)
+// and have it construct a combined map with that and args.
+func (s *SnippetWriter) Do(format string, args interface{}) *SnippetWriter {
+	if s.err != nil {
+		return s
+	}
+	// Name the template by source file:line so it can be found when
+	// there's an error.
+	_, file, line, _ := runtime.Caller(1)
+	tmpl, err := template.
+		New(fmt.Sprintf("%s:%d", file, line)).
+		Delims(s.left, s.right).
+		Funcs(s.funcMap).
+		Parse(format)
+	if err != nil {
+		s.err = err
+		return s
+	}
+	err = tmpl.Execute(s.w, args)
+	if err != nil {
+		s.err = err
+	}
+	return s
+}
+
+// Args exists to make it convenient to construct arguments for
+// SnippetWriter.Do.
+type Args map[interface{}]interface{}
+
+// With makes a copy of a and adds the given key, value pair. If key overlaps,
+// the new value wins.
+func (a Args) With(key, value interface{}) Args {
+	result := Args{}
+	for k, v := range a {
+		result[k] = v
+	}
+	result[key] = value
+	return result
+}
+
+// WithArgs makes a copy of a and adds the given arguments. If any keys
+// overlap, the values from rhs win.
+func (a Args) WithArgs(rhs Args) Args {
+	result := Args{}
+	for k, v := range a {
+		result[k] = v
+	}
+	for k, v := range rhs {
+		result[k] = v
+	}
+	return result
+}
+
+func (s *SnippetWriter) Out() io.Writer {
+	return s.w
+}
+
+// Error returns any encountered error.
+func (s *SnippetWriter) Error() error {
+	return s.err
+}
+
+// Dup creates an exact duplicate SnippetWriter with a different io.Writer.
+func (s *SnippetWriter) Dup(w io.Writer) *SnippetWriter {
+	ret := *s
+	ret.w = w
+	return &ret
+}
+
+// Append adds the contents of the io.Reader to this SnippetWriter's buffer.
+func (s *SnippetWriter) Append(r io.Reader) error {
+	// The behavior of Do() is to ignore all future calls if there's an error,
+	// assuming the top-level caller will check Error().  This method is
+	// effectively a fancy Do(), so keep the same semantic.
+	if s.err != nil {
+		return nil
+	}
+	_, err := io.Copy(s.w, r)
+	return err
+}
+
+// Merge adds the contents of the io.Reader to this SnippetWriter's buffer and
+// sets this SnippetWriter's error to the other's, if needed.
+func (s *SnippetWriter) Merge(r io.Reader, other *SnippetWriter) error {
+	if s.err != nil {
+		return nil
+	}
+	if other.err != nil {
+		s.err = other.err
+	}
+	return s.Append(r)
+}
diff --git a/vendor/k8s.io/gengo/v2/namer/doc.go b/vendor/k8s.io/gengo/v2/namer/doc.go
new file mode 100644
index 000000000..76309ebb0
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/namer/doc.go
@@ -0,0 +1,31 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package namer has support for making different type naming systems.
+//
+// This is because sometimes you want to refer to the literal type, sometimes
+// you want to make a name for the thing you're generating, and you want to
+// make the name based on the type. For example, if you have `type foo string`,
+// you want to be able to generate something like `func FooPrinter(f *foo) {
+// Print(string(*f)) }`; that is, you want to refer to a public name, a literal
+// name, and the underlying literal name.
+//
+// This package supports the idea of a "Namer" and a set of "NameSystems" to
+// support these use cases.
+//
+// Additionally, a "RawNamer" can optionally keep track of what needs to be
+// imported.
+package namer // import "k8s.io/gengo/v2/namer"
diff --git a/vendor/k8s.io/gengo/v2/namer/import_tracker.go b/vendor/k8s.io/gengo/v2/namer/import_tracker.go
new file mode 100644
index 000000000..f8c5a9411
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/namer/import_tracker.go
@@ -0,0 +1,121 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package namer
+
+import (
+	"sort"
+
+	"k8s.io/gengo/v2/types"
+)
+
+// ImportTracker may be passed to a namer.RawNamer, to track the imports needed
+// for the types it names.
+//
+// TODO: pay attention to the package name (instead of renaming every package).
+type DefaultImportTracker struct {
+	pathToName map[string]string
+	// forbidden names are in here. (e.g. "go" is a directory in which
+	// there is code, but "go" is not a legal name for a package, so we put
+	// it here to prevent us from naming any package "go")
+	nameToPath map[string]string
+	local      types.Name
+
+	// Returns true if a given types is an invalid type and should be ignored.
+	IsInvalidType func(*types.Type) bool
+	// Returns the final local name for the given name
+	LocalName func(types.Name) string
+	// Returns the "import" line for a given (path, name).
+	PrintImport func(string, string) string
+}
+
+func NewDefaultImportTracker(local types.Name) DefaultImportTracker {
+	return DefaultImportTracker{
+		pathToName: map[string]string{},
+		nameToPath: map[string]string{},
+		local:      local,
+	}
+}
+
+func (tracker *DefaultImportTracker) AddTypes(types ...*types.Type) {
+	for _, t := range types {
+		tracker.AddType(t)
+	}
+}
+func (tracker *DefaultImportTracker) AddSymbol(symbol types.Name) {
+	if tracker.local.Package == symbol.Package {
+		return
+	}
+
+	if len(symbol.Package) == 0 {
+		return
+	}
+	path := symbol.Path
+	if len(path) == 0 {
+		path = symbol.Package
+	}
+	if _, ok := tracker.pathToName[path]; ok {
+		return
+	}
+
+	name := tracker.LocalName(symbol)
+	tracker.nameToPath[name] = path
+	tracker.pathToName[path] = name
+}
+
+func (tracker *DefaultImportTracker) AddType(t *types.Type) {
+	if tracker.local.Package == t.Name.Package {
+		return
+	}
+
+	if tracker.IsInvalidType(t) {
+		if t.Kind == types.Builtin {
+			return
+		}
+		if _, ok := tracker.nameToPath[t.Name.Package]; !ok {
+			tracker.nameToPath[t.Name.Package] = ""
+		}
+		return
+	}
+
+	tracker.AddSymbol(t.Name)
+}
+
+func (tracker *DefaultImportTracker) ImportLines() []string {
+	importPaths := []string{}
+	for path := range tracker.pathToName {
+		importPaths = append(importPaths, path)
+	}
+	sort.Strings(importPaths)
+	out := []string{}
+	for _, path := range importPaths {
+		out = append(out, tracker.PrintImport(path, tracker.pathToName[path]))
+	}
+	return out
+}
+
+// LocalNameOf returns the name you would use to refer to the package at the
+// specified path within the body of a file.
+func (tracker *DefaultImportTracker) LocalNameOf(path string) string {
+	return tracker.pathToName[path]
+}
+
+// PathOf returns the path that a given localName is referring to within the
+// body of a file.
+func (tracker *DefaultImportTracker) PathOf(localName string) (string, bool) {
+	name, ok := tracker.nameToPath[localName]
+	return name, ok
+}
diff --git a/vendor/k8s.io/gengo/v2/namer/namer.go b/vendor/k8s.io/gengo/v2/namer/namer.go
new file mode 100644
index 000000000..bae2ee9b5
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/namer/namer.go
@@ -0,0 +1,399 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package namer
+
+import (
+	"fmt"
+	"path/filepath"
+	"strconv"
+	"strings"
+
+	"k8s.io/gengo/v2/types"
+)
+
+const (
+	// GoSeperator is used to split go import paths.
+	// Forward slash is used instead of filepath.Seperator because it is the
+	// only universally-accepted path delimiter and the only delimiter not
+	// potentially forbidden by Go compilers. (In particular gc does not allow
+	// the use of backslashes in import paths.)
+	// See https://golang.org/ref/spec#Import_declarations.
+	// See also https://github.com/kubernetes/gengo/issues/83#issuecomment-367040772.
+	GoSeperator = "/"
+)
+
+// Returns whether a name is a private Go name.
+func IsPrivateGoName(name string) bool {
+	return len(name) == 0 || strings.ToLower(name[:1]) == name[:1]
+}
+
+// NewPublicNamer is a helper function that returns a namer that makes
+// CamelCase names. See the NameStrategy struct for an explanation of the
+// arguments to this constructor.
+func NewPublicNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy {
+	n := &NameStrategy{
+		Join:                Joiner(IC, IC),
+		IgnoreWords:         map[string]bool{},
+		PrependPackageNames: prependPackageNames,
+	}
+	for _, w := range ignoreWords {
+		n.IgnoreWords[w] = true
+	}
+	return n
+}
+
+// NewPrivateNamer is a helper function that returns a namer that makes
+// camelCase names. See the NameStrategy struct for an explanation of the
+// arguments to this constructor.
+func NewPrivateNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy {
+	n := &NameStrategy{
+		Join:                Joiner(IL, IC),
+		IgnoreWords:         map[string]bool{},
+		PrependPackageNames: prependPackageNames,
+	}
+	for _, w := range ignoreWords {
+		n.IgnoreWords[w] = true
+	}
+	return n
+}
+
+// NewRawNamer will return a Namer that makes a name by which you would
+// directly refer to a type, optionally keeping track of the import paths
+// necessary to reference the names it provides. Tracker may be nil.
+// The 'pkg' is the full package name, in which the Namer is used - all
+// types from that package will be referenced by just type name without
+// referencing the package.
+//
+// For example, if the type is map[string]int, a raw namer will literally
+// return "map[string]int".
+//
+// Or if the type, in package foo, is "type Bar struct { ... }", then the raw
+// namer will return "foo.Bar" as the name of the type, and if 'tracker' was
+// not nil, will record that package foo needs to be imported.
+func NewRawNamer(pkg string, tracker ImportTracker) *rawNamer {
+	return &rawNamer{pkg: pkg, tracker: tracker}
+}
+
+// Names is a map from Type to name, as defined by some Namer.
+type Names map[*types.Type]string
+
+// Namer takes a type, and assigns a name.
+//
+// The purpose of this complexity is so that you can assign coherent
+// side-by-side systems of names for the types. For example, you might want a
+// public interface, a private implementation struct, and also to reference
+// literally the type name.
+//
+// Note that it is safe to call your own Name() function recursively to find
+// the names of keys, elements, etc. This is because anonymous types can't have
+// cycles in their names, and named types don't require the sort of recursion
+// that would be problematic.
+type Namer interface {
+	Name(*types.Type) string
+}
+
+// NameSystems is a map of a system name to a namer for that system.
+type NameSystems map[string]Namer
+
+// NameStrategy is a general Namer. The easiest way to use it is to copy the
+// Public/PrivateNamer variables, and modify the members you wish to change.
+//
+// The Name method produces a name for the given type, of the forms:
+// Anonymous types: 
+// Named types: 
+//
+// In all cases, every part of the name is run through the capitalization
+// functions.
+//
+// The IgnoreWords map can be set if you have directory names that are
+// semantically meaningless for naming purposes, e.g. "proto".
+//
+// Prefix and Suffix can be used to disambiguate parallel systems of type
+// names. For example, if you want to generate an interface and an
+// implementation, you might want to suffix one with "Interface" and the other
+// with "Implementation". Another common use-- if you want to generate private
+// types, and one of your source types could be "string", you can't use the
+// default lowercase private namer. You'll have to add a suffix or prefix.
+type NameStrategy struct {
+	Prefix, Suffix string
+	Join           func(pre string, parts []string, post string) string
+
+	// Add non-meaningful package directory names here (e.g. "proto") and
+	// they will be ignored.
+	IgnoreWords map[string]bool
+
+	// If > 0, prepend exactly that many package directory names (or as
+	// many as there are).  Package names listed in "IgnoreWords" will be
+	// ignored.
+	//
+	// For example, if Ignore words lists "proto" and type Foo is in
+	// pkg/server/frobbing/proto, then a value of 1 will give a type name
+	// of FrobbingFoo, 2 gives ServerFrobbingFoo, etc.
+	PrependPackageNames int
+
+	// A cache of names thus far assigned by this namer.
+	Names
+}
+
+// IC ensures the first character is uppercase.
+func IC(in string) string {
+	if in == "" {
+		return in
+	}
+	return strings.ToUpper(in[:1]) + in[1:]
+}
+
+// IL ensures the first character is lowercase.
+func IL(in string) string {
+	if in == "" {
+		return in
+	}
+	return strings.ToLower(in[:1]) + in[1:]
+}
+
+// Joiner lets you specify functions that preprocess the various components of
+// a name before joining them. You can construct e.g. camelCase or CamelCase or
+// any other way of joining words. (See the IC and IL convenience functions.)
+func Joiner(first, others func(string) string) func(pre string, in []string, post string) string {
+	return func(pre string, in []string, post string) string {
+		tmp := []string{others(pre)}
+		for i := range in {
+			tmp = append(tmp, others(in[i]))
+		}
+		tmp = append(tmp, others(post))
+		return first(strings.Join(tmp, ""))
+	}
+}
+
+func (ns *NameStrategy) removePrefixAndSuffix(s string) string {
+	// The join function may have changed capitalization.
+	lowerIn := strings.ToLower(s)
+	lowerP := strings.ToLower(ns.Prefix)
+	lowerS := strings.ToLower(ns.Suffix)
+	b, e := 0, len(s)
+	if strings.HasPrefix(lowerIn, lowerP) {
+		b = len(ns.Prefix)
+	}
+	if strings.HasSuffix(lowerIn, lowerS) {
+		e -= len(ns.Suffix)
+	}
+	return s[b:e]
+}
+
+var (
+	importPathNameSanitizer = strings.NewReplacer("-", "_", ".", "")
+)
+
+// filters out unwanted directory names and sanitizes remaining names.
+func (ns *NameStrategy) filterDirs(path string) []string {
+	allDirs := strings.Split(path, GoSeperator)
+	dirs := make([]string, 0, len(allDirs))
+	for _, p := range allDirs {
+		if ns.IgnoreWords == nil || !ns.IgnoreWords[p] {
+			dirs = append(dirs, importPathNameSanitizer.Replace(p))
+		}
+	}
+	return dirs
+}
+
+// See the comment on NameStrategy.
+func (ns *NameStrategy) Name(t *types.Type) string {
+	if ns.Names == nil {
+		ns.Names = Names{}
+	}
+	if s, ok := ns.Names[t]; ok {
+		return s
+	}
+
+	if t.Name.Package != "" {
+		dirs := append(ns.filterDirs(t.Name.Package), t.Name.Name)
+		i := ns.PrependPackageNames + 1
+		dn := len(dirs)
+		if i > dn {
+			i = dn
+		}
+		name := ns.Join(ns.Prefix, dirs[dn-i:], ns.Suffix)
+		ns.Names[t] = name
+		return name
+	}
+
+	// Only anonymous types remain.
+	var name string
+	switch t.Kind {
+	case types.Builtin:
+		name = ns.Join(ns.Prefix, []string{t.Name.Name}, ns.Suffix)
+	case types.Map:
+		name = ns.Join(ns.Prefix, []string{
+			"Map",
+			ns.removePrefixAndSuffix(ns.Name(t.Key)),
+			"To",
+			ns.removePrefixAndSuffix(ns.Name(t.Elem)),
+		}, ns.Suffix)
+	case types.Slice:
+		name = ns.Join(ns.Prefix, []string{
+			"Slice",
+			ns.removePrefixAndSuffix(ns.Name(t.Elem)),
+		}, ns.Suffix)
+	case types.Array:
+		name = ns.Join(ns.Prefix, []string{
+			"Array",
+			ns.removePrefixAndSuffix(fmt.Sprintf("%d", t.Len)),
+			ns.removePrefixAndSuffix(ns.Name(t.Elem)),
+		}, ns.Suffix)
+	case types.Pointer:
+		name = ns.Join(ns.Prefix, []string{
+			"Pointer",
+			ns.removePrefixAndSuffix(ns.Name(t.Elem)),
+		}, ns.Suffix)
+	case types.Struct:
+		names := []string{"Struct"}
+		for _, m := range t.Members {
+			names = append(names, ns.removePrefixAndSuffix(ns.Name(m.Type)))
+		}
+		name = ns.Join(ns.Prefix, names, ns.Suffix)
+	case types.Chan:
+		name = ns.Join(ns.Prefix, []string{
+			"Chan",
+			ns.removePrefixAndSuffix(ns.Name(t.Elem)),
+		}, ns.Suffix)
+	case types.Interface:
+		// TODO: add to name test
+		names := []string{"Interface"}
+		for _, m := range t.Methods {
+			// TODO: include function signature
+			names = append(names, m.Name.Name)
+		}
+		name = ns.Join(ns.Prefix, names, ns.Suffix)
+	case types.Func:
+		// TODO: add to name test
+		parts := []string{"Func"}
+		for _, param := range t.Signature.Parameters {
+			parts = append(parts, ns.removePrefixAndSuffix(ns.Name(param.Type)))
+		}
+		parts = append(parts, "Returns")
+		for _, result := range t.Signature.Results {
+			parts = append(parts, ns.removePrefixAndSuffix(ns.Name(result.Type)))
+		}
+		name = ns.Join(ns.Prefix, parts, ns.Suffix)
+	default:
+		name = "unnameable_" + string(t.Kind)
+	}
+	ns.Names[t] = name
+	return name
+}
+
+// ImportTracker allows a raw namer to keep track of the packages needed for
+// import. You can implement yourself or use the one in the generation package.
+type ImportTracker interface {
+	AddType(*types.Type)
+	AddSymbol(types.Name)
+	LocalNameOf(packagePath string) string
+	PathOf(localName string) (string, bool)
+	ImportLines() []string
+}
+
+type rawNamer struct {
+	pkg     string
+	tracker ImportTracker
+	Names
+}
+
+// Name makes a name the way you'd write it to literally refer to type t,
+// making ordinary assumptions about how you've imported t's package (or using
+// r.tracker to specifically track the package imports).
+func (r *rawNamer) Name(t *types.Type) string {
+	if r.Names == nil {
+		r.Names = Names{}
+	}
+	if name, ok := r.Names[t]; ok {
+		return name
+	}
+	if t.Name.Package != "" {
+		var name string
+		if r.tracker != nil {
+			r.tracker.AddType(t)
+			if t.Name.Package == r.pkg {
+				name = t.Name.Name
+			} else {
+				name = r.tracker.LocalNameOf(t.Name.Package) + "." + t.Name.Name
+			}
+		} else {
+			if t.Name.Package == r.pkg {
+				name = t.Name.Name
+			} else {
+				name = filepath.Base(t.Name.Package) + "." + t.Name.Name
+			}
+		}
+		r.Names[t] = name
+		return name
+	}
+	var name string
+	switch t.Kind {
+	case types.Builtin:
+		name = t.Name.Name
+	case types.Map:
+		name = "map[" + r.Name(t.Key) + "]" + r.Name(t.Elem)
+	case types.Slice:
+		name = "[]" + r.Name(t.Elem)
+	case types.Array:
+		l := strconv.Itoa(int(t.Len))
+		name = "[" + l + "]" + r.Name(t.Elem)
+	case types.Pointer:
+		name = "*" + r.Name(t.Elem)
+	case types.Struct:
+		elems := []string{}
+		for _, m := range t.Members {
+			elems = append(elems, m.Name+" "+r.Name(m.Type))
+		}
+		name = "struct{" + strings.Join(elems, "; ") + "}"
+	case types.Chan:
+		// TODO: include directionality
+		name = "chan " + r.Name(t.Elem)
+	case types.Interface:
+		// TODO: add to name test
+		elems := []string{}
+		for _, m := range t.Methods {
+			// TODO: include function signature
+			elems = append(elems, m.Name.Name)
+		}
+		if len(elems) == 0 {
+			name = "any"
+		} else {
+			name = "interface{" + strings.Join(elems, "; ") + "}"
+		}
+	case types.Func:
+		// TODO: add to name test
+		params := []string{}
+		for _, param := range t.Signature.Parameters {
+			params = append(params, r.Name(param.Type))
+		}
+		results := []string{}
+		for _, result := range t.Signature.Results {
+			results = append(results, r.Name(result.Type))
+		}
+		name = "func(" + strings.Join(params, ",") + ")"
+		if len(results) == 1 {
+			name += " " + results[0]
+		} else if len(results) > 1 {
+			name += " (" + strings.Join(results, ",") + ")"
+		}
+	default:
+		name = "unnameable_" + string(t.Kind)
+	}
+	r.Names[t] = name
+	return name
+}
diff --git a/vendor/k8s.io/gengo/v2/namer/order.go b/vendor/k8s.io/gengo/v2/namer/order.go
new file mode 100644
index 000000000..e676f0115
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/namer/order.go
@@ -0,0 +1,72 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package namer
+
+import (
+	"sort"
+
+	"k8s.io/gengo/v2/types"
+)
+
+// Orderer produces an ordering of types given a Namer.
+type Orderer struct {
+	Namer
+}
+
+// OrderUniverse assigns a name to every type in the Universe, including Types,
+// Functions and Variables, and returns a list sorted by those names.
+func (o *Orderer) OrderUniverse(u types.Universe) []*types.Type {
+	list := tList{
+		namer: o.Namer,
+	}
+	for _, p := range u {
+		for _, t := range p.Types {
+			list.types = append(list.types, t)
+		}
+		for _, f := range p.Functions {
+			list.types = append(list.types, f)
+		}
+		for _, v := range p.Variables {
+			list.types = append(list.types, v)
+		}
+		for _, v := range p.Constants {
+			list.types = append(list.types, v)
+		}
+	}
+	sort.Sort(list)
+	return list.types
+}
+
+// OrderTypes assigns a name to every type, and returns a list sorted by those
+// names.
+func (o *Orderer) OrderTypes(typeList []*types.Type) []*types.Type {
+	list := tList{
+		namer: o.Namer,
+		types: typeList,
+	}
+	sort.Sort(list)
+	return list.types
+}
+
+type tList struct {
+	namer Namer
+	types []*types.Type
+}
+
+func (t tList) Len() int           { return len(t.types) }
+func (t tList) Less(i, j int) bool { return t.namer.Name(t.types[i]) < t.namer.Name(t.types[j]) }
+func (t tList) Swap(i, j int)      { t.types[i], t.types[j] = t.types[j], t.types[i] }
diff --git a/vendor/k8s.io/gengo/v2/namer/plural_namer.go b/vendor/k8s.io/gengo/v2/namer/plural_namer.go
new file mode 100644
index 000000000..6bded6a04
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/namer/plural_namer.go
@@ -0,0 +1,120 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package namer
+
+import (
+	"strings"
+
+	"k8s.io/gengo/v2/types"
+)
+
+var consonants = "bcdfghjklmnpqrstvwxyz"
+
+type pluralNamer struct {
+	// key is the case-sensitive type name, value is the case-insensitive
+	// intended output.
+	exceptions map[string]string
+	finalize   func(string) string
+}
+
+// NewPublicPluralNamer returns a namer that returns the plural form of the input
+// type's name, starting with a uppercase letter.
+func NewPublicPluralNamer(exceptions map[string]string) *pluralNamer {
+	return &pluralNamer{exceptions, IC}
+}
+
+// NewPrivatePluralNamer returns a namer that returns the plural form of the input
+// type's name, starting with a lowercase letter.
+func NewPrivatePluralNamer(exceptions map[string]string) *pluralNamer {
+	return &pluralNamer{exceptions, IL}
+}
+
+// NewAllLowercasePluralNamer returns a namer that returns the plural form of the input
+// type's name, with all letters in lowercase.
+func NewAllLowercasePluralNamer(exceptions map[string]string) *pluralNamer {
+	return &pluralNamer{exceptions, strings.ToLower}
+}
+
+// Name returns the plural form of the type's name. If the type's name is found
+// in the exceptions map, the map value is returned.
+func (r *pluralNamer) Name(t *types.Type) string {
+	singular := t.Name.Name
+	var plural string
+	var ok bool
+	if plural, ok = r.exceptions[singular]; ok {
+		return r.finalize(plural)
+	}
+	if len(singular) < 2 {
+		return r.finalize(singular)
+	}
+
+	switch rune(singular[len(singular)-1]) {
+	case 's', 'x', 'z':
+		plural = esPlural(singular)
+	case 'y':
+		sl := rune(singular[len(singular)-2])
+		if isConsonant(sl) {
+			plural = iesPlural(singular)
+		} else {
+			plural = sPlural(singular)
+		}
+	case 'h':
+		sl := rune(singular[len(singular)-2])
+		if sl == 'c' || sl == 's' {
+			plural = esPlural(singular)
+		} else {
+			plural = sPlural(singular)
+		}
+	case 'e':
+		sl := rune(singular[len(singular)-2])
+		if sl == 'f' {
+			plural = vesPlural(singular[:len(singular)-1])
+		} else {
+			plural = sPlural(singular)
+		}
+	case 'f':
+		plural = vesPlural(singular)
+	default:
+		plural = sPlural(singular)
+	}
+	return r.finalize(plural)
+}
+
+func iesPlural(singular string) string {
+	return singular[:len(singular)-1] + "ies"
+}
+
+func vesPlural(singular string) string {
+	return singular[:len(singular)-1] + "ves"
+}
+
+func esPlural(singular string) string {
+	return singular + "es"
+}
+
+func sPlural(singular string) string {
+	return singular + "s"
+}
+
+func isConsonant(char rune) bool {
+	for _, c := range consonants {
+		if char == c {
+			return true
+		}
+	}
+	return false
+}
diff --git a/vendor/k8s.io/gengo/v2/parser/doc.go b/vendor/k8s.io/gengo/v2/parser/doc.go
new file mode 100644
index 000000000..8dc84facf
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/parser/doc.go
@@ -0,0 +1,19 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package parser provides code to parse go files, type-check them, extract the
+// types.
+package parser // import "k8s.io/gengo/v2/parser"
diff --git a/vendor/k8s.io/gengo/v2/parser/parse.go b/vendor/k8s.io/gengo/v2/parser/parse.go
new file mode 100644
index 000000000..4c1efa001
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/parser/parse.go
@@ -0,0 +1,888 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package parser
+
+import (
+	"errors"
+	"fmt"
+	"go/ast"
+	"go/constant"
+	"go/token"
+	gotypes "go/types"
+	"path/filepath"
+	"sort"
+	"strings"
+	"time"
+
+	"golang.org/x/tools/go/packages"
+
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+)
+
+// Parser lets you add all the go files in all the packages that you care
+// about, then constructs the type source data.
+type Parser struct {
+	// Map of package paths to definitions.  These keys should be canonical
+	// Go import paths (example.com/foo/bar) and not local paths (./foo/bar).
+	goPkgs map[string]*packages.Package
+
+	// Keep track of which packages were directly requested (as opposed to
+	// those which are transitively loaded).
+	userRequested map[string]bool
+
+	// Keep track of which packages have already been scanned for types.
+	fullyProcessed map[string]bool
+
+	// Build tags to set when loading packages.
+	buildTags []string
+
+	// Tracks accumulated parsed files, so we can do position lookups later.
+	fset *token.FileSet
+
+	// All comments from everywhere in every parsed file.  This map is keyed by
+	// the file-line on which the comment block ends, which makes it easy to
+	// look up comments which immediately precede a given obect (e.g. a type or
+	// function definition), which is what we almost always want.  We need this
+	// because Go's own ast package does a very poor job of handling comments.
+	endLineToCommentGroup map[fileLine]*ast.CommentGroup
+}
+
+// key type for finding comments.
+type fileLine struct {
+	file string
+	line int
+}
+
+// New constructs a new Parser.
+func New() *Parser {
+	return NewWithOptions(Options{})
+}
+
+func NewWithOptions(opts Options) *Parser {
+	return &Parser{
+		goPkgs:                map[string]*packages.Package{},
+		userRequested:         map[string]bool{},
+		fullyProcessed:        map[string]bool{},
+		fset:                  token.NewFileSet(),
+		endLineToCommentGroup: map[fileLine]*ast.CommentGroup{},
+		buildTags:             opts.BuildTags,
+	}
+}
+
+// Options holds optional settings for the Parser.
+type Options struct {
+	// BuildTags is a list of optional tags to be specified when loading
+	// packages.
+	BuildTags []string
+}
+
+// FindPackages expands the provided patterns into a list of Go import-paths,
+// much like `go list -find`.
+func (p *Parser) FindPackages(patterns ...string) ([]string, error) {
+	return p.findPackages(nil, patterns...)
+}
+
+// baseCfg is an optional (may be nil) config which might be injected by tests.
+func (p *Parser) findPackages(baseCfg *packages.Config, patterns ...string) ([]string, error) {
+	toFind := make([]string, 0, len(patterns))
+	results := make([]string, 0, len(patterns))
+	for _, pat := range patterns {
+		if pkg := p.goPkgs[pat]; pkg != nil {
+			results = append(results, pkg.PkgPath)
+		} else {
+			toFind = append(toFind, pat)
+		}
+	}
+	if len(toFind) == 0 {
+		return results, nil
+	}
+
+	cfg := packages.Config{
+		Mode:       packages.NeedName | packages.NeedFiles,
+		BuildFlags: []string{"-tags", strings.Join(p.buildTags, ",")},
+		Tests:      false,
+	}
+	if baseCfg != nil {
+		// This is to support tests, e.g. to inject a fake GOPATH or CWD.
+		cfg.Dir = baseCfg.Dir
+		cfg.Env = baseCfg.Env
+	}
+
+	pkgs, err := packages.Load(&cfg, toFind...)
+	if err != nil {
+		return nil, fmt.Errorf("error loading packages: %w", err)
+	}
+	var allErrs []error
+	for _, pkg := range pkgs {
+		results = append(results, pkg.PkgPath)
+
+		// pkg.Errors is not a slice of `error`, but concrete types.  We have
+		// to iteratively convert each one into `error`.
+		var errs []error
+		for _, e := range pkg.Errors {
+			errs = append(errs, e)
+		}
+		if len(errs) > 0 {
+			allErrs = append(allErrs, fmt.Errorf("error(s) in %q:\n%w", pkg.PkgPath, errors.Join(errs...)))
+		}
+	}
+	if len(allErrs) != 0 {
+		return nil, errors.Join(allErrs...)
+	}
+	return results, nil
+}
+
+// LoadPackages loads and parses the specified Go packages.  Specifically
+// named packages (without a trailing "/...") which do not exist or have no Go
+// files are an error.
+func (p *Parser) LoadPackages(patterns ...string) error {
+	_, err := p.loadPackages(patterns...)
+	return err
+}
+
+// LoadPackagesWithConfigForTesting loads and parses the specified Go packages with the
+// specified packages.Config as a starting point.  This is for testing, and
+// only the .Dir and .Env fields of the Config will be considered.
+func (p *Parser) LoadPackagesWithConfigForTesting(cfg *packages.Config, patterns ...string) error {
+	_, err := p.loadPackagesWithConfig(cfg, patterns...)
+	return err
+}
+
+// LoadPackagesTo loads and parses the specified Go packages, and inserts them
+// into the specified Universe. It returns the packages which match the
+// patterns, but loads all packages and their imports, recursively, into the
+// universe.  See NewUniverse for more.
+func (p *Parser) LoadPackagesTo(u *types.Universe, patterns ...string) ([]*types.Package, error) {
+	// Load Packages.
+	pkgs, err := p.loadPackages(patterns...)
+	if err != nil {
+		return nil, err
+	}
+
+	// Load types in all packages (it will internally filter).
+	if err := p.addPkgsToUniverse(pkgs, u); err != nil {
+		return nil, err
+	}
+
+	// Return the results as gengo types.Packages.
+	ret := make([]*types.Package, 0, len(pkgs))
+	for _, pkg := range pkgs {
+		ret = append(ret, u.Package(pkg.PkgPath))
+	}
+
+	return ret, nil
+}
+
+func (p *Parser) loadPackages(patterns ...string) ([]*packages.Package, error) {
+	return p.loadPackagesWithConfig(nil, patterns...)
+}
+
+// baseCfg is an optional (may be nil) config which might be injected by tests.
+func (p *Parser) loadPackagesWithConfig(baseCfg *packages.Config, patterns ...string) ([]*packages.Package, error) {
+	klog.V(5).Infof("loadPackages %q", patterns)
+
+	// Loading packages is slow - only do ones we know we have not already done
+	// (e.g. if a tool calls LoadPackages itself).
+	existingPkgs, netNewPkgs, err := p.alreadyLoaded(baseCfg, patterns...)
+	if err != nil {
+		return nil, err
+	}
+	if vlog := klog.V(5); vlog.Enabled() {
+		if len(existingPkgs) > 0 {
+			keys := make([]string, 0, len(existingPkgs))
+			for _, p := range existingPkgs {
+				keys = append(keys, p.PkgPath)
+			}
+			vlog.Infof("  already have: %q", keys)
+		}
+		if len(netNewPkgs) > 0 {
+			vlog.Infof("  to be loaded: %q", netNewPkgs)
+		}
+	}
+
+	// If these were not user-requested before, they are now.
+	for _, pkg := range existingPkgs {
+		if !p.userRequested[pkg.PkgPath] {
+			p.userRequested[pkg.PkgPath] = true
+		}
+	}
+	for _, pkg := range netNewPkgs {
+		if !p.userRequested[pkg] {
+			p.userRequested[pkg] = true
+		}
+	}
+
+	if len(netNewPkgs) == 0 {
+		return existingPkgs, nil
+	}
+
+	cfg := packages.Config{
+		Mode: packages.NeedName |
+			packages.NeedFiles | packages.NeedImports | packages.NeedDeps |
+			packages.NeedModule | packages.NeedTypes | packages.NeedSyntax,
+		BuildFlags: []string{"-tags", strings.Join(p.buildTags, ",")},
+		Fset:       p.fset,
+		Tests:      false,
+	}
+	if baseCfg != nil {
+		// This is to support tests, e.g. to inject a fake GOPATH or CWD.
+		cfg.Dir = baseCfg.Dir
+		cfg.Env = baseCfg.Env
+	}
+
+	tBefore := time.Now()
+	pkgs, err := packages.Load(&cfg, netNewPkgs...)
+	if err != nil {
+		return nil, fmt.Errorf("error loading packages: %w", err)
+	}
+	klog.V(5).Infof("  loaded %d pkg(s) in %v", len(pkgs), time.Since(tBefore))
+
+	// Handle any errors.
+	collectErrors := func(pkg *packages.Package) error {
+		var errs []error
+		for _, e := range pkg.Errors {
+			if e.Kind == packages.ListError || e.Kind == packages.ParseError {
+				errs = append(errs, e)
+			}
+		}
+		if len(errs) > 0 {
+			return fmt.Errorf("error(s) in %q:\n%w", pkg.PkgPath, errors.Join(errs...))
+		}
+		return nil
+	}
+	if err := forEachPackageRecursive(pkgs, collectErrors); err != nil {
+		return nil, err
+	}
+
+	// Finish integrating packages into our state.
+	absorbPkg := func(pkg *packages.Package) error {
+		p.goPkgs[pkg.PkgPath] = pkg
+
+		for _, f := range pkg.Syntax {
+			for _, c := range f.Comments {
+				// We need to do this on _every_ pkg, not just user-requested
+				// ones, because some generators look at tags in other
+				// packages.
+				//
+				// TODO: It would be nice if we only did this on user-requested
+				// packages.  The problem is that we don't always know which
+				// other packages will need this information, and even when we
+				// do we may have already loaded the package (as a transitive
+				// dep) and might have stored pointers into it.  Doing a
+				// thorough "reload" without invalidating all those pointers is
+				// a problem for another day.
+				position := p.fset.Position(c.End()) // Fset is synchronized
+				p.endLineToCommentGroup[fileLine{position.Filename, position.Line}] = c
+			}
+		}
+
+		return nil
+	}
+	if err := forEachPackageRecursive(pkgs, absorbPkg); err != nil {
+		return nil, err
+	}
+
+	return append(existingPkgs, pkgs...), nil
+}
+
+// alreadyLoaded figures out which of the specified patterns have already been loaded
+// and which have not, and returns those respectively.
+// baseCfg is an optional (may be nil) config which might be injected by tests.
+func (p *Parser) alreadyLoaded(baseCfg *packages.Config, patterns ...string) ([]*packages.Package, []string, error) {
+	existingPkgs := make([]*packages.Package, 0, len(patterns))
+	netNewPkgs := make([]string, 0, len(patterns))
+
+	// Expand and canonicalize the requested patterns.  This should be fast.
+	if pkgPaths, err := p.findPackages(baseCfg, patterns...); err != nil {
+		return nil, nil, err
+	} else {
+		for _, pkgPath := range pkgPaths {
+			if pkg := p.goPkgs[pkgPath]; pkg != nil {
+				existingPkgs = append(existingPkgs, pkg)
+			} else {
+				netNewPkgs = append(netNewPkgs, pkgPath)
+			}
+		}
+	}
+	return existingPkgs, netNewPkgs, nil
+}
+
+// forEachPackageRecursive will run the provided function on all of the specified
+// packages, and on their imports recursively.  Errors are accumulated and
+// returned as via errors.Join.
+func forEachPackageRecursive(pkgs []*packages.Package, fn func(pkg *packages.Package) error) error {
+	seen := map[string]bool{} // PkgPaths we have already visited
+	var errs []error
+	for _, pkg := range pkgs {
+		errs = append(errs, recursePackage(pkg, fn, seen)...)
+	}
+	if len(errs) > 0 {
+		return errors.Join(errs...)
+	}
+	return nil
+}
+
+func recursePackage(pkg *packages.Package, fn func(pkg *packages.Package) error, seen map[string]bool) []error {
+	if seen[pkg.PkgPath] {
+		return nil
+	}
+	var errs []error
+	seen[pkg.PkgPath] = true
+	if err := fn(pkg); err != nil {
+		errs = append(errs, err)
+	}
+	for _, imp := range pkg.Imports {
+		errs = append(errs, recursePackage(imp, fn, seen)...)
+	}
+	return errs
+}
+
+// UserRequestedPackages fetches a list of the user-imported packages.
+func (p *Parser) UserRequestedPackages() []string {
+	// Iterate packages in a predictable order.
+	pkgPaths := make([]string, 0, len(p.userRequested))
+	for k := range p.userRequested {
+		pkgPaths = append(pkgPaths, string(k))
+	}
+	sort.Strings(pkgPaths)
+	return pkgPaths
+}
+
+// NewUniverse finalizes the loaded packages, searches through them for types
+// and produces a new Universe. The returned Universe has one types.Package
+// entry for each Go package that has been loaded, including all of their
+// dependencies, recursively.  It also has one entry, whose key is "", which
+// represents "builtin" types.
+func (p *Parser) NewUniverse() (types.Universe, error) {
+	u := types.Universe{}
+
+	pkgs := []*packages.Package{}
+	for _, path := range p.UserRequestedPackages() {
+		pkgs = append(pkgs, p.goPkgs[path])
+	}
+	if err := p.addPkgsToUniverse(pkgs, &u); err != nil {
+		return nil, err
+	}
+
+	return u, nil
+}
+
+// addCommentsToType takes any accumulated comment lines prior to obj and
+// attaches them to the type t.
+func (p *Parser) addCommentsToType(obj gotypes.Object, t *types.Type) {
+	t.CommentLines = p.docComment(obj.Pos())
+	t.SecondClosestCommentLines = p.priorDetachedComment(obj.Pos())
+}
+
+// packageDir tries to figure out the directory of the specified package.
+func packageDir(pkg *packages.Package) (string, error) {
+	// Sometimes Module is present but has no Dir, e.g. when it is vendored.
+	if pkg.Module != nil && pkg.Module.Dir != "" {
+		// NOTE: this will not work if tests are loaded, because Go mutates the
+		// Package.PkgPath.
+		subdir := strings.TrimPrefix(pkg.PkgPath, pkg.Module.Path)
+		return filepath.Join(pkg.Module.Dir, subdir), nil
+	}
+	if len(pkg.GoFiles) > 0 {
+		return filepath.Dir(pkg.GoFiles[0]), nil
+	}
+	if len(pkg.IgnoredFiles) > 0 {
+		return filepath.Dir(pkg.IgnoredFiles[0]), nil
+	}
+	return "", fmt.Errorf("can't find package dir for %q - no module info and no Go files", pkg.PkgPath)
+}
+
+// addPkgsToUniverse adds the packages, and all of their deps, recursively, to
+// the universe and (if needed) searches through them for types.
+func (p *Parser) addPkgsToUniverse(pkgs []*packages.Package, u *types.Universe) error {
+	addOne := func(pkg *packages.Package) error {
+		if err := p.addPkgToUniverse(pkg, u); err != nil {
+			return err
+		}
+		return nil
+	}
+	if err := forEachPackageRecursive(pkgs, addOne); err != nil {
+		return err
+	}
+	return nil
+}
+
+// addPkgToUniverse adds one package to the universe and (if needed) searches
+// through it for types.
+func (p *Parser) addPkgToUniverse(pkg *packages.Package, u *types.Universe) error {
+	pkgPath := pkg.PkgPath
+	if p.fullyProcessed[pkgPath] {
+		return nil
+	}
+
+	// This will get-or-create the Package.
+	gengoPkg := u.Package(pkgPath)
+
+	if gengoPkg.Dir == "" {
+		// We're keeping this package, though we might not fully process it.
+		if vlog := klog.V(5); vlog.Enabled() {
+			why := "user-requested"
+			if !p.userRequested[pkgPath] {
+				why = "dependency"
+			}
+			vlog.Infof("addPkgToUniverse %q (%s)", pkgPath, why)
+		}
+
+		absPath := ""
+		if dir, err := packageDir(pkg); err != nil {
+			return err
+		} else {
+			absPath = dir
+		}
+
+		gengoPkg.Path = pkg.PkgPath
+		gengoPkg.Dir = absPath
+	}
+
+	// If the package was not user-requested, we can stop here.
+	if !p.userRequested[pkgPath] {
+		return nil
+	}
+
+	// Mark it as done, so we don't ever re-process it.
+	p.fullyProcessed[pkgPath] = true
+	gengoPkg.Name = pkg.Name
+
+	// For historical reasons we treat files named "doc.go" specially.
+	// TODO: It would be nice to not do this and instead treat package
+	// doc-comments as the "global" config place.  This would require changing
+	// most generators and input files.
+	for _, f := range pkg.Syntax {
+		// This gets the filename for the ast.File.  Iterating pkg.GoFiles is
+		// documented as unreliable.
+		pos := p.fset.Position(f.FileStart)
+		if filepath.Base(pos.Filename) == "doc.go" {
+			gengoPkg.Comments = []string{}
+			for i := range f.Comments {
+				gengoPkg.Comments = append(gengoPkg.Comments, splitLines(f.Comments[i].Text())...)
+			}
+			if f.Doc != nil {
+				gengoPkg.DocComments = splitLines(f.Doc.Text())
+			}
+		}
+	}
+
+	// Walk all the types, recursively and save them for later access.
+	s := pkg.Types.Scope()
+	for _, n := range s.Names() {
+		switch obj := s.Lookup(n).(type) {
+		case *gotypes.TypeName:
+			t := p.walkType(*u, nil, obj.Type())
+			p.addCommentsToType(obj, t)
+		case *gotypes.Func:
+			// We only care about functions, not concrete/abstract methods.
+			if obj.Type() != nil && obj.Type().(*gotypes.Signature).Recv() == nil {
+				t := p.addFunction(*u, nil, obj)
+				p.addCommentsToType(obj, t)
+			}
+		case *gotypes.Var:
+			if !obj.IsField() {
+				t := p.addVariable(*u, nil, obj)
+				p.addCommentsToType(obj, t)
+			}
+		case *gotypes.Const:
+			t := p.addConstant(*u, nil, obj)
+			p.addCommentsToType(obj, t)
+		default:
+			klog.Infof("addPkgToUniverse %q: unhandled object of type %T: %v", pkgPath, obj, obj)
+		}
+	}
+
+	// Add all of this package's imports.
+	importedPkgs := []string{}
+	for _, imp := range pkg.Imports {
+		if err := p.addPkgToUniverse(imp, u); err != nil {
+			return err
+		}
+		importedPkgs = append(importedPkgs, imp.PkgPath)
+	}
+	sort.Strings(importedPkgs)
+	u.AddImports(pkg.PkgPath, importedPkgs...)
+
+	return nil
+}
+
+// If the specified position has a "doc comment", return that.
+func (p *Parser) docComment(pos token.Pos) []string {
+	// An object's doc comment always ends on the line before the object's own
+	// declaration.
+	c1 := p.priorCommentLines(pos, 1)
+	return splitLines(c1.Text()) // safe even if c1 is nil
+}
+
+// If there is a detached (not immediately before a declaration) comment,
+// return that.
+func (p *Parser) priorDetachedComment(pos token.Pos) []string {
+	// An object's doc comment always ends on the line before the object's own
+	// declaration.
+	c1 := p.priorCommentLines(pos, 1)
+
+	// Using a literal "2" here is brittle in theory (it means literally 2
+	// lines), but in practice Go code is gofmt'ed (which elides repeated blank
+	// lines), so it works.
+	var c2 *ast.CommentGroup
+	if c1 == nil {
+		c2 = p.priorCommentLines(pos, 2)
+	} else {
+		c2 = p.priorCommentLines(c1.List[0].Slash, 2)
+	}
+	return splitLines(c2.Text()) // safe even if c1 is nil
+}
+
+// If there's a comment block which ends nlines before pos, return it.
+func (p *Parser) priorCommentLines(pos token.Pos, lines int) *ast.CommentGroup {
+	position := p.fset.Position(pos)
+	key := fileLine{position.Filename, position.Line - lines}
+	return p.endLineToCommentGroup[key]
+}
+
+func splitLines(str string) []string {
+	return strings.Split(strings.TrimRight(str, "\n"), "\n")
+}
+
+func goFuncNameToName(in string) types.Name {
+	name := strings.TrimPrefix(in, "func ")
+	nameParts := strings.Split(name, "(")
+	return goNameToName(nameParts[0])
+}
+
+func goVarNameToName(in string) types.Name {
+	nameParts := strings.Split(in, " ")
+	// nameParts[0] is "var".
+	// nameParts[2:] is the type of the variable, we ignore it for now.
+	return goNameToName(nameParts[1])
+}
+
+// goNameToName converts a go name string to a gengo types.Name.
+// It operates solely on the string on a best effort basis. The name may be updated
+// in walkType for generics.
+func goNameToName(in string) types.Name {
+	// Detect anonymous type names. (These may have '.' characters because
+	// embedded types may have packages, so we detect them specially.)
+	if strings.HasPrefix(in, "struct{") ||
+		strings.HasPrefix(in, "<-chan") ||
+		strings.HasPrefix(in, "chan<-") ||
+		strings.HasPrefix(in, "chan ") ||
+		strings.HasPrefix(in, "func(") ||
+		strings.HasPrefix(in, "func (") ||
+		strings.HasPrefix(in, "*") ||
+		strings.HasPrefix(in, "map[") ||
+		strings.HasPrefix(in, "[") {
+		return types.Name{Name: in}
+	}
+
+	// There may be '.' characters within a generic. Temporarily remove
+	// the generic.
+	genericIndex := strings.IndexRune(in, '[')
+	if genericIndex == -1 {
+		genericIndex = len(in)
+	}
+
+	// Otherwise, if there are '.' characters present, the name has a
+	// package path in front.
+	nameParts := strings.Split(in[:genericIndex], ".")
+	name := types.Name{Name: in}
+	if n := len(nameParts); n >= 2 {
+		// The final "." is the name of the type--previous ones must
+		// have been in the package path.
+		name.Package, name.Name = strings.Join(nameParts[:n-1], "."), nameParts[n-1]
+		// Add back the generic component now that the package and type name have been separated.
+		if genericIndex != len(in) {
+			name.Name = name.Name + in[genericIndex:]
+		}
+	}
+	return name
+}
+
+func (p *Parser) convertSignature(u types.Universe, t *gotypes.Signature) *types.Signature {
+	signature := &types.Signature{}
+	for i := 0; i < t.Params().Len(); i++ {
+		signature.Parameters = append(signature.Parameters, &types.ParamResult{
+			Name: t.Params().At(i).Name(),
+			Type: p.walkType(u, nil, t.Params().At(i).Type()),
+		})
+	}
+	for i := 0; i < t.Results().Len(); i++ {
+		signature.Results = append(signature.Results, &types.ParamResult{
+			Name: t.Results().At(i).Name(),
+			Type: p.walkType(u, nil, t.Results().At(i).Type()),
+		})
+	}
+	if r := t.Recv(); r != nil {
+		signature.Receiver = p.walkType(u, nil, r.Type())
+	}
+	signature.Variadic = t.Variadic()
+	return signature
+}
+
+// walkType adds the type, and any necessary child types.
+func (p *Parser) walkType(u types.Universe, useName *types.Name, in gotypes.Type) *types.Type {
+	// Most of the cases are underlying types of the named type.
+	name := goNameToName(in.String())
+	if useName != nil {
+		name = *useName
+	}
+
+	// Handle alias types conditionally on go1.22+.
+	// Inline this once the minimum supported version is go1.22
+	if out := p.walkAliasType(u, in); out != nil {
+		return out
+	}
+
+	switch t := in.(type) {
+	case *gotypes.Struct:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Struct
+		for i := 0; i < t.NumFields(); i++ {
+			f := t.Field(i)
+			m := types.Member{
+				Name:         f.Name(),
+				Embedded:     f.Anonymous(),
+				Tags:         t.Tag(i),
+				Type:         p.walkType(u, nil, f.Type()),
+				CommentLines: p.docComment(f.Pos()),
+			}
+			out.Members = append(out.Members, m)
+		}
+		return out
+	case *gotypes.Map:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Map
+		out.Elem = p.walkType(u, nil, t.Elem())
+		out.Key = p.walkType(u, nil, t.Key())
+		return out
+	case *gotypes.Pointer:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Pointer
+		out.Elem = p.walkType(u, nil, t.Elem())
+		return out
+	case *gotypes.Slice:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Slice
+		out.Elem = p.walkType(u, nil, t.Elem())
+		return out
+	case *gotypes.Array:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Array
+		out.Elem = p.walkType(u, nil, t.Elem())
+		out.Len = in.(*gotypes.Array).Len()
+		return out
+	case *gotypes.Chan:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Chan
+		out.Elem = p.walkType(u, nil, t.Elem())
+		// TODO: need to store direction, otherwise raw type name
+		// cannot be properly written.
+		return out
+	case *gotypes.Basic:
+		out := u.Type(types.Name{
+			Package: "", // This is a magic package name in the Universe.
+			Name:    t.Name(),
+		})
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Unsupported
+		return out
+	case *gotypes.Signature:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Func
+		out.Signature = p.convertSignature(u, t)
+		return out
+	case *gotypes.Interface:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Interface
+		t.Complete()
+		for i := 0; i < t.NumMethods(); i++ {
+			if out.Methods == nil {
+				out.Methods = map[string]*types.Type{}
+			}
+			method := t.Method(i)
+			name := goNameToName(method.String())
+			mt := p.walkType(u, &name, method.Type())
+			mt.CommentLines = p.docComment(method.Pos())
+			out.Methods[method.Name()] = mt
+		}
+		return out
+	case *gotypes.Named:
+		var out *types.Type
+		switch t.Underlying().(type) {
+		case *gotypes.Named, *gotypes.Basic, *gotypes.Map, *gotypes.Slice:
+			name := goNameToName(t.String())
+			out = u.Type(name)
+			out.GoType = in
+			if out.Kind != types.Unknown {
+				return out
+			}
+			out.Kind = types.Alias
+			out.Underlying = p.walkType(u, nil, t.Underlying())
+		case *gotypes.Struct, *gotypes.Interface:
+			name := goNameToName(t.String())
+			tpMap := map[string]*types.Type{}
+			if t.TypeParams().Len() != 0 {
+				// Remove generics, then readd them without the encoded
+				// type, e.g. Foo[T any] => Foo[T]
+				var tpNames []string
+				for i := 0; i < t.TypeParams().Len(); i++ {
+					tp := t.TypeParams().At(i)
+					tpName := tp.Obj().Name()
+					tpNames = append(tpNames, tpName)
+					tpMap[tpName] = p.walkType(u, nil, tp.Constraint())
+				}
+				name.Name = fmt.Sprintf("%s[%s]", strings.SplitN(name.Name, "[", 2)[0], strings.Join(tpNames, ","))
+			}
+
+			if out := u.Type(name); out.Kind != types.Unknown {
+				out.GoType = in
+				return out // short circuit if we've already made this.
+			}
+			out = p.walkType(u, &name, t.Underlying())
+			out.TypeParams = tpMap
+		default:
+			// gotypes package makes everything "named" with an
+			// underlying anonymous type--we remove that annoying
+			// "feature" for users. This flattens those types
+			// together.
+			name := goNameToName(t.String())
+			if out := u.Type(name); out.Kind != types.Unknown {
+				return out // short circuit if we've already made this.
+			}
+			out = p.walkType(u, &name, t.Underlying())
+		}
+		// If the underlying type didn't already add methods, add them.
+		// (Interface types will have already added methods.)
+		if len(out.Methods) == 0 {
+			for i := 0; i < t.NumMethods(); i++ {
+				if out.Methods == nil {
+					out.Methods = map[string]*types.Type{}
+				}
+				method := t.Method(i)
+				name := goNameToName(method.String())
+				mt := p.walkType(u, &name, method.Type())
+				mt.CommentLines = p.docComment(method.Pos())
+				out.Methods[method.Name()] = mt
+			}
+		}
+		return out
+	case *gotypes.TypeParam:
+		// DO NOT retrieve the type from the universe. The default type-param name is only the
+		// generic variable name. Ideally, it would be namespaced by package and struct but it is
+		// not. Thus, if we try to use the universe, we would start polluting it.
+		// e.g. if Foo[T] and Bar[T] exists, we'd mistakenly use the same type T for both.
+		return &types.Type{
+			Name: name,
+			Kind: types.TypeParam,
+		}
+	default:
+		out := u.Type(name)
+		out.GoType = in
+		if out.Kind != types.Unknown {
+			return out
+		}
+		out.Kind = types.Unsupported
+		klog.Warningf("Making unsupported type entry %q for: %#v\n", out, t)
+		return out
+	}
+}
+
+func (p *Parser) addFunction(u types.Universe, useName *types.Name, in *gotypes.Func) *types.Type {
+	name := goFuncNameToName(in.String())
+	if useName != nil {
+		name = *useName
+	}
+	out := u.Function(name)
+	out.Kind = types.DeclarationOf
+	out.Underlying = p.walkType(u, nil, in.Type())
+	return out
+}
+
+func (p *Parser) addVariable(u types.Universe, useName *types.Name, in *gotypes.Var) *types.Type {
+	name := goVarNameToName(in.String())
+	if useName != nil {
+		name = *useName
+	}
+	out := u.Variable(name)
+	out.Kind = types.DeclarationOf
+	out.Underlying = p.walkType(u, nil, in.Type())
+	return out
+}
+
+func (p *Parser) addConstant(u types.Universe, useName *types.Name, in *gotypes.Const) *types.Type {
+	name := goVarNameToName(in.String())
+	if useName != nil {
+		name = *useName
+	}
+	out := u.Constant(name)
+	out.Kind = types.DeclarationOf
+	out.Underlying = p.walkType(u, nil, in.Type())
+
+	var constval string
+
+	// For strings, we use `StringVal()` to get the un-truncated,
+	// un-quoted string. For other values, `.String()` is preferable to
+	// get something relatively human readable (especially since for
+	// floating point types, `ExactString()` will generate numeric
+	// expressions using `big.(*Float).Text()`.
+	switch in.Val().Kind() {
+	case constant.String:
+		constval = constant.StringVal(in.Val())
+	default:
+		constval = in.Val().String()
+	}
+
+	out.ConstValue = &constval
+	return out
+}
diff --git a/vendor/k8s.io/gengo/v2/parser/parse_122.go b/vendor/k8s.io/gengo/v2/parser/parse_122.go
new file mode 100644
index 000000000..ec2064958
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/parser/parse_122.go
@@ -0,0 +1,33 @@
+//go:build go1.22
+// +build go1.22
+
+/*
+Copyright 2024 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package parser
+
+import (
+	gotypes "go/types"
+
+	"k8s.io/gengo/v2/types"
+)
+
+func (p *Parser) walkAliasType(u types.Universe, in gotypes.Type) *types.Type {
+	if t, isAlias := in.(*gotypes.Alias); isAlias {
+		return p.walkType(u, nil, gotypes.Unalias(t))
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/gengo/v2/parser/parse_pre_122.go b/vendor/k8s.io/gengo/v2/parser/parse_pre_122.go
new file mode 100644
index 000000000..6f62100c0
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/parser/parse_pre_122.go
@@ -0,0 +1,30 @@
+//go:build !go1.22
+// +build !go1.22
+
+/*
+Copyright 2024 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package parser
+
+import (
+	gotypes "go/types"
+
+	"k8s.io/gengo/v2/types"
+)
+
+func (p *Parser) walkAliasType(u types.Universe, in gotypes.Type) *types.Type {
+	return nil
+}
diff --git a/vendor/k8s.io/gengo/v2/types/doc.go b/vendor/k8s.io/gengo/v2/types/doc.go
new file mode 100644
index 000000000..23acb879c
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/types/doc.go
@@ -0,0 +1,19 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package types contains go type information, packaged in a way that makes
+// auto-generation convenient, whether by template or straight go functions.
+package types // import "k8s.io/gengo/v2/types"
diff --git a/vendor/k8s.io/gengo/v2/types/types.go b/vendor/k8s.io/gengo/v2/types/types.go
new file mode 100644
index 000000000..dab11d96e
--- /dev/null
+++ b/vendor/k8s.io/gengo/v2/types/types.go
@@ -0,0 +1,575 @@
+/*
+Copyright 2015 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package types
+
+import (
+	gotypes "go/types"
+	"strings"
+)
+
+// Ref makes a reference to the given type. It can only be used for e.g.
+// passing to namers.
+func Ref(packageName, typeName string) *Type {
+	return &Type{Name: Name{
+		Name:    typeName,
+		Package: packageName,
+	}}
+}
+
+// A type name may have a package qualifier.
+type Name struct {
+	// Empty if embedded or builtin. This is the package path unless Path is specified.
+	Package string
+	// The type name.
+	Name string
+	// An optional location of the type definition for languages that can have disjoint
+	// packages and paths.
+	Path string
+}
+
+// String returns the name formatted as a string.
+func (n Name) String() string {
+	if n.Package == "" {
+		return n.Name
+	}
+	return n.Package + "." + n.Name
+}
+
+// ParseFullyQualifiedName parses a name like k8s.io/kubernetes/pkg/api.Pod into a Name.
+func ParseFullyQualifiedName(fqn string) Name {
+	cs := strings.Split(fqn, ".")
+	pkg := ""
+	if len(cs) > 1 {
+		pkg = strings.Join(cs[0:len(cs)-1], ".")
+	}
+	return Name{
+		Name:    cs[len(cs)-1],
+		Package: pkg,
+	}
+}
+
+// The possible classes of types.
+type Kind string
+
+const (
+	// Builtin is a primitive, like bool, string, int.
+	Builtin Kind = "Builtin"
+	Struct  Kind = "Struct"
+	Map     Kind = "Map"
+	Slice   Kind = "Slice"
+	Pointer Kind = "Pointer"
+
+	// Alias is an alias of another type, e.g. in:
+	//   type Foo string
+	//   type Bar Foo
+	// Bar is an alias of Foo.
+	//
+	// In the real go type system, Foo is a "Named" string; but to simplify
+	// generation, this type system will just say that Foo *is* a builtin.
+	// We then need "Alias" as a way for us to say that Bar *is* a Foo.
+	Alias Kind = "Alias"
+
+	// Interface is any type that could have differing types at run time.
+	Interface Kind = "Interface"
+
+	// Array is just like slice, but has a fixed length.
+	Array Kind = "Array"
+
+	// The remaining types are included for completeness, but are not well
+	// supported.
+	Chan Kind = "Chan"
+	Func Kind = "Func"
+
+	// DeclarationOf is different from other Kinds; it indicates that instead of
+	// representing an actual Type, the type is a declaration of an instance of
+	// a type. E.g., a top-level function, variable, or constant. See the
+	// comment for Type.Name for more detail.
+	DeclarationOf Kind = "DeclarationOf"
+	Unknown       Kind = ""
+	Unsupported   Kind = "Unsupported"
+	TypeParam     Kind = "TypeParam"
+
+	// Protobuf is protobuf type.
+	Protobuf Kind = "Protobuf"
+)
+
+// Package holds package-level information.
+// Fields are public, as everything in this package, to enable consumption by
+// templates (for example). But it is strongly encouraged for code to build by
+// using the provided functions.
+type Package struct {
+	// Canonical import-path of this package.
+	Path string
+
+	// The location (on disk) of this package.
+	Dir string
+
+	// Short name of this package, as in the 'package x' line.
+	Name string
+
+	// The comment right above the package declaration in doc.go, if any.
+	DocComments []string
+
+	// All comments from doc.go, if any.
+	// TODO: remove Comments and use DocComments everywhere.
+	Comments []string
+
+	// Types within this package, indexed by their name (*not* including
+	// package name).
+	Types map[string]*Type
+
+	// Functions within this package, indexed by their name (*not* including
+	// package name).
+	Functions map[string]*Type
+
+	// Global variables within this package, indexed by their name (*not* including
+	// package name).
+	Variables map[string]*Type
+
+	// Global constants within this package, indexed by their name (*not* including
+	// package name).
+	Constants map[string]*Type
+
+	// Packages imported by this package, indexed by (canonicalized)
+	// package path.
+	Imports map[string]*Package
+}
+
+// Has returns true if the given name references a type known to this package.
+func (p *Package) Has(name string) bool {
+	_, has := p.Types[name]
+	return has
+}
+
+// Type gets the given Type in this Package.  If the Type is not already
+// defined, this will add it and return the new Type value.  The caller is
+// expected to finish initialization.
+func (p *Package) Type(typeName string) *Type {
+	if t, ok := p.Types[typeName]; ok {
+		return t
+	}
+	if p.Path == "" {
+		// Import the standard builtin types!
+		if t, ok := builtins.Types[typeName]; ok {
+			p.Types[typeName] = t
+			return t
+		}
+	}
+	t := &Type{Name: Name{Package: p.Path, Name: typeName}}
+	p.Types[typeName] = t
+	return t
+}
+
+// Function gets the given function Type in this Package. If the function is
+// not already defined, this will add it.  If a function is added, it's the
+// caller's responsibility to finish construction of the function by setting
+// Underlying to the correct type.
+func (p *Package) Function(funcName string) *Type {
+	if t, ok := p.Functions[funcName]; ok {
+		return t
+	}
+	t := &Type{Name: Name{Package: p.Path, Name: funcName}}
+	t.Kind = DeclarationOf
+	p.Functions[funcName] = t
+	return t
+}
+
+// Variable gets the given variable Type in this Package. If the variable is
+// not already defined, this will add it. If a variable is added, it's the caller's
+// responsibility to finish construction of the variable by setting Underlying
+// to the correct type.
+func (p *Package) Variable(varName string) *Type {
+	if t, ok := p.Variables[varName]; ok {
+		return t
+	}
+	t := &Type{Name: Name{Package: p.Path, Name: varName}}
+	t.Kind = DeclarationOf
+	p.Variables[varName] = t
+	return t
+}
+
+// Constant gets the given constant Type in this Package. If the constant is
+// not already defined, this will add it. If a constant is added, it's the caller's
+// responsibility to finish construction of the constant by setting Underlying
+// to the correct type.
+func (p *Package) Constant(constName string) *Type {
+	if t, ok := p.Constants[constName]; ok {
+		return t
+	}
+	t := &Type{Name: Name{Package: p.Path, Name: constName}}
+	t.Kind = DeclarationOf
+	p.Constants[constName] = t
+	return t
+}
+
+// HasImport returns true if p imports packageName. Package names include the
+// package directory.
+func (p *Package) HasImport(packageName string) bool {
+	_, has := p.Imports[packageName]
+	return has
+}
+
+// Universe is a map of all packages. The key is the package name, but you
+// should use Package(), Type(), Function(), or Variable() instead of direct
+// access.
+type Universe map[string]*Package
+
+// Type returns the canonical type for the given fully-qualified name. Builtin
+// types will always be found, even if they haven't been explicitly added to
+// the map. If a non-existing type is requested, this will create (a marker for)
+// it.
+func (u Universe) Type(n Name) *Type {
+	return u.Package(n.Package).Type(n.Name)
+}
+
+// Function returns the canonical function for the given fully-qualified name.
+// If a non-existing function is requested, this will create (a marker for) it.
+// If a marker is created, it's the caller's responsibility to finish
+// construction of the function by setting Underlying to the correct type.
+func (u Universe) Function(n Name) *Type {
+	return u.Package(n.Package).Function(n.Name)
+}
+
+// Variable returns the canonical variable for the given fully-qualified name.
+// If a non-existing variable is requested, this will create (a marker for) it.
+// If a marker is created, it's the caller's responsibility to finish
+// construction of the variable by setting Underlying to the correct type.
+func (u Universe) Variable(n Name) *Type {
+	return u.Package(n.Package).Variable(n.Name)
+}
+
+// Constant returns the canonical constant for the given fully-qualified name.
+// If a non-existing constant is requested, this will create (a marker for) it.
+// If a marker is created, it's the caller's responsibility to finish
+// construction of the constant by setting Underlying to the correct type.
+func (u Universe) Constant(n Name) *Type {
+	return u.Package(n.Package).Constant(n.Name)
+}
+
+// AddImports registers import lines for packageName. May be called multiple times.
+// You are responsible for canonicalizing all package paths.
+func (u Universe) AddImports(packagePath string, importPaths ...string) {
+	p := u.Package(packagePath)
+	for _, i := range importPaths {
+		p.Imports[i] = u.Package(i)
+	}
+}
+
+// Package returns the Package for the given path.
+// If a non-existing package is requested, this will create (a marker for) it.
+// If a marker is created, it's the caller's responsibility to finish
+// construction of the package.
+func (u Universe) Package(packagePath string) *Package {
+	if p, ok := u[packagePath]; ok {
+		return p
+	}
+	p := &Package{
+		Path:      packagePath,
+		Types:     map[string]*Type{},
+		Functions: map[string]*Type{},
+		Variables: map[string]*Type{},
+		Constants: map[string]*Type{},
+		Imports:   map[string]*Package{},
+	}
+	u[packagePath] = p
+	return p
+}
+
+// Type represents a subset of possible go types.
+type Type struct {
+	// There are two general categories of types, those explicitly named
+	// and those anonymous. Named ones will have a non-empty package in the
+	// name field.
+	//
+	// An exception: If Kind == DeclarationOf, then this name is the name of a
+	// top-level function, variable, or const, and the type can be found in Underlying.
+	// We do this to allow the naming system to work against these objects, even
+	// though they aren't strictly speaking types.
+	Name Name
+
+	// The general kind of this type.
+	Kind Kind
+
+	// If there are comment lines immediately before the type definition,
+	// they will be recorded here.
+	CommentLines []string
+
+	// If there are comment lines preceding the `CommentLines`, they will be
+	// recorded here. There are two cases:
+	// ---
+	// SecondClosestCommentLines
+	// a blank line
+	// CommentLines
+	// type definition
+	// ---
+	//
+	// or
+	// ---
+	// SecondClosestCommentLines
+	// a blank line
+	// type definition
+	// ---
+	SecondClosestCommentLines []string
+
+	// If Kind == Struct
+	Members []Member
+
+	// If Kind == Struct
+	TypeParams map[string]*Type
+
+	// If Kind == Map, Slice, Pointer, or Chan
+	Elem *Type
+
+	// If Kind == Map, this is the map's key type.
+	Key *Type
+
+	// If Kind == Alias, this is the underlying type.
+	// If Kind == DeclarationOf, this is the type of the declaration.
+	Underlying *Type
+
+	// If Kind == Interface, this is the set of all required functions.
+	// Otherwise, if this is a named type, this is the list of methods that
+	// type has. (All elements will have Kind=="Func")
+	Methods map[string]*Type
+
+	// If Kind == func, this is the signature of the function.
+	Signature *Signature
+
+	// ConstValue contains a stringified constant value if
+	// Kind == DeclarationOf and this is a constant value
+	// declaration. For string constants, this field contains
+	// the entire, un-quoted value. For other types, it contains
+	// a human-readable literal.
+	ConstValue *string
+
+	// TODO: Add:
+	// * channel direction
+
+	// If Kind == Array
+	Len int64
+
+	// The underlying Go type.
+	GoType gotypes.Type
+}
+
+// String returns the name of the type.
+func (t *Type) String() string {
+	if t == nil {
+		return "" // makes tests easier
+	}
+	return t.Name.String()
+}
+
+// IsPrimitive returns whether the type is a built-in type or is an alias to a
+// built-in type.  For example: strings and aliases of strings are primitives,
+// structs are not.
+func (t *Type) IsPrimitive() bool {
+	if t.Kind == Builtin || (t.Kind == Alias && t.Underlying.Kind == Builtin) {
+		return true
+	}
+	return false
+}
+
+// IsAssignable returns whether the type is deep-assignable.  For example,
+// slices and maps and pointers are shallow copies, but ints and strings are
+// complete.
+func (t *Type) IsAssignable() bool {
+	if t.IsPrimitive() {
+		return true
+	}
+	if t.Kind == Struct {
+		for _, m := range t.Members {
+			if !m.Type.IsAssignable() {
+				return false
+			}
+		}
+		return true
+	}
+	return false
+}
+
+// IsAnonymousStruct returns true if the type is an anonymous struct or an alias
+// to an anonymous struct.
+func (t *Type) IsAnonymousStruct() bool {
+	return (t.Kind == Struct && t.Name.Name == "struct{}") || (t.Kind == Alias && t.Underlying.IsAnonymousStruct())
+}
+
+// IsComparable returns whether the type is comparable.
+func (t *Type) IsComparable() bool {
+	return gotypes.Comparable(t.GoType)
+}
+
+// A single struct member
+type Member struct {
+	// The name of the member.
+	Name string
+
+	// If the member is embedded (anonymous) this will be true, and the
+	// Name will be the type name.
+	Embedded bool
+
+	// If there are comment lines immediately before the member in the type
+	// definition, they will be recorded here.
+	CommentLines []string
+
+	// If there are tags along with this member, they will be saved here.
+	Tags string
+
+	// The type of this member.
+	Type *Type
+}
+
+// String returns the name and type of the member.
+func (m Member) String() string {
+	return m.Name + " " + m.Type.String()
+}
+
+// ParamResult represents a parameter or a result of a method's signature.
+type ParamResult struct {
+	// The name of the parameter or result.
+	Name string
+	// The type of this parameter or result.
+	Type *Type
+}
+
+// Signature is a function's signature.
+type Signature struct {
+	// If a method of some type, this is the type it's a member of.
+	Receiver   *Type
+	Parameters []*ParamResult
+	Results    []*ParamResult
+
+	// True if the last in parameter is of the form ...T.
+	Variadic bool
+
+	// If there are comment lines immediately before this
+	// signature/method/function declaration, they will be recorded here.
+	CommentLines []string
+}
+
+// Built in types.
+var (
+	Any = &Type{
+		Name: Name{Name: "any"},
+		Kind: Interface,
+	}
+	String = &Type{
+		Name: Name{Name: "string"},
+		Kind: Builtin,
+	}
+	Int64 = &Type{
+		Name: Name{Name: "int64"},
+		Kind: Builtin,
+	}
+	Int32 = &Type{
+		Name: Name{Name: "int32"},
+		Kind: Builtin,
+	}
+	Int16 = &Type{
+		Name: Name{Name: "int16"},
+		Kind: Builtin,
+	}
+	Int = &Type{
+		Name: Name{Name: "int"},
+		Kind: Builtin,
+	}
+	Uint64 = &Type{
+		Name: Name{Name: "uint64"},
+		Kind: Builtin,
+	}
+	Uint32 = &Type{
+		Name: Name{Name: "uint32"},
+		Kind: Builtin,
+	}
+	Uint16 = &Type{
+		Name: Name{Name: "uint16"},
+		Kind: Builtin,
+	}
+	Uint = &Type{
+		Name: Name{Name: "uint"},
+		Kind: Builtin,
+	}
+	Uintptr = &Type{
+		Name: Name{Name: "uintptr"},
+		Kind: Builtin,
+	}
+	Float64 = &Type{
+		Name: Name{Name: "float64"},
+		Kind: Builtin,
+	}
+	Float32 = &Type{
+		Name: Name{Name: "float32"},
+		Kind: Builtin,
+	}
+	Float = &Type{
+		Name: Name{Name: "float"},
+		Kind: Builtin,
+	}
+	Bool = &Type{
+		Name: Name{Name: "bool"},
+		Kind: Builtin,
+	}
+	Byte = &Type{
+		Name: Name{Name: "byte"},
+		Kind: Builtin,
+	}
+
+	builtins = &Package{
+		Types: map[string]*Type{
+			"any":     Any,
+			"bool":    Bool,
+			"string":  String,
+			"int":     Int,
+			"int64":   Int64,
+			"int32":   Int32,
+			"int16":   Int16,
+			"int8":    Byte,
+			"uint":    Uint,
+			"uint64":  Uint64,
+			"uint32":  Uint32,
+			"uint16":  Uint16,
+			"uint8":   Byte,
+			"uintptr": Uintptr,
+			"byte":    Byte,
+			"float":   Float,
+			"float64": Float64,
+			"float32": Float32,
+		},
+		Imports: map[string]*Package{},
+		Path:    "",
+		Name:    "",
+	}
+)
+
+func PointerTo(t *Type) *Type {
+	return &Type{
+		Name: Name{
+			Name: "*" + t.Name.String(),
+		},
+		Kind: Pointer,
+		Elem: t,
+	}
+}
+
+func IsInteger(t *Type) bool {
+	switch t {
+	case Int, Int64, Int32, Int16, Uint, Uint64, Uint32, Uint16, Byte:
+		return true
+	default:
+		return false
+	}
+}
diff --git a/vendor/k8s.io/kube-openapi/cmd/openapi-gen/args/args.go b/vendor/k8s.io/kube-openapi/cmd/openapi-gen/args/args.go
new file mode 100644
index 000000000..153784ed9
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/cmd/openapi-gen/args/args.go
@@ -0,0 +1,78 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package args
+
+import (
+	"fmt"
+
+	"github.com/spf13/pflag"
+)
+
+type Args struct {
+	OutputDir  string // must be a directory path
+	OutputPkg  string // must be a Go import-path
+	OutputFile string
+
+	GoHeaderFile string
+
+	// ReportFilename is added to Args for specifying name of report file used
+	// by API linter. If specified, API rule violations will be printed to report file.
+	// Otherwise default value "-" will be used which indicates stdout.
+	ReportFilename string
+}
+
+// New returns default arguments for the generator. Returning the arguments instead
+// of using default flag parsing allows registering custom arguments afterwards
+func New() *Args {
+	args := &Args{}
+
+	// Default value for report filename is "-", which stands for stdout
+	args.ReportFilename = "-"
+
+	return args
+}
+
+// AddFlags add the generator flags to the flag set.
+func (args *Args) AddFlags(fs *pflag.FlagSet) {
+	fs.StringVar(&args.OutputDir, "output-dir", "",
+		"the base directory under which to generate results")
+	fs.StringVar(&args.OutputPkg, "output-pkg", "",
+		"the base Go import-path under which to generate results")
+	fs.StringVar(&args.OutputFile, "output-file", "generated.openapi.go",
+		"the name of the file to be generated")
+	fs.StringVar(&args.GoHeaderFile, "go-header-file", "",
+		"the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year")
+	fs.StringVarP(&args.ReportFilename, "report-filename", "r", args.ReportFilename,
+		"Name of report file used by API linter to print API violations. Default \"-\" stands for standard output. NOTE that if valid filename other than \"-\" is specified, API linter won't return error on detected API violations. This allows further check of existing API violations without stopping the OpenAPI generation toolchain.")
+}
+
+// Validate checks the given arguments.
+func (args *Args) Validate() error {
+	if len(args.OutputDir) == 0 {
+		return fmt.Errorf("--output-dir must be specified")
+	}
+	if len(args.OutputPkg) == 0 {
+		return fmt.Errorf("--output-pkg must be specified")
+	}
+	if len(args.OutputFile) == 0 {
+		return fmt.Errorf("--output-file must be specified")
+	}
+	if len(args.ReportFilename) == 0 {
+		return fmt.Errorf("--report-filename must be specified (use \"-\" for stdout)")
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/kube-openapi/cmd/openapi-gen/openapi-gen.go b/vendor/k8s.io/kube-openapi/cmd/openapi-gen/openapi-gen.go
new file mode 100644
index 000000000..b466019ad
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/cmd/openapi-gen/openapi-gen.go
@@ -0,0 +1,62 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// This package generates openAPI definition file to be used in open API spec generation on API servers. To generate
+// definition for a specific type or package add "+k8s:openapi-gen=true" tag to the type/package comment lines. To
+// exclude a type from a tagged package, add "+k8s:openapi-gen=false" tag to the type comment lines.
+
+package main
+
+import (
+	"flag"
+	"log"
+
+	"github.com/spf13/pflag"
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/klog/v2"
+	"k8s.io/kube-openapi/cmd/openapi-gen/args"
+	"k8s.io/kube-openapi/pkg/generators"
+)
+
+func main() {
+	klog.InitFlags(nil)
+	args := args.New()
+
+	args.AddFlags(pflag.CommandLine)
+	flag.Set("logtostderr", "true")
+	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
+	pflag.Parse()
+
+	if err := args.Validate(); err != nil {
+		log.Fatalf("Arguments validation error: %v", err)
+	}
+
+	myTargets := func(context *generator.Context) []generator.Target {
+		return generators.GetTargets(context, args)
+	}
+
+	// Generates the code for the OpenAPIDefinitions.
+	if err := gengo.Execute(
+		generators.NameSystems(),
+		generators.DefaultNameSystem(),
+		myTargets,
+		gengo.StdBuildTag,
+		pflag.Args(),
+	); err != nil {
+		log.Fatalf("OpenAPI code generation error: %v", err)
+	}
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/common/common.go b/vendor/k8s.io/kube-openapi/pkg/common/common.go
index e4ce843b0..da2e8f11a 100644
--- a/vendor/k8s.io/kube-openapi/pkg/common/common.go
+++ b/vendor/k8s.io/kube-openapi/pkg/common/common.go
@@ -48,11 +48,11 @@ type GetOpenAPIDefinitions func(ReferenceCallback) map[string]OpenAPIDefinition
 // GetOpenAPITypeFormat for more information about trade-offs of using this interface or GetOpenAPITypeFormat method when
 // possible.
 type OpenAPIDefinitionGetter interface {
-	OpenAPIDefinition() *OpenAPIDefinition
+	OpenAPIDefinition() OpenAPIDefinition
 }
 
 type OpenAPIV3DefinitionGetter interface {
-	OpenAPIV3Definition() *OpenAPIDefinition
+	OpenAPIV3Definition() OpenAPIDefinition
 }
 
 type PathHandler interface {
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/README.md b/vendor/k8s.io/kube-openapi/pkg/generators/README.md
new file mode 100644
index 000000000..72b4e5fb4
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/README.md
@@ -0,0 +1,49 @@
+# Generate OpenAPI definitions
+
+- To generate definition for a specific type or package add "+k8s:openapi-gen=true" tag to the type/package comment lines.
+- To exclude a type or a member from a tagged package/type, add "+k8s:openapi-gen=false" tag to the comment lines.
+
+# OpenAPI Extensions
+
+OpenAPI spec can have extensions on types. To define one or more extensions on a type or its member
+add `+k8s:openapi-gen=x-kubernetes-$NAME:$VALUE` to the comment lines before type/member. A type/member can
+have multiple extensions. The rest of the line in the comment will be used as $VALUE so there is no need to
+escape or quote the value string. Extensions can be used to pass more information to client generators or
+documentation generators. For example a type might have a friendly name to be displayed in documentation or
+being used in a client's fluent interface.
+
+# Custom OpenAPI type definitions
+
+Custom types which otherwise don't map directly to OpenAPI can override their
+OpenAPI definition by implementing a function named "OpenAPIDefinition" with
+the following signature:
+
+```go
+	import openapi "k8s.io/kube-openapi/pkg/common"
+
+	// ...
+
+	type Time struct {
+		time.Time
+	}
+
+	func (_ Time) OpenAPIDefinition() openapi.OpenAPIDefinition {
+		return openapi.OpenAPIDefinition{
+			Schema: spec.Schema{
+				SchemaProps: spec.SchemaProps{
+					Type:   []string{"string"},
+					Format: "date-time",
+				},
+			},
+		}
+	}
+```
+
+Alternatively, the type can avoid the "openapi" import by defining the following
+methods. The following example produces the same OpenAPI definition as the
+example above:
+
+```go
+    func (_ Time) OpenAPISchemaType() []string { return []string{"string"} }
+    func (_ Time) OpenAPISchemaFormat() string { return "date-time" }
+```
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/api_linter.go b/vendor/k8s.io/kube-openapi/pkg/generators/api_linter.go
new file mode 100644
index 000000000..fc854a641
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/api_linter.go
@@ -0,0 +1,222 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"os"
+	"sort"
+
+	"k8s.io/kube-openapi/pkg/generators/rules"
+
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+)
+
+const apiViolationFileType = "api-violation"
+
+type apiViolationFile struct {
+	// Since our file actually is unrelated to the package structure, use a
+	// path that hasn't been mangled by the framework.
+	unmangledPath string
+}
+
+func (a apiViolationFile) AssembleFile(f *generator.File, path string) error {
+	path = a.unmangledPath
+	klog.V(2).Infof("Assembling file %q", path)
+	if path == "-" {
+		_, err := io.Copy(os.Stdout, &f.Body)
+		return err
+	}
+
+	output, err := os.Create(path)
+	if err != nil {
+		return err
+	}
+	defer output.Close()
+	_, err = io.Copy(output, &f.Body)
+	return err
+}
+
+func (a apiViolationFile) VerifyFile(f *generator.File, path string) error {
+	if path == "-" {
+		// Nothing to verify against.
+		return nil
+	}
+	path = a.unmangledPath
+
+	formatted := f.Body.Bytes()
+	existing, err := os.ReadFile(path)
+	if err != nil {
+		return fmt.Errorf("unable to read file %q for comparison: %v", path, err)
+	}
+	if bytes.Compare(formatted, existing) == 0 {
+		return nil
+	}
+
+	// Be nice and find the first place where they differ
+	// (Copied from gengo's default file type)
+	i := 0
+	for i < len(formatted) && i < len(existing) && formatted[i] == existing[i] {
+		i++
+	}
+	eDiff, fDiff := existing[i:], formatted[i:]
+	if len(eDiff) > 100 {
+		eDiff = eDiff[:100]
+	}
+	if len(fDiff) > 100 {
+		fDiff = fDiff[:100]
+	}
+	return fmt.Errorf("output for %q differs; first existing/expected diff: \n  %q\n  %q", path, string(eDiff), string(fDiff))
+}
+
+func newAPIViolationGen() *apiViolationGen {
+	return &apiViolationGen{
+		linter: newAPILinter(),
+	}
+}
+
+type apiViolationGen struct {
+	generator.GoGenerator
+
+	linter *apiLinter
+}
+
+func (v *apiViolationGen) FileType() string { return apiViolationFileType }
+func (v *apiViolationGen) Filename() string {
+	return "this file is ignored by the file assembler"
+}
+
+func (v *apiViolationGen) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
+	klog.V(5).Infof("validating API rules for type %v", t)
+	if err := v.linter.validate(t); err != nil {
+		return err
+	}
+	return nil
+}
+
+// Finalize prints the API rule violations to report file (if specified from
+// arguments) or stdout (default)
+func (v *apiViolationGen) Finalize(c *generator.Context, w io.Writer) error {
+	// NOTE: we don't return error here because we assume that the report file will
+	// get evaluated afterwards to determine if error should be raised. For example,
+	// you can have make rules that compare the report file with existing known
+	// violations (whitelist) and determine no error if no change is detected.
+	v.linter.report(w)
+	return nil
+}
+
+// apiLinter is the framework hosting multiple API rules and recording API rule
+// violations
+type apiLinter struct {
+	// API rules that implement APIRule interface and output API rule violations
+	rules      []APIRule
+	violations []apiViolation
+}
+
+// newAPILinter creates an apiLinter object with API rules in package rules. Please
+// add APIRule here when new API rule is implemented.
+func newAPILinter() *apiLinter {
+	return &apiLinter{
+		rules: []APIRule{
+			&rules.NamesMatch{},
+			&rules.OmitEmptyMatchCase{},
+			&rules.ListTypeMissing{},
+			&rules.StreamingListTypeFieldOrder{},
+			&rules.StreamingListTypeJSONTags{},
+			&rules.StreamingListTypeProtoTags{},
+		},
+	}
+}
+
+// apiViolation uniquely identifies single API rule violation
+type apiViolation struct {
+	// Name of rule from APIRule.Name()
+	rule string
+
+	packageName string
+	typeName    string
+
+	// Optional: name of field that violates API rule. Empty fieldName implies that
+	// the entire type violates the rule.
+	field string
+}
+
+// apiViolations implements sort.Interface for []apiViolation based on the fields: rule,
+// packageName, typeName and field.
+type apiViolations []apiViolation
+
+func (a apiViolations) Len() int      { return len(a) }
+func (a apiViolations) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a apiViolations) Less(i, j int) bool {
+	if a[i].rule != a[j].rule {
+		return a[i].rule < a[j].rule
+	}
+	if a[i].packageName != a[j].packageName {
+		return a[i].packageName < a[j].packageName
+	}
+	if a[i].typeName != a[j].typeName {
+		return a[i].typeName < a[j].typeName
+	}
+	return a[i].field < a[j].field
+}
+
+// APIRule is the interface for validating API rule on Go types
+type APIRule interface {
+	// Validate evaluates API rule on type t and returns a list of field names in
+	// the type that violate the rule. Empty field name [""] implies the entire
+	// type violates the rule.
+	Validate(t *types.Type) ([]string, error)
+
+	// Name returns the name of APIRule
+	Name() string
+}
+
+// validate runs all API rules on type t and records any API rule violation
+func (l *apiLinter) validate(t *types.Type) error {
+	for _, r := range l.rules {
+		klog.V(5).Infof("validating API rule %v for type %v", r.Name(), t)
+		fields, err := r.Validate(t)
+		if err != nil {
+			return err
+		}
+		for _, field := range fields {
+			l.violations = append(l.violations, apiViolation{
+				rule:        r.Name(),
+				packageName: t.Name.Package,
+				typeName:    t.Name.Name,
+				field:       field,
+			})
+		}
+	}
+	return nil
+}
+
+// report prints any API rule violation to writer w and returns error if violation exists
+func (l *apiLinter) report(w io.Writer) error {
+	sort.Sort(apiViolations(l.violations))
+	for _, v := range l.violations {
+		fmt.Fprintf(w, "API rule violation: %s,%s,%s,%s\n", v.rule, v.packageName, v.typeName, v.field)
+	}
+	if len(l.violations) > 0 {
+		return fmt.Errorf("API rule violations exist")
+	}
+	return nil
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/config.go b/vendor/k8s.io/kube-openapi/pkg/generators/config.go
new file mode 100644
index 000000000..1fbd77598
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/config.go
@@ -0,0 +1,84 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"path"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/klog/v2"
+	"k8s.io/kube-openapi/cmd/openapi-gen/args"
+)
+
+type identityNamer struct{}
+
+func (_ identityNamer) Name(t *types.Type) string {
+	return t.Name.String()
+}
+
+var _ namer.Namer = identityNamer{}
+
+// NameSystems returns the name system used by the generators in this package.
+func NameSystems() namer.NameSystems {
+	return namer.NameSystems{
+		"raw":           namer.NewRawNamer("", nil),
+		"sorting_namer": identityNamer{},
+	}
+}
+
+// DefaultNameSystem returns the default name system for ordering the types to be
+// processed by the generators in this package.
+func DefaultNameSystem() string {
+	return "sorting_namer"
+}
+
+func GetTargets(context *generator.Context, args *args.Args) []generator.Target {
+	boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, gengo.StdBuildTag, gengo.StdGeneratedBy)
+	if err != nil {
+		klog.Fatalf("Failed loading boilerplate: %v", err)
+	}
+
+	reportPath := "-"
+	if args.ReportFilename != "" {
+		reportPath = args.ReportFilename
+	}
+	context.FileTypes[apiViolationFileType] = apiViolationFile{
+		unmangledPath: reportPath,
+	}
+
+	return []generator.Target{
+		&generator.SimpleTarget{
+			PkgName:       path.Base(args.OutputPkg), // `path` vs. `filepath` because packages use '/'
+			PkgPath:       args.OutputPkg,
+			PkgDir:        args.OutputDir,
+			HeaderComment: boilerplate,
+			GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) {
+				return []generator.Generator{
+					newOpenAPIGen(
+						args.OutputFile,
+						args.OutputPkg,
+					),
+					newAPIViolationGen(),
+				}
+			},
+			FilterFunc: apiTypeFilterFunc,
+		},
+	}
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/enum.go b/vendor/k8s.io/kube-openapi/pkg/generators/enum.go
new file mode 100644
index 000000000..3db034d6c
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/enum.go
@@ -0,0 +1,177 @@
+/*
+Copyright 2021 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"fmt"
+	"regexp"
+	"sort"
+	"strings"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/types"
+)
+
+const tagEnumType = "enum"
+const enumTypeDescriptionHeader = "Possible enum values:"
+
+type enumValue struct {
+	Name    string
+	Value   string
+	Comment string
+}
+
+type enumType struct {
+	Name   types.Name
+	Values []*enumValue
+}
+
+// enumMap is a map from the name to the matching enum type.
+type enumMap map[types.Name]*enumType
+
+type enumContext struct {
+	enumTypes enumMap
+}
+
+func newEnumContext(c *generator.Context) *enumContext {
+	return &enumContext{enumTypes: parseEnums(c)}
+}
+
+// EnumType checks and finds the enumType for a given type.
+// If the given type is a known enum type, returns the enumType, true
+// Otherwise, returns nil, false
+func (ec *enumContext) EnumType(t *types.Type) (enum *enumType, isEnum bool) {
+	// if t is a pointer, use its underlying type instead
+	if t.Kind == types.Pointer {
+		t = t.Elem
+	}
+	enum, ok := ec.enumTypes[t.Name]
+	return enum, ok
+}
+
+// ValueStrings returns all possible values of the enum type as strings
+// the results are sorted and quoted as Go literals.
+func (et *enumType) ValueStrings() []string {
+	var values []string
+	for _, value := range et.Values {
+		// use "%q" format to generate a Go literal of the string const value
+		values = append(values, fmt.Sprintf("%q", value.Value))
+	}
+	sort.Strings(values)
+	return values
+}
+
+// DescriptionLines returns a description of the enum in this format:
+//
+// Possible enum values:
+//   - `"value1"` description 1
+//   - `"value2"` description 2
+func (et *enumType) DescriptionLines() []string {
+	if len(et.Values) == 0 {
+		return nil
+	}
+	var lines []string
+	for _, value := range et.Values {
+		lines = append(lines, value.Description())
+	}
+	sort.Strings(lines)
+	// Prepend an empty string to initiate a new paragraph.
+	return append([]string{"", enumTypeDescriptionHeader}, lines...)
+}
+
+func parseEnums(c *generator.Context) enumMap {
+	// First, find the builtin "string" type
+	stringType := c.Universe.Type(types.Name{Name: "string"})
+
+	// find all enum types.
+	enumTypes := make(enumMap)
+	for _, p := range c.Universe {
+		for _, t := range p.Types {
+			if isEnumType(stringType, t) {
+				if _, ok := enumTypes[t.Name]; !ok {
+					enumTypes[t.Name] = &enumType{
+						Name: t.Name,
+					}
+				}
+			}
+		}
+	}
+
+	// find all enum values from constants, and try to match each with its type.
+	for _, p := range c.Universe {
+		for _, c := range p.Constants {
+			enumType := c.Underlying
+			if _, ok := enumTypes[enumType.Name]; ok {
+				value := &enumValue{
+					Name:    c.Name.Name,
+					Value:   *c.ConstValue,
+					Comment: strings.Join(c.CommentLines, " "),
+				}
+				enumTypes[enumType.Name].addIfNotPresent(value)
+			}
+		}
+	}
+
+	return enumTypes
+}
+
+func (et *enumType) addIfNotPresent(value *enumValue) {
+	// If we already have an enum case with the same value, then ignore this new
+	// one. This can happen if an enum aliases one from another package and
+	// re-exports the cases.
+	for i, existing := range et.Values {
+		if existing.Value == value.Value {
+
+			// Take the value of the longer comment (or some other deterministic tie breaker)
+			if len(existing.Comment) < len(value.Comment) || (len(existing.Comment) == len(value.Comment) && existing.Comment > value.Comment) {
+				et.Values[i] = value
+			}
+
+			return
+		}
+	}
+	et.Values = append(et.Values, value)
+}
+
+// Description returns the description line for the enumValue
+// with the format:
+//   - `"FooValue"` is the Foo value
+func (ev *enumValue) Description() string {
+	comment := strings.TrimSpace(ev.Comment)
+	// The comment should starts with the type name, trim it first.
+	comment = strings.TrimPrefix(comment, ev.Name)
+	// Trim the possible space after previous step.
+	comment = strings.TrimSpace(comment)
+	// The comment may be multiline, cascade all consecutive whitespaces.
+	comment = whitespaceRegex.ReplaceAllString(comment, " ")
+	return fmt.Sprintf(" - `%q` %s", ev.Value, comment)
+}
+
+// isEnumType checks if a given type is an enum by the definition
+// An enum type should be an alias of string and has tag '+enum' in its comment.
+// Additionally, pass the type of builtin 'string' to check against.
+func isEnumType(stringType *types.Type, t *types.Type) bool {
+	return t.Kind == types.Alias && t.Underlying == stringType && hasEnumTag(t)
+}
+
+func hasEnumTag(t *types.Type) bool {
+	return gengo.ExtractCommentTags("+", t.CommentLines)[tagEnumType] != nil
+}
+
+// whitespaceRegex is the regex for consecutive whitespaces.
+var whitespaceRegex = regexp.MustCompile(`\s+`)
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/extension.go b/vendor/k8s.io/kube-openapi/pkg/generators/extension.go
new file mode 100644
index 000000000..42d385416
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/extension.go
@@ -0,0 +1,203 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"fmt"
+	"sort"
+	"strings"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/types"
+	"k8s.io/kube-openapi/pkg/util/sets"
+)
+
+const extensionPrefix = "x-kubernetes-"
+
+// extensionAttributes encapsulates common traits for particular extensions.
+type extensionAttributes struct {
+	xName         string
+	kind          types.Kind
+	allowedValues sets.String
+	enforceArray  bool
+}
+
+// Extension tag to openapi extension attributes
+var tagToExtension = map[string]extensionAttributes{
+	"patchMergeKey": {
+		xName: "x-kubernetes-patch-merge-key",
+		kind:  types.Slice,
+	},
+	"patchStrategy": {
+		xName:         "x-kubernetes-patch-strategy",
+		kind:          types.Slice,
+		allowedValues: sets.NewString("merge", "retainKeys"),
+	},
+	"listMapKey": {
+		xName:        "x-kubernetes-list-map-keys",
+		kind:         types.Slice,
+		enforceArray: true,
+	},
+	"listType": {
+		xName:         "x-kubernetes-list-type",
+		kind:          types.Slice,
+		allowedValues: sets.NewString("atomic", "set", "map"),
+	},
+	"mapType": {
+		xName:         "x-kubernetes-map-type",
+		kind:          types.Map,
+		allowedValues: sets.NewString("atomic", "granular"),
+	},
+	"structType": {
+		xName:         "x-kubernetes-map-type",
+		kind:          types.Struct,
+		allowedValues: sets.NewString("atomic", "granular"),
+	},
+	"validations": {
+		xName: "x-kubernetes-validations",
+		kind:  types.Slice,
+	},
+}
+
+// Extension encapsulates information necessary to generate an OpenAPI extension.
+type extension struct {
+	idlTag string   // Example: listType
+	xName  string   // Example: x-kubernetes-list-type
+	values []string // Example: [atomic]
+}
+
+func (e extension) hasAllowedValues() bool {
+	return tagToExtension[e.idlTag].allowedValues.Len() > 0
+}
+
+func (e extension) allowedValues() sets.String {
+	return tagToExtension[e.idlTag].allowedValues
+}
+
+func (e extension) hasKind() bool {
+	return len(tagToExtension[e.idlTag].kind) > 0
+}
+
+func (e extension) kind() types.Kind {
+	return tagToExtension[e.idlTag].kind
+}
+
+func (e extension) validateAllowedValues() error {
+	// allowedValues not set means no restrictions on values.
+	if !e.hasAllowedValues() {
+		return nil
+	}
+	// Check for missing value.
+	if len(e.values) == 0 {
+		return fmt.Errorf("%s needs a value, none given.", e.idlTag)
+	}
+	// For each extension value, validate that it is allowed.
+	allowedValues := e.allowedValues()
+	if !allowedValues.HasAll(e.values...) {
+		return fmt.Errorf("%v not allowed for %s. Allowed values: %v",
+			e.values, e.idlTag, allowedValues.List())
+	}
+	return nil
+}
+
+func (e extension) validateType(kind types.Kind) error {
+	// If this extension class has no kind, then don't validate the type.
+	if !e.hasKind() {
+		return nil
+	}
+	if kind != e.kind() {
+		return fmt.Errorf("tag %s on type %v; only allowed on type %v",
+			e.idlTag, kind, e.kind())
+	}
+	return nil
+}
+
+func (e extension) hasMultipleValues() bool {
+	return len(e.values) > 1
+}
+
+func (e extension) isAlwaysArrayFormat() bool {
+	return tagToExtension[e.idlTag].enforceArray
+}
+
+// Returns sorted list of map keys. Needed for deterministic testing.
+func sortedMapKeys(m map[string][]string) []string {
+	keys := make([]string, len(m))
+	i := 0
+	for k := range m {
+		keys[i] = k
+		i++
+	}
+	sort.Strings(keys)
+	return keys
+}
+
+// Parses comments to return openapi extensions. Returns a list of
+// extensions which parsed correctly, as well as a list of the
+// parse errors. Validating extensions is performed separately.
+// NOTE: Non-empty errors does not mean extensions is empty.
+func parseExtensions(comments []string) ([]extension, []error) {
+	extensions := []extension{}
+	errors := []error{}
+	// First, generate extensions from "+k8s:openapi-gen=x-kubernetes-*" annotations.
+	values := getOpenAPITagValue(comments)
+	for _, val := range values {
+		// Example: x-kubernetes-member-tag:member_test
+		if strings.HasPrefix(val, extensionPrefix) {
+			parts := strings.SplitN(val, ":", 2)
+			if len(parts) != 2 {
+				errors = append(errors, fmt.Errorf("invalid extension value: %v", val))
+				continue
+			}
+			e := extension{
+				idlTag: tagName,            // Example: k8s:openapi-gen
+				xName:  parts[0],           // Example: x-kubernetes-member-tag
+				values: []string{parts[1]}, // Example: member_test
+			}
+			extensions = append(extensions, e)
+		}
+	}
+	// Next, generate extensions from "idlTags" (e.g. +listType)
+	tagValues := gengo.ExtractCommentTags("+", comments)
+	for _, idlTag := range sortedMapKeys(tagValues) {
+		xAttrs, exists := tagToExtension[idlTag]
+		if !exists {
+			continue
+		}
+		values := tagValues[idlTag]
+		e := extension{
+			idlTag: idlTag,       // listType
+			xName:  xAttrs.xName, // x-kubernetes-list-type
+			values: values,       // [atomic]
+		}
+		extensions = append(extensions, e)
+	}
+	return extensions, errors
+}
+
+func validateMemberExtensions(extensions []extension, m *types.Member) []error {
+	errors := []error{}
+	for _, e := range extensions {
+		if err := e.validateAllowedValues(); err != nil {
+			errors = append(errors, err)
+		}
+		if err := e.validateType(m.Type.Kind); err != nil {
+			errors = append(errors, err)
+		}
+	}
+	return errors
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/markers.go b/vendor/k8s.io/kube-openapi/pkg/generators/markers.go
new file mode 100644
index 000000000..a8af60b6c
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/markers.go
@@ -0,0 +1,799 @@
+/*
+Copyright 2022 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"reflect"
+	"regexp"
+	"strconv"
+	"strings"
+	"sync"
+
+	"k8s.io/gengo/v2/types"
+	openapi "k8s.io/kube-openapi/pkg/common"
+	"k8s.io/kube-openapi/pkg/validation/spec"
+)
+
+type CELTag struct {
+	Rule              string `json:"rule,omitempty"`
+	Message           string `json:"message,omitempty"`
+	MessageExpression string `json:"messageExpression,omitempty"`
+	OptionalOldSelf   *bool  `json:"optionalOldSelf,omitempty"`
+	Reason            string `json:"reason,omitempty"`
+	FieldPath         string `json:"fieldPath,omitempty"`
+}
+
+func (c *CELTag) Validate() error {
+	if c == nil || *c == (CELTag{}) {
+		return fmt.Errorf("empty CEL tag is not allowed")
+	}
+
+	var errs []error
+	if c.Rule == "" {
+		errs = append(errs, fmt.Errorf("rule cannot be empty"))
+	}
+	if c.Message == "" && c.MessageExpression == "" {
+		errs = append(errs, fmt.Errorf("message or messageExpression must be set"))
+	}
+	if c.Message != "" && c.MessageExpression != "" {
+		errs = append(errs, fmt.Errorf("message and messageExpression cannot be set at the same time"))
+	}
+
+	if len(errs) > 0 {
+		return errors.Join(errs...)
+	}
+
+	return nil
+}
+
+// isKnownTagCommentKey returns true if the given key is a known comment tag key.
+// Known keys are identified by the json field tags in the commentTags struct.
+// If the key is a composite key, only the first key part is checked, and is
+// expected to be separated by the remainder of the key by a ':' or '[' delimiter.
+func isKnownTagCommentKey(key string) bool {
+	split := func(r rune) bool { return r == ':' || r == '[' }
+	commentTags := strings.FieldsFunc(key, split)
+	if len(commentTags) == 0 {
+		return false
+	}
+	_, ok := tagKeys()[commentTags[0]]
+	return ok
+}
+
+var tagKeys = sync.OnceValue(func() map[string]struct{} {
+	result := map[string]struct{}{}
+	t := reflect.TypeOf(commentTags{})
+	for i := 0; i < t.NumField(); i++ {
+		field := t.Field(i)
+		if jsonTag := field.Tag.Get("json"); jsonTag != "" {
+			if key, _, _ := strings.Cut(jsonTag, ","); key != "" {
+				result[key] = struct{}{}
+			}
+		}
+	}
+	return result
+})
+
+// commentTags represents the parsed comment tags for a given type. These types are then used to generate schema validations.
+// These only include the newer prefixed tags. The older tags are still supported,
+// but are not included in this struct. Comment Tags are transformed into a
+// *spec.Schema, which is then combined with the older marker comments to produce
+// the generated OpenAPI spec.
+//
+// List of tags not included in this struct:
+//
+// - +optional
+// - +default
+// - +listType
+// - +listMapKeys
+// - +mapType
+type commentTags struct {
+	Nullable         *bool         `json:"nullable,omitempty"`
+	Format           *string       `json:"format,omitempty"`
+	Maximum          *float64      `json:"maximum,omitempty"`
+	ExclusiveMaximum *bool         `json:"exclusiveMaximum,omitempty"`
+	Minimum          *float64      `json:"minimum,omitempty"`
+	ExclusiveMinimum *bool         `json:"exclusiveMinimum,omitempty"`
+	MaxLength        *int64        `json:"maxLength,omitempty"`
+	MinLength        *int64        `json:"minLength,omitempty"`
+	Pattern          *string       `json:"pattern,omitempty"`
+	MaxItems         *int64        `json:"maxItems,omitempty"`
+	MinItems         *int64        `json:"minItems,omitempty"`
+	UniqueItems      *bool         `json:"uniqueItems,omitempty"`
+	MultipleOf       *float64      `json:"multipleOf,omitempty"`
+	Enum             []interface{} `json:"enum,omitempty"`
+	MaxProperties    *int64        `json:"maxProperties,omitempty"`
+	MinProperties    *int64        `json:"minProperties,omitempty"`
+
+	// Nested commentTags for extending the schemas of subfields at point-of-use
+	// when you cant annotate them directly. Cannot be used to add properties
+	// or remove validations on the overridden schema.
+	Items                *commentTags            `json:"items,omitempty"`
+	Properties           map[string]*commentTags `json:"properties,omitempty"`
+	AdditionalProperties *commentTags            `json:"additionalProperties,omitempty"`
+
+	CEL []CELTag `json:"cel,omitempty"`
+
+	// Future markers can all be parsed into this centralized struct...
+	// Optional bool `json:"optional,omitempty"`
+	// Default  any  `json:"default,omitempty"`
+}
+
+// Returns the schema for the given CommentTags instance.
+// This is the final authoritative schema for the comment tags
+func (c *commentTags) ValidationSchema() (*spec.Schema, error) {
+	if c == nil {
+		return nil, nil
+	}
+
+	isNullable := c.Nullable != nil && *c.Nullable
+	format := ""
+	if c.Format != nil {
+		format = *c.Format
+	}
+	isExclusiveMaximum := c.ExclusiveMaximum != nil && *c.ExclusiveMaximum
+	isExclusiveMinimum := c.ExclusiveMinimum != nil && *c.ExclusiveMinimum
+	isUniqueItems := c.UniqueItems != nil && *c.UniqueItems
+	pattern := ""
+	if c.Pattern != nil {
+		pattern = *c.Pattern
+	}
+
+	var transformedItems *spec.SchemaOrArray
+	var transformedProperties map[string]spec.Schema
+	var transformedAdditionalProperties *spec.SchemaOrBool
+
+	if c.Items != nil {
+		items, err := c.Items.ValidationSchema()
+		if err != nil {
+			return nil, fmt.Errorf("failed to transform items: %w", err)
+		}
+		transformedItems = &spec.SchemaOrArray{Schema: items}
+	}
+
+	if c.Properties != nil {
+		properties := make(map[string]spec.Schema)
+		for key, value := range c.Properties {
+			property, err := value.ValidationSchema()
+			if err != nil {
+				return nil, fmt.Errorf("failed to transform property %q: %w", key, err)
+			}
+			properties[key] = *property
+		}
+		transformedProperties = properties
+	}
+
+	if c.AdditionalProperties != nil {
+		additionalProperties, err := c.AdditionalProperties.ValidationSchema()
+		if err != nil {
+			return nil, fmt.Errorf("failed to transform additionalProperties: %w", err)
+		}
+		transformedAdditionalProperties = &spec.SchemaOrBool{Schema: additionalProperties, Allows: true}
+	}
+
+	res := spec.Schema{
+		SchemaProps: spec.SchemaProps{
+			Nullable:         isNullable,
+			Format:           format,
+			Maximum:          c.Maximum,
+			ExclusiveMaximum: isExclusiveMaximum,
+			Minimum:          c.Minimum,
+			ExclusiveMinimum: isExclusiveMinimum,
+			MaxLength:        c.MaxLength,
+			MinLength:        c.MinLength,
+			Pattern:          pattern,
+			MaxItems:         c.MaxItems,
+			MinItems:         c.MinItems,
+			UniqueItems:      isUniqueItems,
+			MultipleOf:       c.MultipleOf,
+			Enum:             c.Enum,
+			MaxProperties:    c.MaxProperties,
+			MinProperties:    c.MinProperties,
+		},
+	}
+
+	if len(c.CEL) > 0 {
+		// Convert the CELTag to a map[string]interface{} via JSON
+		celTagJSON, err := json.Marshal(c.CEL)
+		if err != nil {
+			return nil, fmt.Errorf("failed to marshal CEL tag: %w", err)
+		}
+		var celTagMap []interface{}
+		if err := json.Unmarshal(celTagJSON, &celTagMap); err != nil {
+			return nil, fmt.Errorf("failed to unmarshal CEL tag: %w", err)
+		}
+
+		res.VendorExtensible.AddExtension("x-kubernetes-validations", celTagMap)
+	}
+
+	// Dont add structural properties directly to this schema. This schema
+	// is used only for validation.
+	if transformedItems != nil || len(transformedProperties) > 0 || transformedAdditionalProperties != nil {
+		res.AllOf = append(res.AllOf, spec.Schema{
+			SchemaProps: spec.SchemaProps{
+				Items:                transformedItems,
+				Properties:           transformedProperties,
+				AdditionalProperties: transformedAdditionalProperties,
+			},
+		})
+	}
+
+	return &res, nil
+}
+
+// validates the parameters in a CommentTags instance. Returns any errors encountered.
+func (c commentTags) Validate() error {
+
+	var err error
+
+	if c.MinLength != nil && *c.MinLength < 0 {
+		err = errors.Join(err, fmt.Errorf("minLength cannot be negative"))
+	}
+	if c.MaxLength != nil && *c.MaxLength < 0 {
+		err = errors.Join(err, fmt.Errorf("maxLength cannot be negative"))
+	}
+	if c.MinItems != nil && *c.MinItems < 0 {
+		err = errors.Join(err, fmt.Errorf("minItems cannot be negative"))
+	}
+	if c.MaxItems != nil && *c.MaxItems < 0 {
+		err = errors.Join(err, fmt.Errorf("maxItems cannot be negative"))
+	}
+	if c.MinProperties != nil && *c.MinProperties < 0 {
+		err = errors.Join(err, fmt.Errorf("minProperties cannot be negative"))
+	}
+	if c.MaxProperties != nil && *c.MaxProperties < 0 {
+		err = errors.Join(err, fmt.Errorf("maxProperties cannot be negative"))
+	}
+	if c.Minimum != nil && c.Maximum != nil && *c.Minimum > *c.Maximum {
+		err = errors.Join(err, fmt.Errorf("minimum %f is greater than maximum %f", *c.Minimum, *c.Maximum))
+	}
+	if (c.ExclusiveMinimum != nil || c.ExclusiveMaximum != nil) && c.Minimum != nil && c.Maximum != nil && *c.Minimum == *c.Maximum {
+		err = errors.Join(err, fmt.Errorf("exclusiveMinimum/Maximum cannot be set when minimum == maximum"))
+	}
+	if c.MinLength != nil && c.MaxLength != nil && *c.MinLength > *c.MaxLength {
+		err = errors.Join(err, fmt.Errorf("minLength %d is greater than maxLength %d", *c.MinLength, *c.MaxLength))
+	}
+	if c.MinItems != nil && c.MaxItems != nil && *c.MinItems > *c.MaxItems {
+		err = errors.Join(err, fmt.Errorf("minItems %d is greater than maxItems %d", *c.MinItems, *c.MaxItems))
+	}
+	if c.MinProperties != nil && c.MaxProperties != nil && *c.MinProperties > *c.MaxProperties {
+		err = errors.Join(err, fmt.Errorf("minProperties %d is greater than maxProperties %d", *c.MinProperties, *c.MaxProperties))
+	}
+	if c.Pattern != nil {
+		_, e := regexp.Compile(*c.Pattern)
+		if e != nil {
+			err = errors.Join(err, fmt.Errorf("invalid pattern %q: %v", *c.Pattern, e))
+		}
+	}
+	if c.MultipleOf != nil && *c.MultipleOf == 0 {
+		err = errors.Join(err, fmt.Errorf("multipleOf cannot be 0"))
+	}
+
+	for i, celTag := range c.CEL {
+		celError := celTag.Validate()
+		if celError == nil {
+			continue
+		}
+		err = errors.Join(err, fmt.Errorf("invalid CEL tag at index %d: %w", i, celError))
+	}
+
+	return err
+}
+
+// Performs type-specific validation for CommentTags porameters. Accepts a Type instance and returns any errors encountered during validation.
+func (c commentTags) ValidateType(t *types.Type) error {
+	var err error
+
+	resolvedType := resolveAliasAndPtrType(t)
+	typeString, _ := openapi.OpenAPITypeFormat(resolvedType.String()) // will be empty for complicated types
+
+	// Structs and interfaces may dynamically be any type, so we cant validate them
+	// easily.
+	if resolvedType.Kind == types.Interface || resolvedType.Kind == types.Struct {
+		// Skip validation for structs and interfaces which implement custom
+		// overrides
+		//
+		// Only check top-level t type without resolving alias to mirror generator
+		// behavior. Generator only checks the top level type without resolving
+		// alias. The `has*Method` functions can be changed to add this behavior in the
+		// future if needed.
+		elemT := resolvePtrType(t)
+		if hasOpenAPIDefinitionMethod(elemT) ||
+			hasOpenAPIDefinitionMethods(elemT) ||
+			hasOpenAPIV3DefinitionMethod(elemT) ||
+			hasOpenAPIV3OneOfMethod(elemT) {
+
+			return nil
+		}
+	}
+
+	isArray := resolvedType.Kind == types.Slice || resolvedType.Kind == types.Array
+	isMap := resolvedType.Kind == types.Map
+	isString := typeString == "string"
+	isInt := typeString == "integer"
+	isFloat := typeString == "number"
+	isStruct := resolvedType.Kind == types.Struct
+
+	if c.MaxItems != nil && !isArray {
+		err = errors.Join(err, fmt.Errorf("maxItems can only be used on array types"))
+	}
+	if c.MinItems != nil && !isArray {
+		err = errors.Join(err, fmt.Errorf("minItems can only be used on array types"))
+	}
+	if c.UniqueItems != nil && !isArray {
+		err = errors.Join(err, fmt.Errorf("uniqueItems can only be used on array types"))
+	}
+	if c.MaxProperties != nil && !(isMap || isStruct) {
+		err = errors.Join(err, fmt.Errorf("maxProperties can only be used on map types"))
+	}
+	if c.MinProperties != nil && !(isMap || isStruct) {
+		err = errors.Join(err, fmt.Errorf("minProperties can only be used on map types"))
+	}
+	if c.MinLength != nil && !isString {
+		err = errors.Join(err, fmt.Errorf("minLength can only be used on string types"))
+	}
+	if c.MaxLength != nil && !isString {
+		err = errors.Join(err, fmt.Errorf("maxLength can only be used on string types"))
+	}
+	if c.Pattern != nil && !isString {
+		err = errors.Join(err, fmt.Errorf("pattern can only be used on string types"))
+	}
+	if c.Minimum != nil && !isInt && !isFloat {
+		err = errors.Join(err, fmt.Errorf("minimum can only be used on numeric types"))
+	}
+	if c.Maximum != nil && !isInt && !isFloat {
+		err = errors.Join(err, fmt.Errorf("maximum can only be used on numeric types"))
+	}
+	if c.MultipleOf != nil && !isInt && !isFloat {
+		err = errors.Join(err, fmt.Errorf("multipleOf can only be used on numeric types"))
+	}
+	if c.ExclusiveMinimum != nil && !isInt && !isFloat {
+		err = errors.Join(err, fmt.Errorf("exclusiveMinimum can only be used on numeric types"))
+	}
+	if c.ExclusiveMaximum != nil && !isInt && !isFloat {
+		err = errors.Join(err, fmt.Errorf("exclusiveMaximum can only be used on numeric types"))
+	}
+	if c.AdditionalProperties != nil && !isMap {
+		err = errors.Join(err, fmt.Errorf("additionalProperties can only be used on map types"))
+
+		if err == nil {
+			err = errors.Join(err, c.AdditionalProperties.ValidateType(t))
+		}
+	}
+	if c.Items != nil && !isArray {
+		err = errors.Join(err, fmt.Errorf("items can only be used on array types"))
+
+		if err == nil {
+			err = errors.Join(err, c.Items.ValidateType(t))
+		}
+	}
+	if c.Properties != nil {
+		if !isStruct && !isMap {
+			err = errors.Join(err, fmt.Errorf("properties can only be used on struct types"))
+		} else if isStruct && err == nil {
+			for key, tags := range c.Properties {
+				if member := memberWithJSONName(resolvedType, key); member == nil {
+					err = errors.Join(err, fmt.Errorf("property used in comment tag %q not found in struct %s", key, resolvedType.String()))
+				} else if nestedErr := tags.ValidateType(member.Type); nestedErr != nil {
+					err = errors.Join(err, fmt.Errorf("failed to validate property %q: %w", key, nestedErr))
+				}
+			}
+		}
+	}
+
+	return err
+}
+
+func memberWithJSONName(t *types.Type, key string) *types.Member {
+	for _, member := range t.Members {
+		tags := getJsonTags(&member)
+		if len(tags) > 0 && tags[0] == key {
+			return &member
+		} else if member.Embedded {
+			if embeddedMember := memberWithJSONName(member.Type, key); embeddedMember != nil {
+				return embeddedMember
+			}
+		}
+	}
+	return nil
+}
+
+// ParseCommentTags parses the given comments into a CommentTags type. Validates the parsed comment tags, and returns the result.
+// Accepts an optional type to validate against, and a prefix to filter out markers not related to validation.
+// Accepts a prefix to filter out markers not related to validation.
+// Returns any errors encountered while parsing or validating the comment tags.
+func ParseCommentTags(t *types.Type, comments []string, prefix string) (*spec.Schema, error) {
+	markers, err := parseMarkers(comments, prefix)
+	if err != nil {
+		return nil, fmt.Errorf("failed to parse marker comments: %w", err)
+	}
+	nested, err := nestMarkers(markers)
+	if err != nil {
+		return nil, fmt.Errorf("invalid marker comments: %w", err)
+	}
+
+	// Parse the map into a CommentTags type by marshalling and unmarshalling
+	// as JSON in leiu of an unstructured converter.
+	out, err := json.Marshal(nested)
+	if err != nil {
+		return nil, fmt.Errorf("failed to marshal marker comments: %w", err)
+	}
+
+	var commentTags commentTags
+	if err = json.Unmarshal(out, &commentTags); err != nil {
+		return nil, fmt.Errorf("failed to unmarshal marker comments: %w", err)
+	}
+
+	// Validate the parsed comment tags
+	validationErrors := commentTags.Validate()
+
+	if t != nil {
+		validationErrors = errors.Join(validationErrors, commentTags.ValidateType(t))
+	}
+
+	if validationErrors != nil {
+		return nil, fmt.Errorf("invalid marker comments: %w", validationErrors)
+	}
+
+	return commentTags.ValidationSchema()
+}
+
+var (
+	allowedKeyCharacterSet = `[:_a-zA-Z0-9\[\]\-]`
+	valueEmpty             = regexp.MustCompile(fmt.Sprintf(`^(%s*)$`, allowedKeyCharacterSet))
+	valueAssign            = regexp.MustCompile(fmt.Sprintf(`^(%s*)=(.*)$`, allowedKeyCharacterSet))
+	valueRawString         = regexp.MustCompile(fmt.Sprintf(`^(%s*)>(.*)$`, allowedKeyCharacterSet))
+)
+
+// extractCommentTags parses comments for lines of the form:
+//
+//	'marker' + "key=value"
+//
+//	or to specify truthy boolean keys:
+//
+//	'marker' + "key"
+//
+// Values are optional; "" is the default.  A tag can be specified more than
+// one time and all values are returned.  Returns a map with an entry for
+// for each key and a value.
+//
+// Similar to version from gengo, but this version support only allows one
+// value per key (preferring explicit array indices), supports raw strings
+// with concatenation, and limits the usable characters allowed in a key
+// (for simpler parsing).
+//
+// Assignments and empty values have the same syntax as from gengo. Raw strings
+// have the syntax:
+//
+//	'marker' + "key>value"
+//	'marker' + "key>value"
+//
+// Successive usages of the same raw string key results in concatenating each
+// line with `\n` in between. It is an error to use `=` to assing to a previously
+// assigned key
+// (in contrast to types.ExtractCommentTags which allows array-typed
+// values to be specified using `=`).
+func extractCommentTags(marker string, lines []string) (map[string]string, error) {
+	out := map[string]string{}
+
+	// Used to track the the line immediately prior to the one being iterated.
+	// If there was an invalid or ignored line, these values get reset.
+	lastKey := ""
+	lastIndex := -1
+	lastArrayKey := ""
+
+	var lintErrors []error
+
+	for _, line := range lines {
+		line = strings.Trim(line, " ")
+
+		// Track the current value of the last vars to use in this loop iteration
+		// before they are reset for the next iteration.
+		previousKey := lastKey
+		previousArrayKey := lastArrayKey
+		previousIndex := lastIndex
+
+		// Make sure last vars gets reset if we `continue`
+		lastIndex = -1
+		lastArrayKey = ""
+		lastKey = ""
+
+		if len(line) == 0 {
+			continue
+		} else if !strings.HasPrefix(line, marker) {
+			continue
+		}
+
+		line = strings.TrimPrefix(line, marker)
+
+		key := ""
+		value := ""
+
+		if matches := valueAssign.FindStringSubmatch(line); matches != nil {
+			key = matches[1]
+			value = matches[2]
+
+			// If key exists, throw error.
+			// Some of the old kube open-api gen marker comments like
+			// `+listMapKeys` allowed a list to be specified by writing key=value
+			// multiple times.
+			//
+			// This is not longer supported for the prefixed marker comments.
+			// This is to prevent confusion with the new array syntax which
+			// supports lists of objects.
+			//
+			// The old marker comments like +listMapKeys will remain functional,
+			// but new markers will not support it.
+			if _, ok := out[key]; ok {
+				return nil, fmt.Errorf("cannot have multiple values for key '%v'", key)
+			}
+
+		} else if matches := valueEmpty.FindStringSubmatch(line); matches != nil {
+			key = matches[1]
+			value = ""
+
+		} else if matches := valueRawString.FindStringSubmatch(line); matches != nil {
+			toAdd := strings.Trim(string(matches[2]), " ")
+
+			key = matches[1]
+
+			// First usage as a raw string.
+			if existing, exists := out[key]; !exists {
+
+				// Encode the raw string as JSON to ensure that it is properly escaped.
+				valueBytes, err := json.Marshal(toAdd)
+				if err != nil {
+					return nil, fmt.Errorf("invalid value for key %v: %w", key, err)
+				}
+
+				value = string(valueBytes)
+			} else if key != previousKey {
+				// Successive usages of the same key of a raw string must be
+				// consecutive
+				return nil, fmt.Errorf("concatenations to key '%s' must be consecutive with its assignment", key)
+			} else {
+				// If it is a consecutive repeat usage, concatenate to the
+				// existing value.
+				//
+				// Decode JSON string, append to it, re-encode JSON string.
+				// Kinda janky but this is a code-generator...
+				var unmarshalled string
+				if err := json.Unmarshal([]byte(existing), &unmarshalled); err != nil {
+					return nil, fmt.Errorf("invalid value for key %v: %w", key, err)
+				} else {
+					unmarshalled += "\n" + toAdd
+					valueBytes, err := json.Marshal(unmarshalled)
+					if err != nil {
+						return nil, fmt.Errorf("invalid value for key %v: %w", key, err)
+					}
+
+					value = string(valueBytes)
+				}
+			}
+		} else {
+			// Comment has the correct prefix, but incorrect syntax, so it is an
+			// error
+			return nil, fmt.Errorf("invalid marker comment does not match expected `+key=` pattern: %v", line)
+		}
+
+		out[key] = value
+		lastKey = key
+
+		// Lint the array subscript for common mistakes. This only lints the last
+		// array index used, (since we do not have a need for nested arrays yet
+		// in markers)
+		if arrayPath, index, hasSubscript, err := extractArraySubscript(key); hasSubscript {
+			// If index is non-zero, check that that previous line was for the same
+			// key and either the same or previous index
+			if err != nil {
+				lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: expected integer index in key '%v'", line, key))
+			} else if previousArrayKey != arrayPath && index != 0 {
+				lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: non-consecutive index %v for key '%v'", line, index, arrayPath))
+			} else if index != previousIndex+1 && index != previousIndex {
+				lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: non-consecutive index %v for key '%v'", line, index, arrayPath))
+			}
+
+			lastIndex = index
+			lastArrayKey = arrayPath
+		}
+	}
+
+	if len(lintErrors) > 0 {
+		return nil, errors.Join(lintErrors...)
+	}
+
+	return out, nil
+}
+
+// Extracts and parses the given marker comments into a map of key -> value.
+// Accepts a prefix to filter out markers not related to validation.
+// The prefix is removed from the key in the returned map.
+// Empty keys and invalid values will return errors, refs are currently unsupported and will be skipped.
+func parseMarkers(markerComments []string, prefix string) (map[string]any, error) {
+	markers, err := extractCommentTags(prefix, markerComments)
+	if err != nil {
+		return nil, err
+	}
+
+	// Parse the values as JSON
+	result := map[string]any{}
+	for key, value := range markers {
+		var unmarshalled interface{}
+
+		if len(key) == 0 {
+			return nil, fmt.Errorf("cannot have empty key for marker comment")
+		} else if !isKnownTagCommentKey(key) {
+			continue
+		} else if _, ok := parseSymbolReference(value, ""); ok {
+			// Skip ref markers
+			continue
+		} else if len(value) == 0 {
+			// Empty value means key is implicitly a bool
+			result[key] = true
+		} else if err := json.Unmarshal([]byte(value), &unmarshalled); err != nil {
+			// Not valid JSON, throw error
+			return nil, fmt.Errorf("failed to parse value for key %v as JSON: %w", key, err)
+		} else {
+			// Is is valid JSON, use as a JSON value
+			result[key] = unmarshalled
+		}
+	}
+	return result, nil
+}
+
+// Converts a map of:
+//
+//	"a:b:c": 1
+//	"a:b:d": 2
+//	"a:e": 3
+//	"f": 4
+//
+// Into:
+//
+//	 map[string]any{
+//	   "a": map[string]any{
+//		      "b": map[string]any{
+//		          "c": 1,
+//				  "d": 2,
+//			   },
+//			   "e": 3,
+//		  },
+//		  "f": 4,
+//	 }
+//
+// Returns a list of joined errors for any invalid keys. See putNestedValue for more details.
+func nestMarkers(markers map[string]any) (map[string]any, error) {
+	nested := make(map[string]any)
+	var errs []error
+	for key, value := range markers {
+		var err error
+		keys := strings.Split(key, ":")
+
+		if err = putNestedValue(nested, keys, value); err != nil {
+			errs = append(errs, err)
+		}
+	}
+
+	if len(errs) > 0 {
+		return nil, errors.Join(errs...)
+	}
+
+	return nested, nil
+}
+
+// Recursively puts a value into the given keypath, creating intermediate maps
+// and slices as needed. If a key is of the form `foo[bar]`, then bar will be
+// treated as an index into the array foo. If bar is not a valid integer, putNestedValue returns an error.
+func putNestedValue(m map[string]any, k []string, v any) error {
+	if len(k) == 0 {
+		return nil
+	}
+
+	key := k[0]
+	rest := k[1:]
+
+	// Array case
+	if arrayKeyWithoutSubscript, index, hasSubscript, err := extractArraySubscript(key); err != nil {
+		return fmt.Errorf("error parsing subscript for key %v: %w", key, err)
+	} else if hasSubscript {
+		key = arrayKeyWithoutSubscript
+		var arrayDestination []any
+		if existing, ok := m[key]; !ok {
+			arrayDestination = make([]any, index+1)
+		} else if existing, ok := existing.([]any); !ok {
+			// Error case. Existing isn't of correct type. Can happen if
+			// someone is subscripting a field that was previously not an array
+			return fmt.Errorf("expected []any at key %v, got %T", key, existing)
+		} else if index >= len(existing) {
+			// Ensure array is big enough
+			arrayDestination = append(existing, make([]any, index-len(existing)+1)...)
+		} else {
+			arrayDestination = existing
+		}
+
+		m[key] = arrayDestination
+		if arrayDestination[index] == nil {
+			// Doesn't exist case, create the destination.
+			// Assumes the destination is a map for now. Theoretically could be
+			// extended to support arrays of arrays, but that's not needed yet.
+			destination := make(map[string]any)
+			arrayDestination[index] = destination
+			if err = putNestedValue(destination, rest, v); err != nil {
+				return err
+			}
+		} else if dst, ok := arrayDestination[index].(map[string]any); ok {
+			// Already exists case, correct type
+			if putNestedValue(dst, rest, v); err != nil {
+				return err
+			}
+		} else {
+			// Already exists, incorrect type. Error
+			// This shouldn't be possible.
+			return fmt.Errorf("expected map at %v[%v], got %T", key, index, arrayDestination[index])
+		}
+
+		return nil
+	} else if len(rest) == 0 {
+		// Base case. Single key. Just set into destination
+		m[key] = v
+		return nil
+	}
+
+	if existing, ok := m[key]; !ok {
+		destination := make(map[string]any)
+		m[key] = destination
+		return putNestedValue(destination, rest, v)
+	} else if destination, ok := existing.(map[string]any); ok {
+		return putNestedValue(destination, rest, v)
+	} else {
+		// Error case. Existing isn't of correct type. Can happen if prior comment
+		// referred to value as an error
+		return fmt.Errorf("expected map[string]any at key %v, got %T", key, existing)
+	}
+}
+
+// extractArraySubscript extracts the left array subscript from a key of
+// the form  `foo[bar][baz]` -> "bar".
+// Returns the key without the subscript, the index, and a bool indicating if
+// the key had a subscript.
+// If the key has a subscript, but the subscript is not a valid integer, returns an error.
+//
+// This can be adapted to support multidimensional subscripts probably fairly
+// easily by retuning a list of ints
+func extractArraySubscript(str string) (string, int, bool, error) {
+	subscriptIdx := strings.Index(str, "[")
+	if subscriptIdx == -1 {
+		return "", -1, false, nil
+	}
+
+	subscript := strings.Split(str[subscriptIdx+1:], "]")[0]
+	if len(subscript) == 0 {
+		return "", -1, false, fmt.Errorf("empty subscript not allowed")
+	}
+
+	index, err := strconv.Atoi(subscript)
+	if err != nil {
+		return "", -1, false, fmt.Errorf("expected integer index in key %v", str)
+	} else if index < 0 {
+		return "", -1, false, fmt.Errorf("subscript '%v' is invalid. index must be positive", subscript)
+	}
+
+	return str[:subscriptIdx], index, true, nil
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/openapi.go b/vendor/k8s.io/kube-openapi/pkg/generators/openapi.go
new file mode 100644
index 000000000..c5c009381
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/openapi.go
@@ -0,0 +1,1137 @@
+/*
+Copyright 2016 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"io"
+	"path"
+	"reflect"
+	"regexp"
+	"sort"
+	"strings"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/generator"
+	"k8s.io/gengo/v2/namer"
+	"k8s.io/gengo/v2/types"
+	openapi "k8s.io/kube-openapi/pkg/common"
+	"k8s.io/kube-openapi/pkg/validation/spec"
+
+	"k8s.io/klog/v2"
+)
+
+// This is the comment tag that carries parameters for open API generation.
+const tagName = "k8s:openapi-gen"
+const markerPrefix = "+k8s:validation:"
+const tagOptional = "optional"
+const tagRequired = "required"
+const tagDefault = "default"
+
+// Known values for the tag.
+const (
+	tagValueTrue  = "true"
+	tagValueFalse = "false"
+)
+
+// Used for temporary validation of patch struct tags.
+// TODO: Remove patch struct tag validation because they we are now consuming OpenAPI on server.
+var tempPatchTags = [...]string{
+	"patchMergeKey",
+	"patchStrategy",
+}
+
+func getOpenAPITagValue(comments []string) []string {
+	return gengo.ExtractCommentTags("+", comments)[tagName]
+}
+
+func getSingleTagsValue(comments []string, tag string) (string, error) {
+	tags, ok := gengo.ExtractCommentTags("+", comments)[tag]
+	if !ok || len(tags) == 0 {
+		return "", nil
+	}
+	if len(tags) > 1 {
+		return "", fmt.Errorf("multiple values are not allowed for tag %s", tag)
+	}
+	return tags[0], nil
+}
+
+func hasOpenAPITagValue(comments []string, value string) bool {
+	tagValues := getOpenAPITagValue(comments)
+	for _, val := range tagValues {
+		if val == value {
+			return true
+		}
+	}
+	return false
+}
+
+// isOptional returns error if the member has +optional and +required in
+// its comments. If +optional is present it returns true. If +required is present
+// it returns false. Otherwise, it returns true if `omitempty` JSON tag is present
+func isOptional(m *types.Member) (bool, error) {
+	hasOptionalCommentTag := gengo.ExtractCommentTags(
+		"+", m.CommentLines)[tagOptional] != nil
+	hasRequiredCommentTag := gengo.ExtractCommentTags(
+		"+", m.CommentLines)[tagRequired] != nil
+	if hasOptionalCommentTag && hasRequiredCommentTag {
+		return false, fmt.Errorf("member %s cannot be both optional and required", m.Name)
+	} else if hasRequiredCommentTag {
+		return false, nil
+	} else if hasOptionalCommentTag {
+		return true, nil
+	}
+
+	// If neither +optional nor +required is present in the comments,
+	// infer optional from the json tags.
+	return strings.Contains(reflect.StructTag(m.Tags).Get("json"), "omitempty"), nil
+}
+
+func apiTypeFilterFunc(c *generator.Context, t *types.Type) bool {
+	// There is a conflict between this codegen and codecgen, we should avoid types generated for codecgen
+	if strings.HasPrefix(t.Name.Name, "codecSelfer") {
+		return false
+	}
+	pkg := c.Universe.Package(t.Name.Package)
+	if hasOpenAPITagValue(pkg.Comments, tagValueTrue) {
+		return !hasOpenAPITagValue(t.CommentLines, tagValueFalse)
+	}
+	if hasOpenAPITagValue(t.CommentLines, tagValueTrue) {
+		return true
+	}
+	return false
+}
+
+const (
+	specPackagePath          = "k8s.io/kube-openapi/pkg/validation/spec"
+	openAPICommonPackagePath = "k8s.io/kube-openapi/pkg/common"
+)
+
+// openApiGen produces a file with auto-generated OpenAPI functions.
+type openAPIGen struct {
+	generator.GoGenerator
+	// TargetPackage is the package that will get GetOpenAPIDefinitions function returns all open API definitions.
+	targetPackage string
+	imports       namer.ImportTracker
+}
+
+func newOpenAPIGen(outputFilename string, targetPackage string) generator.Generator {
+	return &openAPIGen{
+		GoGenerator: generator.GoGenerator{
+			OutputFilename: outputFilename,
+		},
+		imports:       generator.NewImportTrackerForPackage(targetPackage),
+		targetPackage: targetPackage,
+	}
+}
+
+const nameTmpl = "schema_$.type|private$"
+
+func (g *openAPIGen) Namers(c *generator.Context) namer.NameSystems {
+	// Have the raw namer for this file track what it imports.
+	return namer.NameSystems{
+		"raw": namer.NewRawNamer(g.targetPackage, g.imports),
+		"private": &namer.NameStrategy{
+			Join: func(pre string, in []string, post string) string {
+				return strings.Join(in, "_")
+			},
+			PrependPackageNames: 4, // enough to fully qualify from k8s.io/api/...
+		},
+	}
+}
+
+func (g *openAPIGen) Imports(c *generator.Context) []string {
+	importLines := []string{}
+	for _, singleImport := range g.imports.ImportLines() {
+		importLines = append(importLines, singleImport)
+	}
+	return importLines
+}
+
+func argsFromType(t *types.Type) generator.Args {
+	return generator.Args{
+		"type":              t,
+		"ReferenceCallback": types.Ref(openAPICommonPackagePath, "ReferenceCallback"),
+		"OpenAPIDefinition": types.Ref(openAPICommonPackagePath, "OpenAPIDefinition"),
+		"SpecSchemaType":    types.Ref(specPackagePath, "Schema"),
+	}
+}
+
+func (g *openAPIGen) Init(c *generator.Context, w io.Writer) error {
+	sw := generator.NewSnippetWriter(w, c, "$", "$")
+	sw.Do("func GetOpenAPIDefinitions(ref $.ReferenceCallback|raw$) map[string]$.OpenAPIDefinition|raw$ {\n", argsFromType(nil))
+	sw.Do("return map[string]$.OpenAPIDefinition|raw${\n", argsFromType(nil))
+
+	for _, t := range c.Order {
+		err := newOpenAPITypeWriter(sw, c).generateCall(t)
+		if err != nil {
+			return err
+		}
+	}
+
+	sw.Do("}\n", nil)
+	sw.Do("}\n\n", nil)
+
+	return sw.Error()
+}
+
+func (g *openAPIGen) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
+	klog.V(5).Infof("generating for type %v", t)
+	sw := generator.NewSnippetWriter(w, c, "$", "$")
+	err := newOpenAPITypeWriter(sw, c).generate(t)
+	if err != nil {
+		return err
+	}
+	return sw.Error()
+}
+
+func getJsonTags(m *types.Member) []string {
+	jsonTag := reflect.StructTag(m.Tags).Get("json")
+	if jsonTag == "" {
+		return []string{}
+	}
+	return strings.Split(jsonTag, ",")
+}
+
+func getReferableName(m *types.Member) string {
+	jsonTags := getJsonTags(m)
+	if len(jsonTags) > 0 {
+		if jsonTags[0] == "-" {
+			return ""
+		} else {
+			return jsonTags[0]
+		}
+	} else {
+		return m.Name
+	}
+}
+
+func shouldInlineMembers(m *types.Member) bool {
+	jsonTags := getJsonTags(m)
+	return len(jsonTags) > 1 && jsonTags[1] == "inline"
+}
+
+type openAPITypeWriter struct {
+	*generator.SnippetWriter
+	context                *generator.Context
+	refTypes               map[string]*types.Type
+	enumContext            *enumContext
+	GetDefinitionInterface *types.Type
+}
+
+func newOpenAPITypeWriter(sw *generator.SnippetWriter, c *generator.Context) openAPITypeWriter {
+	return openAPITypeWriter{
+		SnippetWriter: sw,
+		context:       c,
+		refTypes:      map[string]*types.Type{},
+		enumContext:   newEnumContext(c),
+	}
+}
+
+func methodReturnsValue(mt *types.Type, pkg, name string) bool {
+	if len(mt.Signature.Parameters) != 0 || len(mt.Signature.Results) != 1 {
+		return false
+	}
+	r := mt.Signature.Results[0]
+	return r.Type.Name.Name == name && r.Type.Name.Package == pkg
+}
+
+func hasOpenAPIV3DefinitionMethod(t *types.Type) bool {
+	for mn, mt := range t.Methods {
+		if mn != "OpenAPIV3Definition" {
+			continue
+		}
+		return methodReturnsValue(mt, openAPICommonPackagePath, "OpenAPIDefinition")
+	}
+	return false
+}
+
+func hasOpenAPIDefinitionMethod(t *types.Type) bool {
+	for mn, mt := range t.Methods {
+		if mn != "OpenAPIDefinition" {
+			continue
+		}
+		return methodReturnsValue(mt, openAPICommonPackagePath, "OpenAPIDefinition")
+	}
+	return false
+}
+
+func hasOpenAPIDefinitionMethods(t *types.Type) bool {
+	var hasSchemaTypeMethod, hasOpenAPISchemaFormat bool
+	for mn, mt := range t.Methods {
+		switch mn {
+		case "OpenAPISchemaType":
+			hasSchemaTypeMethod = methodReturnsValue(mt, "", "[]string")
+		case "OpenAPISchemaFormat":
+			hasOpenAPISchemaFormat = methodReturnsValue(mt, "", "string")
+		}
+	}
+	return hasSchemaTypeMethod && hasOpenAPISchemaFormat
+}
+
+func hasOpenAPIV3OneOfMethod(t *types.Type) bool {
+	for mn, mt := range t.Methods {
+		if mn != "OpenAPIV3OneOfTypes" {
+			continue
+		}
+		return methodReturnsValue(mt, "", "[]string")
+	}
+	return false
+}
+
+// typeShortName returns short package name (e.g. the name x appears in package x definition) dot type name.
+func typeShortName(t *types.Type) string {
+	// `path` vs. `filepath` because packages use '/'
+	return path.Base(t.Name.Package) + "." + t.Name.Name
+}
+
+func (g openAPITypeWriter) generateMembers(t *types.Type, required []string) ([]string, error) {
+	var err error
+	for t.Kind == types.Pointer { // fast-forward to effective type containing members
+		t = t.Elem
+	}
+	for _, m := range t.Members {
+		if hasOpenAPITagValue(m.CommentLines, tagValueFalse) {
+			continue
+		}
+		if shouldInlineMembers(&m) {
+			required, err = g.generateMembers(m.Type, required)
+			if err != nil {
+				return required, err
+			}
+			continue
+		}
+		name := getReferableName(&m)
+		if name == "" {
+			continue
+		}
+		if isOptional, err := isOptional(&m); err != nil {
+			klog.Errorf("Error when generating: %v, %v\n", name, m)
+			return required, err
+		} else if !isOptional {
+			required = append(required, name)
+		}
+		if err = g.generateProperty(&m, t); err != nil {
+			klog.Errorf("Error when generating: %v, %v\n", name, m)
+			return required, err
+		}
+	}
+	return required, nil
+}
+
+func (g openAPITypeWriter) generateCall(t *types.Type) error {
+	// Only generate for struct type and ignore the rest
+	switch t.Kind {
+	case types.Struct:
+		args := argsFromType(t)
+		g.Do("\"$.$\": ", t.Name)
+
+		hasV2Definition := hasOpenAPIDefinitionMethod(t)
+		hasV2DefinitionTypeAndFormat := hasOpenAPIDefinitionMethods(t)
+		hasV3Definition := hasOpenAPIV3DefinitionMethod(t)
+
+		switch {
+		case hasV2DefinitionTypeAndFormat:
+			g.Do(nameTmpl+"(ref),\n", args)
+		case hasV2Definition && hasV3Definition:
+			g.Do("common.EmbedOpenAPIDefinitionIntoV2Extension($.type|raw${}.OpenAPIV3Definition(), $.type|raw${}.OpenAPIDefinition()),\n", args)
+		case hasV2Definition:
+			g.Do("$.type|raw${}.OpenAPIDefinition(),\n", args)
+		case hasV3Definition:
+			g.Do("$.type|raw${}.OpenAPIV3Definition(),\n", args)
+		default:
+			g.Do(nameTmpl+"(ref),\n", args)
+		}
+	}
+	return g.Error()
+}
+
+// Generates Go code to represent an OpenAPI schema. May be refactored in
+// the future to take more responsibility as we transition from an on-line
+// approach to parsing the comments to spec.Schema
+func (g openAPITypeWriter) generateSchema(s *spec.Schema) error {
+	if !reflect.DeepEqual(s.SchemaProps, spec.SchemaProps{}) {
+		g.Do("SchemaProps: spec.SchemaProps{\n", nil)
+		err := g.generateValueValidations(&s.SchemaProps)
+		if err != nil {
+			return err
+		}
+
+		if len(s.Properties) > 0 {
+			g.Do("Properties: map[string]spec.Schema{\n", nil)
+
+			// Sort property names to generate deterministic output
+			keys := []string{}
+			for k := range s.Properties {
+				keys = append(keys, k)
+			}
+			sort.Strings(keys)
+
+			for _, k := range keys {
+				v := s.Properties[k]
+				g.Do("$.$: {\n", fmt.Sprintf("%#v", k))
+				err := g.generateSchema(&v)
+				if err != nil {
+					return err
+				}
+				g.Do("},\n", nil)
+			}
+			g.Do("},\n", nil)
+		}
+
+		if s.AdditionalProperties != nil && s.AdditionalProperties.Schema != nil {
+			g.Do("AdditionalProperties: &spec.SchemaOrBool{\n", nil)
+			g.Do("Allows: true,\n", nil)
+			g.Do("Schema: &spec.Schema{\n", nil)
+			err := g.generateSchema(s.AdditionalProperties.Schema)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("},\n", nil)
+		}
+
+		if s.Items != nil && s.Items.Schema != nil {
+			g.Do("Items: &spec.SchemaOrArray{\n", nil)
+			g.Do("Schema: &spec.Schema{\n", nil)
+			err := g.generateSchema(s.Items.Schema)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("},\n", nil)
+		}
+
+		g.Do("},\n", nil)
+	}
+
+	if len(s.Extensions) > 0 {
+		g.Do("VendorExtensible: spec.VendorExtensible{\nExtensions: spec.Extensions{\n", nil)
+
+		// Sort extension keys to generate deterministic output
+		keys := []string{}
+		for k := range s.Extensions {
+			keys = append(keys, k)
+		}
+		sort.Strings(keys)
+
+		for _, k := range keys {
+			v := s.Extensions[k]
+			g.Do("$.key$: $.value$,\n", map[string]interface{}{
+				"key":   fmt.Sprintf("%#v", k),
+				"value": fmt.Sprintf("%#v", v),
+			})
+		}
+		g.Do("},\n},\n", nil)
+	}
+
+	return nil
+}
+
+func (g openAPITypeWriter) generateValueValidations(vs *spec.SchemaProps) error {
+
+	if vs == nil {
+		return nil
+	}
+	args := generator.Args{
+		"ptrTo": &types.Type{
+			Name: types.Name{
+				Package: "k8s.io/utils/ptr",
+				Name:    "To",
+			}},
+		"spec": vs,
+	}
+	if vs.Minimum != nil {
+		g.Do("Minimum: $.ptrTo|raw$[float64]($.spec.Minimum$),\n", args)
+	}
+	if vs.Maximum != nil {
+		g.Do("Maximum: $.ptrTo|raw$[float64]($.spec.Maximum$),\n", args)
+	}
+	if vs.ExclusiveMinimum {
+		g.Do("ExclusiveMinimum: true,\n", args)
+	}
+	if vs.ExclusiveMaximum {
+		g.Do("ExclusiveMaximum: true,\n", args)
+	}
+	if vs.MinLength != nil {
+		g.Do("MinLength: $.ptrTo|raw$[int64]($.spec.MinLength$),\n", args)
+	}
+	if vs.MaxLength != nil {
+		g.Do("MaxLength: $.ptrTo|raw$[int64]($.spec.MaxLength$),\n", args)
+	}
+
+	if vs.MinProperties != nil {
+		g.Do("MinProperties: $.ptrTo|raw$[int64]($.spec.MinProperties$),\n", args)
+	}
+	if vs.MaxProperties != nil {
+		g.Do("MaxProperties: $.ptrTo|raw$[int64]($.spec.MaxProperties$),\n", args)
+	}
+	if len(vs.Pattern) > 0 {
+		p, err := json.Marshal(vs.Pattern)
+		if err != nil {
+			return err
+		}
+		g.Do("Pattern: $.$,\n", string(p))
+	}
+	if vs.MultipleOf != nil {
+		g.Do("MultipleOf: $.ptrTo|raw$[float64]($.spec.MultipleOf$),\n", args)
+	}
+	if vs.MinItems != nil {
+		g.Do("MinItems: $.ptrTo|raw$[int64]($.spec.MinItems$),\n", args)
+	}
+	if vs.MaxItems != nil {
+		g.Do("MaxItems: $.ptrTo|raw$[int64]($.spec.MaxItems$),\n", args)
+	}
+	if vs.UniqueItems {
+		g.Do("UniqueItems: true,\n", nil)
+	}
+
+	if len(vs.AllOf) > 0 {
+		g.Do("AllOf: []spec.Schema{\n", nil)
+		for _, s := range vs.AllOf {
+			g.Do("{\n", nil)
+			if err := g.generateSchema(&s); err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+		}
+		g.Do("},\n", nil)
+	}
+
+	return nil
+}
+
+func (g openAPITypeWriter) generate(t *types.Type) error {
+	// Only generate for struct type and ignore the rest
+	switch t.Kind {
+	case types.Struct:
+		validationSchema, err := ParseCommentTags(t, t.CommentLines, markerPrefix)
+		if err != nil {
+			return fmt.Errorf("failed parsing comment tags for %v: %w", t.String(), err)
+		}
+
+		hasV2Definition := hasOpenAPIDefinitionMethod(t)
+		hasV2DefinitionTypeAndFormat := hasOpenAPIDefinitionMethods(t)
+		hasV3OneOfTypes := hasOpenAPIV3OneOfMethod(t)
+		hasV3Definition := hasOpenAPIV3DefinitionMethod(t)
+
+		if hasV2Definition || (hasV3Definition && !hasV2DefinitionTypeAndFormat) {
+			// already invoked directly
+			return nil
+		}
+
+		args := argsFromType(t)
+		g.Do("func "+nameTmpl+"(ref $.ReferenceCallback|raw$) $.OpenAPIDefinition|raw$ {\n", args)
+		switch {
+		case hasV2DefinitionTypeAndFormat && hasV3Definition:
+			g.Do("return common.EmbedOpenAPIDefinitionIntoV2Extension($.type|raw${}.OpenAPIV3Definition(), $.OpenAPIDefinition|raw${\n"+
+				"Schema: spec.Schema{\n"+
+				"SchemaProps: spec.SchemaProps{\n", args)
+			g.generateDescription(t.CommentLines)
+			g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+
+				"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args)
+			err = g.generateValueValidations(&validationSchema.SchemaProps)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("})\n}\n\n", args)
+			return nil
+		case hasV2DefinitionTypeAndFormat && hasV3OneOfTypes:
+			// generate v3 def.
+			g.Do("return common.EmbedOpenAPIDefinitionIntoV2Extension($.OpenAPIDefinition|raw${\n"+
+				"Schema: spec.Schema{\n"+
+				"SchemaProps: spec.SchemaProps{\n", args)
+			g.generateDescription(t.CommentLines)
+			g.Do("OneOf:common.GenerateOpenAPIV3OneOfSchema($.type|raw${}.OpenAPIV3OneOfTypes()),\n"+
+				"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args)
+			err = g.generateValueValidations(&validationSchema.SchemaProps)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("},", args)
+			// generate v2 def.
+			g.Do("$.OpenAPIDefinition|raw${\n"+
+				"Schema: spec.Schema{\n"+
+				"SchemaProps: spec.SchemaProps{\n", args)
+			g.generateDescription(t.CommentLines)
+			g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+
+				"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args)
+			err = g.generateValueValidations(&validationSchema.SchemaProps)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("})\n}\n\n", args)
+			return nil
+		case hasV2DefinitionTypeAndFormat:
+			g.Do("return $.OpenAPIDefinition|raw${\n"+
+				"Schema: spec.Schema{\n"+
+				"SchemaProps: spec.SchemaProps{\n", args)
+			g.generateDescription(t.CommentLines)
+			g.Do("Type:$.type|raw${}.OpenAPISchemaType(),\n"+
+				"Format:$.type|raw${}.OpenAPISchemaFormat(),\n", args)
+			err = g.generateValueValidations(&validationSchema.SchemaProps)
+			if err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil {
+				return err
+			}
+			g.Do("},\n", nil)
+			g.Do("}\n}\n\n", args)
+			return nil
+		case hasV3OneOfTypes:
+			// having v3 oneOf types without custom v2 type or format does not make sense.
+			return fmt.Errorf("type %q has v3 one of types but not v2 type or format", t.Name)
+		}
+
+		g.Do("return $.OpenAPIDefinition|raw${\nSchema: spec.Schema{\nSchemaProps: spec.SchemaProps{\n", args)
+		g.generateDescription(t.CommentLines)
+		g.Do("Type: []string{\"object\"},\n", nil)
+		err = g.generateValueValidations(&validationSchema.SchemaProps)
+		if err != nil {
+			return err
+		}
+
+		// write members into a temporary buffer, in order to postpone writing out the Properties field. We only do
+		// that if it is not empty.
+		propertiesBuf := bytes.Buffer{}
+		bsw := g
+		bsw.SnippetWriter = generator.NewSnippetWriter(&propertiesBuf, g.context, "$", "$")
+		required, err := bsw.generateMembers(t, []string{})
+		if err != nil {
+			return err
+		}
+		if propertiesBuf.Len() > 0 {
+			g.Do("Properties: map[string]$.SpecSchemaType|raw${\n", args)
+			g.Do(strings.Replace(propertiesBuf.String(), "$", "$\"$\"$", -1), nil) // escape $ (used as delimiter of the templates)
+			g.Do("},\n", nil)
+		}
+
+		if len(required) > 0 {
+			g.Do("Required: []string{\"$.$\"},\n", strings.Join(required, "\",\""))
+		}
+		g.Do("},\n", nil)
+		if err := g.generateStructExtensions(t, validationSchema.Extensions); err != nil {
+			return err
+		}
+		g.Do("},\n", nil)
+
+		// Map order is undefined, sort them or we may get a different file generated each time.
+		keys := []string{}
+		for k := range g.refTypes {
+			keys = append(keys, k)
+		}
+		sort.Strings(keys)
+		deps := []string{}
+		for _, k := range keys {
+			v := g.refTypes[k]
+			if t, _ := openapi.OpenAPITypeFormat(v.String()); t != "" {
+				// This is a known type, we do not need a reference to it
+				// Will eliminate special case of time.Time
+				continue
+			}
+			deps = append(deps, k)
+		}
+		if len(deps) > 0 {
+			g.Do("Dependencies: []string{\n", args)
+			for _, k := range deps {
+				g.Do("\"$.$\",", k)
+			}
+			g.Do("},\n", nil)
+		}
+		g.Do("}\n}\n\n", nil)
+	}
+	return nil
+}
+
+func (g openAPITypeWriter) generateStructExtensions(t *types.Type, otherExtensions map[string]interface{}) error {
+	extensions, errors := parseExtensions(t.CommentLines)
+	// Initially, we will only log struct extension errors.
+	if len(errors) > 0 {
+		for _, e := range errors {
+			klog.Errorf("[%s]: %s\n", t.String(), e)
+		}
+	}
+	unions, errors := parseUnions(t)
+	if len(errors) > 0 {
+		for _, e := range errors {
+			klog.Errorf("[%s]: %s\n", t.String(), e)
+		}
+	}
+
+	// TODO(seans3): Validate struct extensions here.
+	g.emitExtensions(extensions, unions, otherExtensions)
+	return nil
+}
+
+func (g openAPITypeWriter) generateMemberExtensions(m *types.Member, parent *types.Type, otherExtensions map[string]interface{}) error {
+	extensions, parseErrors := parseExtensions(m.CommentLines)
+	validationErrors := validateMemberExtensions(extensions, m)
+	errors := append(parseErrors, validationErrors...)
+	// Initially, we will only log member extension errors.
+	if len(errors) > 0 {
+		errorPrefix := fmt.Sprintf("[%s] %s:", parent.String(), m.String())
+		for _, e := range errors {
+			klog.V(2).Infof("%s %s\n", errorPrefix, e)
+		}
+	}
+	g.emitExtensions(extensions, nil, otherExtensions)
+	return nil
+}
+
+func (g openAPITypeWriter) emitExtensions(extensions []extension, unions []union, otherExtensions map[string]interface{}) {
+	// If any extensions exist, then emit code to create them.
+	if len(extensions) == 0 && len(unions) == 0 && len(otherExtensions) == 0 {
+		return
+	}
+	g.Do("VendorExtensible: spec.VendorExtensible{\nExtensions: spec.Extensions{\n", nil)
+	for _, extension := range extensions {
+		g.Do("\"$.$\": ", extension.xName)
+		if extension.hasMultipleValues() || extension.isAlwaysArrayFormat() {
+			g.Do("[]interface{}{\n", nil)
+		}
+		for _, value := range extension.values {
+			g.Do("\"$.$\",\n", value)
+		}
+		if extension.hasMultipleValues() || extension.isAlwaysArrayFormat() {
+			g.Do("},\n", nil)
+		}
+	}
+	if len(unions) > 0 {
+		g.Do("\"x-kubernetes-unions\": []interface{}{\n", nil)
+		for _, u := range unions {
+			u.emit(g)
+		}
+		g.Do("},\n", nil)
+	}
+
+	if len(otherExtensions) > 0 {
+		// Sort extension keys to generate deterministic output
+		keys := []string{}
+		for k := range otherExtensions {
+			keys = append(keys, k)
+		}
+		sort.Strings(keys)
+
+		for _, k := range keys {
+			v := otherExtensions[k]
+			g.Do("$.key$: $.value$,\n", map[string]interface{}{
+				"key":   fmt.Sprintf("%#v", k),
+				"value": fmt.Sprintf("%#v", v),
+			})
+		}
+	}
+
+	g.Do("},\n},\n", nil)
+}
+
+// TODO(#44005): Move this validation outside of this generator (probably to policy verifier)
+func (g openAPITypeWriter) validatePatchTags(m *types.Member, parent *types.Type) error {
+	// TODO: Remove patch struct tag validation because they we are now consuming OpenAPI on server.
+	for _, tagKey := range tempPatchTags {
+		structTagValue := reflect.StructTag(m.Tags).Get(tagKey)
+		commentTagValue, err := getSingleTagsValue(m.CommentLines, tagKey)
+		if err != nil {
+			return err
+		}
+		if structTagValue != commentTagValue {
+			return fmt.Errorf("Tags in comment and struct should match for member (%s) of (%s)",
+				m.Name, parent.Name.String())
+		}
+	}
+	return nil
+}
+
+func defaultFromComments(comments []string, commentPath string, t *types.Type) (interface{}, *types.Name, error) {
+	var tag string
+
+	for {
+		var err error
+		tag, err = getSingleTagsValue(comments, tagDefault)
+		if err != nil {
+			return nil, nil, err
+		}
+
+		if t == nil || len(tag) > 0 {
+			break
+		}
+
+		comments = t.CommentLines
+		commentPath = t.Name.Package
+		switch t.Kind {
+		case types.Pointer:
+			t = t.Elem
+		case types.Alias:
+			t = t.Underlying
+		default:
+			t = nil
+		}
+	}
+
+	if tag == "" {
+		return nil, nil, nil
+	}
+
+	var i interface{}
+	if id, ok := parseSymbolReference(tag, commentPath); ok {
+		klog.V(5).Infof("%v, %v", id, commentPath)
+		return nil, &id, nil
+	} else if err := json.Unmarshal([]byte(tag), &i); err != nil {
+		return nil, nil, fmt.Errorf("failed to unmarshal default: %v", err)
+	}
+	return i, nil, nil
+}
+
+var refRE = regexp.MustCompile(`^ref\((?P[^"]+)\)$`)
+var refREIdentIndex = refRE.SubexpIndex("reference")
+
+// parseSymbolReference looks for strings that match one of the following:
+//   - ref(Ident)
+//   - ref(pkgpath.Ident)
+//     If the input string matches either of these, it will return the (optional)
+//     pkgpath, the Ident, and true.  Otherwise it will return empty strings and
+//     false.
+//
+// This is borrowed from k8s.io/code-generator.
+func parseSymbolReference(s, sourcePackage string) (types.Name, bool) {
+	matches := refRE.FindStringSubmatch(s)
+	if len(matches) < refREIdentIndex || matches[refREIdentIndex] == "" {
+		return types.Name{}, false
+	}
+
+	contents := matches[refREIdentIndex]
+	name := types.ParseFullyQualifiedName(contents)
+	if len(name.Package) == 0 {
+		name.Package = sourcePackage
+	}
+	return name, true
+}
+
+func implementsCustomUnmarshalling(t *types.Type) bool {
+	switch t.Kind {
+	case types.Pointer:
+		unmarshaller, isUnmarshaller := t.Elem.Methods["UnmarshalJSON"]
+		return isUnmarshaller && unmarshaller.Signature.Receiver.Kind == types.Pointer
+	case types.Struct:
+		_, isUnmarshaller := t.Methods["UnmarshalJSON"]
+		return isUnmarshaller
+	default:
+		return false
+	}
+}
+
+func mustEnforceDefault(t *types.Type, omitEmpty bool) (interface{}, error) {
+	// Treat types with custom unmarshalling as a value
+	// (Can be alias, struct, or pointer)
+	if implementsCustomUnmarshalling(t) {
+		// Since Go JSON deserializer always feeds `null` when present
+		// to structs with custom UnmarshalJSON, the zero value for
+		// these structs is also null.
+		//
+		// In general, Kubernetes API types with custom marshalling should
+		// marshal their empty values to `null`.
+		return nil, nil
+	}
+
+	switch t.Kind {
+	case types.Alias:
+		return mustEnforceDefault(t.Underlying, omitEmpty)
+	case types.Pointer, types.Map, types.Slice, types.Array, types.Interface:
+		return nil, nil
+	case types.Struct:
+		if len(t.Members) == 1 && t.Members[0].Embedded {
+			// Treat a struct with a single embedded member the same as an alias
+			return mustEnforceDefault(t.Members[0].Type, omitEmpty)
+		}
+
+		return map[string]interface{}{}, nil
+	case types.Builtin:
+		if !omitEmpty {
+			if zero, ok := openapi.OpenAPIZeroValue(t.String()); ok {
+				return zero, nil
+			} else {
+				return nil, fmt.Errorf("please add type %v to getOpenAPITypeFormat function", t)
+			}
+		}
+		return nil, nil
+	default:
+		return nil, fmt.Errorf("not sure how to enforce default for %v", t.Kind)
+	}
+}
+
+func (g openAPITypeWriter) generateDefault(comments []string, t *types.Type, omitEmpty bool, commentOwningType *types.Type) error {
+	def, ref, err := defaultFromComments(comments, commentOwningType.Name.Package, t)
+	if err != nil {
+		return err
+	}
+	if enforced, err := mustEnforceDefault(t, omitEmpty); err != nil {
+		return err
+	} else if enforced != nil {
+		if def == nil {
+			def = enforced
+		} else if !reflect.DeepEqual(def, enforced) {
+			enforcedJson, _ := json.Marshal(enforced)
+			return fmt.Errorf("invalid default value (%#v) for non-pointer/non-omitempty. If specified, must be: %v", def, string(enforcedJson))
+		}
+	}
+	if def != nil {
+		g.Do("Default: $.$,\n", fmt.Sprintf("%#v", def))
+	} else if ref != nil {
+		g.Do("Default: $.|raw$,\n", &types.Type{Name: *ref})
+	}
+	return nil
+}
+
+func (g openAPITypeWriter) generateDescription(CommentLines []string) {
+	var buffer bytes.Buffer
+	delPrevChar := func() {
+		if buffer.Len() > 0 {
+			buffer.Truncate(buffer.Len() - 1) // Delete the last " " or "\n"
+		}
+	}
+
+	for _, line := range CommentLines {
+		// Ignore all lines after ---
+		if line == "---" {
+			break
+		}
+		line = strings.TrimRight(line, " ")
+		leading := strings.TrimLeft(line, " ")
+		switch {
+		case len(line) == 0: // Keep paragraphs
+			delPrevChar()
+			buffer.WriteString("\n\n")
+		case strings.HasPrefix(leading, "TODO"): // Ignore one line TODOs
+		case strings.HasPrefix(leading, "+"): // Ignore instructions to go2idl
+		default:
+			if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
+				delPrevChar()
+				line = "\n" + line + "\n" // Replace it with newline. This is useful when we have a line with: "Example:\n\tJSON-something..."
+			} else {
+				line += " "
+			}
+			buffer.WriteString(line)
+		}
+	}
+
+	postDoc := strings.TrimSpace(buffer.String())
+	if len(postDoc) > 0 {
+		g.Do("Description: $.$,\n", fmt.Sprintf("%#v", postDoc))
+	}
+}
+
+func (g openAPITypeWriter) generateProperty(m *types.Member, parent *types.Type) error {
+	name := getReferableName(m)
+	if name == "" {
+		return nil
+	}
+	validationSchema, err := ParseCommentTags(m.Type, m.CommentLines, markerPrefix)
+	if err != nil {
+		return err
+	}
+	if err := g.validatePatchTags(m, parent); err != nil {
+		return err
+	}
+	g.Do("\"$.$\": {\n", name)
+	if err := g.generateMemberExtensions(m, parent, validationSchema.Extensions); err != nil {
+		return err
+	}
+	g.Do("SchemaProps: spec.SchemaProps{\n", nil)
+	var extraComments []string
+	if enumType, isEnum := g.enumContext.EnumType(m.Type); isEnum {
+		extraComments = enumType.DescriptionLines()
+	}
+	g.generateDescription(append(m.CommentLines, extraComments...))
+	jsonTags := getJsonTags(m)
+	if len(jsonTags) > 1 && jsonTags[1] == "string" {
+		g.generateSimpleProperty("string", "")
+		g.Do("},\n},\n", nil)
+		return nil
+	}
+	omitEmpty := strings.Contains(reflect.StructTag(m.Tags).Get("json"), "omitempty")
+	if err := g.generateDefault(m.CommentLines, m.Type, omitEmpty, parent); err != nil {
+		return fmt.Errorf("failed to generate default in %v: %v: %v", parent, m.Name, err)
+	}
+	err = g.generateValueValidations(&validationSchema.SchemaProps)
+	if err != nil {
+		return err
+	}
+	t := resolveAliasAndPtrType(m.Type)
+	// If we can get a openAPI type and format for this type, we consider it to be simple property
+	typeString, format := openapi.OpenAPITypeFormat(t.String())
+	if typeString != "" {
+		g.generateSimpleProperty(typeString, format)
+		if enumType, isEnum := g.enumContext.EnumType(m.Type); isEnum {
+			// original type is an enum, add "Enum: " and the values
+			g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", "))
+		}
+		g.Do("},\n},\n", nil)
+		return nil
+	}
+	switch t.Kind {
+	case types.Builtin:
+		return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", t)
+	case types.Map:
+		if err := g.generateMapProperty(t); err != nil {
+			return fmt.Errorf("failed to generate map property in %v: %v: %v", parent, m.Name, err)
+		}
+	case types.Slice, types.Array:
+		if err := g.generateSliceProperty(t); err != nil {
+			return fmt.Errorf("failed to generate slice property in %v: %v: %v", parent, m.Name, err)
+		}
+	case types.Struct, types.Interface:
+		g.generateReferenceProperty(t)
+	default:
+		return fmt.Errorf("cannot generate spec for type %v", t)
+	}
+	g.Do("},\n},\n", nil)
+	return g.Error()
+}
+
+func (g openAPITypeWriter) generateSimpleProperty(typeString, format string) {
+	g.Do("Type: []string{\"$.$\"},\n", typeString)
+	g.Do("Format: \"$.$\",\n", format)
+}
+
+func (g openAPITypeWriter) generateReferenceProperty(t *types.Type) {
+	g.refTypes[t.Name.String()] = t
+	g.Do("Ref: ref(\"$.$\"),\n", t.Name.String())
+}
+
+func resolvePtrType(t *types.Type) *types.Type {
+	var prev *types.Type
+	for prev != t {
+		prev = t
+		if t.Kind == types.Pointer {
+			t = t.Elem
+		}
+	}
+	return t
+}
+
+func resolveAliasAndPtrType(t *types.Type) *types.Type {
+	var prev *types.Type
+	for prev != t {
+		prev = t
+		if t.Kind == types.Alias {
+			t = t.Underlying
+		}
+		if t.Kind == types.Pointer {
+			t = t.Elem
+		}
+	}
+	return t
+}
+
+func (g openAPITypeWriter) generateMapProperty(t *types.Type) error {
+	keyType := resolveAliasAndPtrType(t.Key)
+	elemType := resolveAliasAndPtrType(t.Elem)
+
+	// According to OpenAPI examples, only map from string is supported
+	if keyType.Name.Name != "string" {
+		return fmt.Errorf("map with non-string keys are not supported by OpenAPI in %v", t)
+	}
+
+	g.Do("Type: []string{\"object\"},\n", nil)
+	g.Do("AdditionalProperties: &spec.SchemaOrBool{\nAllows: true,\nSchema: &spec.Schema{\nSchemaProps: spec.SchemaProps{\n", nil)
+	if err := g.generateDefault(t.Elem.CommentLines, t.Elem, false, t.Elem); err != nil {
+		return err
+	}
+	typeString, format := openapi.OpenAPITypeFormat(elemType.String())
+	if typeString != "" {
+		g.generateSimpleProperty(typeString, format)
+		if enumType, isEnum := g.enumContext.EnumType(t.Elem); isEnum {
+			// original type is an enum, add "Enum: " and the values
+			g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", "))
+		}
+		g.Do("},\n},\n},\n", nil)
+		return nil
+	}
+	switch elemType.Kind {
+	case types.Builtin:
+		return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", elemType)
+	case types.Struct:
+		g.generateReferenceProperty(elemType)
+	case types.Slice, types.Array:
+		if err := g.generateSliceProperty(elemType); err != nil {
+			return err
+		}
+	case types.Map:
+		if err := g.generateMapProperty(elemType); err != nil {
+			return err
+		}
+	default:
+		return fmt.Errorf("map Element kind %v is not supported in %v", elemType.Kind, t.Name)
+	}
+	g.Do("},\n},\n},\n", nil)
+	return nil
+}
+
+func (g openAPITypeWriter) generateSliceProperty(t *types.Type) error {
+	elemType := resolveAliasAndPtrType(t.Elem)
+	g.Do("Type: []string{\"array\"},\n", nil)
+	g.Do("Items: &spec.SchemaOrArray{\nSchema: &spec.Schema{\nSchemaProps: spec.SchemaProps{\n", nil)
+	if err := g.generateDefault(t.Elem.CommentLines, t.Elem, false, t.Elem); err != nil {
+		return err
+	}
+	typeString, format := openapi.OpenAPITypeFormat(elemType.String())
+	if typeString != "" {
+		g.generateSimpleProperty(typeString, format)
+		if enumType, isEnum := g.enumContext.EnumType(t.Elem); isEnum {
+			// original type is an enum, add "Enum: " and the values
+			g.Do("Enum: []interface{}{$.$},\n", strings.Join(enumType.ValueStrings(), ", "))
+		}
+		g.Do("},\n},\n},\n", nil)
+		return nil
+	}
+	switch elemType.Kind {
+	case types.Builtin:
+		return fmt.Errorf("please add type %v to getOpenAPITypeFormat function", elemType)
+	case types.Struct:
+		g.generateReferenceProperty(elemType)
+	case types.Slice, types.Array:
+		if err := g.generateSliceProperty(elemType); err != nil {
+			return err
+		}
+	case types.Map:
+		if err := g.generateMapProperty(elemType); err != nil {
+			return err
+		}
+	default:
+		return fmt.Errorf("slice Element kind %v is not supported in %v", elemType.Kind, t)
+	}
+	g.Do("},\n},\n},\n", nil)
+	return nil
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS b/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS
new file mode 100644
index 000000000..235bc545b
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/OWNERS
@@ -0,0 +1,4 @@
+reviewers:
+- roycaihw
+approvers:
+- roycaihw
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/doc.go b/vendor/k8s.io/kube-openapi/pkg/generators/rules/doc.go
new file mode 100644
index 000000000..384a44dca
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/doc.go
@@ -0,0 +1,23 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package rules contains API rules that are enforced in OpenAPI spec generation
+// as part of the machinery. Files under this package implement APIRule interface
+// which evaluates Go type and produces list of API rule violations.
+//
+// Implementations of APIRule should be added to API linter under openAPIGen code-
+// generator to get integrated in the generation process.
+package rules
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/idl_tag.go b/vendor/k8s.io/kube-openapi/pkg/generators/rules/idl_tag.go
new file mode 100644
index 000000000..e4b0f7cd3
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/idl_tag.go
@@ -0,0 +1,55 @@
+package rules
+
+import (
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/types"
+)
+
+const ListTypeIDLTag = "listType"
+
+// ListTypeMissing implements APIRule interface.
+// A list type is required for inlined list.
+type ListTypeMissing struct{}
+
+// Name returns the name of APIRule
+func (l *ListTypeMissing) Name() string {
+	return "list_type_missing"
+}
+
+// Validate evaluates API rule on type t and returns a list of field names in
+// the type that violate the rule. Empty field name [""] implies the entire
+// type violates the rule.
+func (l *ListTypeMissing) Validate(t *types.Type) ([]string, error) {
+	fields := make([]string, 0)
+
+	switch t.Kind {
+	case types.Struct:
+		for _, m := range t.Members {
+			hasListType := gengo.ExtractCommentTags("+", m.CommentLines)[ListTypeIDLTag] != nil
+
+			if m.Name == "Items" && m.Type.Kind == types.Slice && hasNamedMember(t, "ListMeta") {
+				if hasListType {
+					fields = append(fields, m.Name)
+				}
+				continue
+			}
+
+			// All slice fields must have a list-type tag except []byte
+			if m.Type.Kind == types.Slice && m.Type.Elem != types.Byte && !hasListType {
+				fields = append(fields, m.Name)
+				continue
+			}
+		}
+	}
+
+	return fields, nil
+}
+
+func hasNamedMember(t *types.Type, name string) bool {
+	for _, m := range t.Members {
+		if m.Name == name {
+			return true
+		}
+	}
+	return false
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/list_type_streaming_tags.go b/vendor/k8s.io/kube-openapi/pkg/generators/rules/list_type_streaming_tags.go
new file mode 100644
index 000000000..4f34d42ec
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/list_type_streaming_tags.go
@@ -0,0 +1,117 @@
+/*
+Copyright 2025 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package rules
+
+import (
+	"reflect"
+
+	"k8s.io/gengo/v2/types"
+)
+
+// StreamingListTypeFieldOrder implements APIRule interface.
+// Fields must be ordered TypeMeta, ListMeta, Items
+type StreamingListTypeFieldOrder struct{}
+
+func (l *StreamingListTypeFieldOrder) Name() string {
+	return "streaming_list_type_field_order"
+}
+func (l *StreamingListTypeFieldOrder) Validate(t *types.Type) ([]string, error) {
+	if !isListType(t) {
+		return nil, nil
+	}
+	var fields []string
+	if t.Members[0].Name != "TypeMeta" {
+		fields = append(fields, "TypeMeta")
+	}
+	if t.Members[1].Name != "ListMeta" {
+		fields = append(fields, "ListMeta")
+	}
+	if t.Members[2].Name != "Items" {
+		fields = append(fields, "Items")
+	}
+	return fields, nil
+}
+
+// StreamingListTypeJSONTags implements APIRule interface.
+// Fields must be JSON-tagged
+type StreamingListTypeJSONTags struct{}
+
+func (l *StreamingListTypeJSONTags) Name() string {
+	return "streaming_list_type_json_tags"
+}
+
+func (l *StreamingListTypeJSONTags) Validate(t *types.Type) ([]string, error) {
+	if !isListType(t) {
+		return nil, nil
+	}
+	var fields []string
+	for _, m := range t.Members {
+		switch m.Name {
+		case "TypeMeta":
+			if reflect.StructTag(m.Tags).Get("json") != ",inline" {
+				fields = append(fields, "TypeMeta")
+			}
+		case "ListMeta":
+			if reflect.StructTag(m.Tags).Get("json") != "metadata,omitempty" {
+				fields = append(fields, "ListMeta")
+			}
+		case "Items":
+			if reflect.StructTag(m.Tags).Get("json") != "items" {
+				fields = append(fields, "Items")
+			}
+		}
+	}
+	return fields, nil
+}
+
+// StreamingListTypeProtoTags implements APIRule interface.
+// Fields must be Proto-tagged with specific tags for streaming to work.
+type StreamingListTypeProtoTags struct{}
+
+func (l *StreamingListTypeProtoTags) Name() string {
+	return "streaming_list_type_proto_tags"
+}
+func (l *StreamingListTypeProtoTags) Validate(t *types.Type) ([]string, error) {
+	if !isListType(t) {
+		return nil, nil
+	}
+	var fields []string
+	for _, m := range t.Members {
+		switch m.Name {
+		case "TypeMeta":
+			if v := reflect.StructTag(m.Tags).Get("protobuf"); v != "" {
+				fields = append(fields, "TypeMeta")
+			}
+		case "ListMeta":
+			if v := reflect.StructTag(m.Tags).Get("protobuf"); v != "" && v != "bytes,1,opt,name=metadata" {
+				fields = append(fields, "ListMeta")
+			}
+		case "Items":
+			if v := reflect.StructTag(m.Tags).Get("protobuf"); v != "" && v != "bytes,2,rep,name=items" {
+				fields = append(fields, "Items")
+			}
+		}
+	}
+	return fields, nil
+}
+
+func isListType(t *types.Type) bool {
+	return len(t.Members) == 3 &&
+		hasNamedMember(t, "TypeMeta") &&
+		hasNamedMember(t, "ListMeta") &&
+		hasNamedMember(t, "Items")
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/names_match.go b/vendor/k8s.io/kube-openapi/pkg/generators/rules/names_match.go
new file mode 100644
index 000000000..d7655f0d9
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/names_match.go
@@ -0,0 +1,182 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package rules
+
+import (
+	"reflect"
+	"strings"
+
+	"k8s.io/kube-openapi/pkg/util/sets"
+
+	"k8s.io/gengo/v2/types"
+)
+
+var (
+	// Blacklist of JSON tags that should skip match evaluation
+	jsonTagBlacklist = sets.NewString(
+		// Omitted field is ignored by the package
+		"-",
+	)
+
+	// List of substrings that aren't allowed in Go name and JSON name
+	disallowedNameSubstrings = sets.NewString(
+		// Underscore is not allowed in either name
+		"_",
+		// Dash is not allowed in either name. Note that since dash is a valid JSON tag, this should be checked
+		// after JSON tag blacklist check.
+		"-",
+	)
+)
+
+/*
+NamesMatch implements APIRule interface.
+Go field names must be CamelCase. JSON field names must be camelCase. Other than capitalization of the
+initial letter, the two should almost always match. No underscores nor dashes in either.
+This rule verifies the convention "Other than capitalization of the initial letter, the two should almost always match."
+Examples (also in unit test):
+
+	Go name      | JSON name    | match
+	               podSpec        false
+	PodSpec        podSpec        true
+	PodSpec        PodSpec        false
+	podSpec        podSpec        false
+	PodSpec        spec           false
+	Spec           podSpec        false
+	JSONSpec       jsonSpec       true
+	JSONSpec       jsonspec       false
+	HTTPJSONSpec   httpJSONSpec   true
+
+NOTE: this validator cannot tell two sequential all-capital words from one word, therefore the case below
+is also considered matched.
+
+	HTTPJSONSpec   httpjsonSpec   true
+
+NOTE: an empty JSON name is valid only for inlined structs or pointer to structs.
+It cannot be empty for anything else because capitalization must be set explicitly.
+
+NOTE: metav1.ListMeta and metav1.ObjectMeta by convention must have "metadata" as name.
+Other fields may have that JSON name if the field name matches.
+*/
+type NamesMatch struct{}
+
+// Name returns the name of APIRule
+func (n *NamesMatch) Name() string {
+	return "names_match"
+}
+
+// Validate evaluates API rule on type t and returns a list of field names in
+// the type that violate the rule. Empty field name [""] implies the entire
+// type violates the rule.
+func (n *NamesMatch) Validate(t *types.Type) ([]string, error) {
+	fields := make([]string, 0)
+
+	// Only validate struct type and ignore the rest
+	switch t.Kind {
+	case types.Struct:
+		for _, m := range t.Members {
+			goName := m.Name
+			jsonTag, ok := reflect.StructTag(m.Tags).Lookup("json")
+			// Distinguish empty JSON tag and missing JSON tag. Empty JSON tag / name is
+			// allowed (in JSON name blacklist) but missing JSON tag is invalid.
+			if !ok {
+				fields = append(fields, goName)
+				continue
+			}
+			if jsonTagBlacklist.Has(jsonTag) {
+				continue
+			}
+			jsonName := strings.Split(jsonTag, ",")[0]
+			if !nameIsOkay(m, jsonName) {
+				fields = append(fields, goName)
+			}
+		}
+	}
+	return fields, nil
+}
+
+func nameIsOkay(member types.Member, jsonName string) bool {
+	if jsonName == "" {
+		return member.Type.Kind == types.Struct ||
+			member.Type.Kind == types.Pointer && member.Type.Elem.Kind == types.Struct
+	}
+
+	typeName := member.Type.String()
+	switch typeName {
+	case "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta",
+		"k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta":
+		return jsonName == "metadata"
+	}
+
+	return namesMatch(member.Name, jsonName)
+}
+
+// namesMatch evaluates if goName and jsonName match the API rule
+// TODO: Use an off-the-shelf CamelCase solution instead of implementing this logic. The following existing
+//
+//	      packages have been tried out:
+//			github.com/markbates/inflect
+//			github.com/segmentio/go-camelcase
+//			github.com/iancoleman/strcase
+//			github.com/fatih/camelcase
+//		 Please see https://github.com/kubernetes/kube-openapi/pull/83#issuecomment-400842314 for more details
+//		 about why they don't satisfy our need. What we need can be a function that detects an acronym at the
+//		 beginning of a string.
+func namesMatch(goName, jsonName string) bool {
+	if !isAllowedName(goName) || !isAllowedName(jsonName) {
+		return false
+	}
+	if !strings.EqualFold(goName, jsonName) {
+		return false
+	}
+	// Go field names must be CamelCase. JSON field names must be camelCase.
+	if !isCapital(goName[0]) || isCapital(jsonName[0]) {
+		return false
+	}
+	for i := 0; i < len(goName); i++ {
+		if goName[i] == jsonName[i] {
+			// goName[0:i-1] is uppercase and jsonName[0:i-1] is lowercase, goName[i:]
+			// and jsonName[i:] should match;
+			// goName[i] should be lowercase if i is equal to 1, e.g.:
+			//	goName   | jsonName
+			//	PodSpec     podSpec
+			// or uppercase if i is greater than 1, e.g.:
+			//      goname   | jsonName
+			//      JSONSpec   jsonSpec
+			// This is to rule out cases like:
+			//      goname   | jsonName
+			//      JSONSpec   jsonspec
+			return goName[i:] == jsonName[i:] && (i == 1 || isCapital(goName[i]))
+		}
+	}
+	return true
+}
+
+// isCapital returns true if one character is capital
+func isCapital(b byte) bool {
+	return b >= 'A' && b <= 'Z'
+}
+
+// isAllowedName checks the list of disallowedNameSubstrings and returns true if name doesn't contain
+// any disallowed substring.
+func isAllowedName(name string) bool {
+	for _, substr := range disallowedNameSubstrings.UnsortedList() {
+		if strings.Contains(name, substr) {
+			return false
+		}
+	}
+	return true
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/rules/omitempty_match_case.go b/vendor/k8s.io/kube-openapi/pkg/generators/rules/omitempty_match_case.go
new file mode 100644
index 000000000..d83875964
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/rules/omitempty_match_case.go
@@ -0,0 +1,64 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package rules
+
+import (
+	"reflect"
+	"strings"
+
+	"k8s.io/gengo/v2/types"
+)
+
+// OmitEmptyMatchCase implements APIRule interface.
+// "omitempty" must appear verbatim (no case variants).
+type OmitEmptyMatchCase struct{}
+
+func (n *OmitEmptyMatchCase) Name() string {
+	return "omitempty_match_case"
+}
+
+func (n *OmitEmptyMatchCase) Validate(t *types.Type) ([]string, error) {
+	fields := make([]string, 0)
+
+	// Only validate struct type and ignore the rest
+	switch t.Kind {
+	case types.Struct:
+		for _, m := range t.Members {
+			goName := m.Name
+			jsonTag, ok := reflect.StructTag(m.Tags).Lookup("json")
+			if !ok {
+				continue
+			}
+
+			parts := strings.Split(jsonTag, ",")
+			if len(parts) < 2 {
+				// no tags other than name
+				continue
+			}
+			if parts[0] == "-" {
+				// not serialized
+				continue
+			}
+			for _, part := range parts[1:] {
+				if strings.EqualFold(part, "omitempty") && part != "omitempty" {
+					fields = append(fields, goName)
+				}
+			}
+		}
+	}
+	return fields, nil
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/generators/union.go b/vendor/k8s.io/kube-openapi/pkg/generators/union.go
new file mode 100644
index 000000000..bfcba1ad7
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/generators/union.go
@@ -0,0 +1,208 @@
+/*
+Copyright 2016 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package generators
+
+import (
+	"fmt"
+	"sort"
+
+	"k8s.io/gengo/v2"
+	"k8s.io/gengo/v2/types"
+)
+
+const tagUnionMember = "union"
+const tagUnionDeprecated = "unionDeprecated"
+const tagUnionDiscriminator = "unionDiscriminator"
+
+type union struct {
+	discriminator         string
+	fieldsToDiscriminated map[string]string
+}
+
+// emit prints the union, can be called on a nil union (emits nothing)
+func (u *union) emit(g openAPITypeWriter) {
+	if u == nil {
+		return
+	}
+	g.Do("map[string]interface{}{\n", nil)
+	if u.discriminator != "" {
+		g.Do("\"discriminator\": \"$.$\",\n", u.discriminator)
+	}
+	g.Do("\"fields-to-discriminateBy\": map[string]interface{}{\n", nil)
+	keys := []string{}
+	for field := range u.fieldsToDiscriminated {
+		keys = append(keys, field)
+	}
+	sort.Strings(keys)
+	for _, field := range keys {
+		g.Do("\"$.$\": ", field)
+		g.Do("\"$.$\",\n", u.fieldsToDiscriminated[field])
+	}
+	g.Do("},\n", nil)
+	g.Do("},\n", nil)
+}
+
+// Sets the discriminator if it's not set yet, otherwise return an error
+func (u *union) setDiscriminator(value string) []error {
+	errors := []error{}
+	if u.discriminator != "" {
+		errors = append(errors, fmt.Errorf("at least two discriminators found: %v and %v", value, u.discriminator))
+	}
+	u.discriminator = value
+	return errors
+}
+
+// Add a new member to the union
+func (u *union) addMember(jsonName, variableName string) {
+	if _, ok := u.fieldsToDiscriminated[jsonName]; ok {
+		panic(fmt.Errorf("same field (%v) found multiple times", jsonName))
+	}
+	u.fieldsToDiscriminated[jsonName] = variableName
+}
+
+// Makes sure that the union is valid, specifically looking for re-used discriminated
+func (u *union) isValid() []error {
+	errors := []error{}
+	// Case 1: discriminator but no fields
+	if u.discriminator != "" && len(u.fieldsToDiscriminated) == 0 {
+		errors = append(errors, fmt.Errorf("discriminator set with no fields in union"))
+	}
+	// Case 2: two fields have the same discriminated value
+	discriminated := map[string]struct{}{}
+	for _, d := range u.fieldsToDiscriminated {
+		if _, ok := discriminated[d]; ok {
+			errors = append(errors, fmt.Errorf("discriminated value is used twice: %v", d))
+		}
+		discriminated[d] = struct{}{}
+	}
+	// Case 3: a field is both discriminator AND part of the union
+	if u.discriminator != "" {
+		if _, ok := u.fieldsToDiscriminated[u.discriminator]; ok {
+			errors = append(errors, fmt.Errorf("%v can't be both discriminator and part of the union", u.discriminator))
+		}
+	}
+	return errors
+}
+
+// Find unions either directly on the members (or inlined members, not
+// going across types) or on the type itself, or on embedded types.
+func parseUnions(t *types.Type) ([]union, []error) {
+	errors := []error{}
+	unions := []union{}
+	su, err := parseUnionStruct(t)
+	if su != nil {
+		unions = append(unions, *su)
+	}
+	errors = append(errors, err...)
+	eu, err := parseEmbeddedUnion(t)
+	unions = append(unions, eu...)
+	errors = append(errors, err...)
+	mu, err := parseUnionMembers(t)
+	if mu != nil {
+		unions = append(unions, *mu)
+	}
+	errors = append(errors, err...)
+	return unions, errors
+}
+
+// Find unions in embedded types, unions shouldn't go across types.
+func parseEmbeddedUnion(t *types.Type) ([]union, []error) {
+	errors := []error{}
+	unions := []union{}
+	for _, m := range t.Members {
+		if hasOpenAPITagValue(m.CommentLines, tagValueFalse) {
+			continue
+		}
+		if !shouldInlineMembers(&m) {
+			continue
+		}
+		u, err := parseUnions(m.Type)
+		unions = append(unions, u...)
+		errors = append(errors, err...)
+	}
+	return unions, errors
+}
+
+// Look for union tag on a struct, and then include all the fields
+// (except the discriminator if there is one). The struct shouldn't have
+// embedded types.
+func parseUnionStruct(t *types.Type) (*union, []error) {
+	errors := []error{}
+	if gengo.ExtractCommentTags("+", t.CommentLines)[tagUnionMember] == nil {
+		return nil, nil
+	}
+
+	u := &union{fieldsToDiscriminated: map[string]string{}}
+
+	for _, m := range t.Members {
+		jsonName := getReferableName(&m)
+		if jsonName == "" {
+			continue
+		}
+		if shouldInlineMembers(&m) {
+			errors = append(errors, fmt.Errorf("union structures can't have embedded fields: %v.%v", t.Name, m.Name))
+			continue
+		}
+		if gengo.ExtractCommentTags("+", m.CommentLines)[tagUnionDeprecated] != nil {
+			errors = append(errors, fmt.Errorf("union struct can't have unionDeprecated members: %v.%v", t.Name, m.Name))
+			continue
+		}
+		if gengo.ExtractCommentTags("+", m.CommentLines)[tagUnionDiscriminator] != nil {
+			errors = append(errors, u.setDiscriminator(jsonName)...)
+		} else {
+			if optional, err := isOptional(&m); !optional || err != nil {
+				errors = append(errors, fmt.Errorf("union members must be optional: %v.%v", t.Name, m.Name))
+			}
+			u.addMember(jsonName, m.Name)
+		}
+	}
+
+	return u, errors
+}
+
+// Find unions specifically on members.
+func parseUnionMembers(t *types.Type) (*union, []error) {
+	errors := []error{}
+	u := &union{fieldsToDiscriminated: map[string]string{}}
+
+	for _, m := range t.Members {
+		jsonName := getReferableName(&m)
+		if jsonName == "" {
+			continue
+		}
+		if shouldInlineMembers(&m) {
+			continue
+		}
+		if gengo.ExtractCommentTags("+", m.CommentLines)[tagUnionDiscriminator] != nil {
+			errors = append(errors, u.setDiscriminator(jsonName)...)
+		}
+		if gengo.ExtractCommentTags("+", m.CommentLines)[tagUnionMember] != nil {
+			errors = append(errors, fmt.Errorf("union tag is not accepted on struct members: %v.%v", t.Name, m.Name))
+			continue
+		}
+		if gengo.ExtractCommentTags("+", m.CommentLines)[tagUnionDeprecated] != nil {
+			if optional, err := isOptional(&m); !optional || err != nil {
+				errors = append(errors, fmt.Errorf("union members must be optional: %v.%v", t.Name, m.Name))
+			}
+			u.addMember(jsonName, m.Name)
+		}
+	}
+	if len(u.fieldsToDiscriminated) == 0 {
+		return nil, nil
+	}
+	return u, append(errors, u.isValid()...)
+}
diff --git a/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go b/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
index 61141a500..81280aae6 100644
--- a/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
+++ b/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
@@ -22,7 +22,7 @@ import (
 	"strings"
 
 	"k8s.io/kube-openapi/pkg/validation/spec"
-	"sigs.k8s.io/structured-merge-diff/v4/schema"
+	"sigs.k8s.io/structured-merge-diff/v6/schema"
 )
 
 // ToSchemaFromOpenAPI converts a directory of OpenAPI schemas to an smd Schema.
diff --git a/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go b/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
index 2c6fd76a9..e40f6056e 100644
--- a/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
+++ b/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
@@ -22,7 +22,7 @@ import (
 	"strings"
 
 	"k8s.io/kube-openapi/pkg/util/proto"
-	"sigs.k8s.io/structured-merge-diff/v4/schema"
+	"sigs.k8s.io/structured-merge-diff/v6/schema"
 )
 
 // ToSchema converts openapi definitions into a schema suitable for structured
diff --git a/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go b/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
index 9887d185b..c4a083cb4 100644
--- a/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
+++ b/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
@@ -20,7 +20,7 @@ import (
 	"fmt"
 	"sort"
 
-	"sigs.k8s.io/structured-merge-diff/v4/schema"
+	"sigs.k8s.io/structured-merge-diff/v6/schema"
 )
 
 const (
diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
index 1b758ab25..c7b69b200 100644
--- a/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
+++ b/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
@@ -22,7 +22,7 @@ import (
 	"strings"
 
 	openapi_v2 "github.com/google/gnostic-models/openapiv2"
-	yaml "sigs.k8s.io/yaml/goyaml.v2"
+	yaml "go.yaml.in/yaml/v2"
 )
 
 func newSchemaError(path *Path, format string, a ...interface{}) error {
diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
index d9f2896e3..8694c6c76 100644
--- a/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
+++ b/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
@@ -22,7 +22,7 @@ import (
 	"strings"
 
 	openapi_v3 "github.com/google/gnostic-models/openapiv3"
-	"gopkg.in/yaml.v3"
+	"go.yaml.in/yaml/v3"
 )
 
 // Temporary parse implementation to be used until gnostic->kube-openapi conversion
diff --git a/vendor/k8s.io/kube-openapi/pkg/util/sets/empty.go b/vendor/k8s.io/kube-openapi/pkg/util/sets/empty.go
new file mode 100644
index 000000000..13303ea89
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/util/sets/empty.go
@@ -0,0 +1,27 @@
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by set-gen. DO NOT EDIT.
+
+// NOTE: This file is copied from k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/sets/empty.go
+// because in Kubernetes we don't allowed vendor code to import staging code. See
+// https://github.com/kubernetes/kube-openapi/pull/90 for more details.
+
+package sets
+
+// Empty is public since it is used by some internal API objects for conversions between external
+// string arrays and internal sets, and conversion logic requires public types today.
+type Empty struct{}
diff --git a/vendor/k8s.io/kube-openapi/pkg/util/sets/string.go b/vendor/k8s.io/kube-openapi/pkg/util/sets/string.go
new file mode 100644
index 000000000..53f2bc12a
--- /dev/null
+++ b/vendor/k8s.io/kube-openapi/pkg/util/sets/string.go
@@ -0,0 +1,207 @@
+/*
+Copyright The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Code generated by set-gen. DO NOT EDIT.
+
+// NOTE: This file is copied from k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/sets/string.go
+// because in Kubernetes we don't allowed vendor code to import staging code. See
+// https://github.com/kubernetes/kube-openapi/pull/90 for more details.
+
+package sets
+
+import (
+	"reflect"
+	"sort"
+)
+
+// sets.String is a set of strings, implemented via map[string]struct{} for minimal memory consumption.
+type String map[string]Empty
+
+// NewString creates a String from a list of values.
+func NewString(items ...string) String {
+	ss := String{}
+	ss.Insert(items...)
+	return ss
+}
+
+// StringKeySet creates a String from a keys of a map[string](? extends interface{}).
+// If the value passed in is not actually a map, this will panic.
+func StringKeySet(theMap interface{}) String {
+	v := reflect.ValueOf(theMap)
+	ret := String{}
+
+	for _, keyValue := range v.MapKeys() {
+		ret.Insert(keyValue.Interface().(string))
+	}
+	return ret
+}
+
+// Insert adds items to the set.
+func (s String) Insert(items ...string) {
+	for _, item := range items {
+		s[item] = Empty{}
+	}
+}
+
+// Delete removes all items from the set.
+func (s String) Delete(items ...string) {
+	for _, item := range items {
+		delete(s, item)
+	}
+}
+
+// Has returns true if and only if item is contained in the set.
+func (s String) Has(item string) bool {
+	_, contained := s[item]
+	return contained
+}
+
+// HasAll returns true if and only if all items are contained in the set.
+func (s String) HasAll(items ...string) bool {
+	for _, item := range items {
+		if !s.Has(item) {
+			return false
+		}
+	}
+	return true
+}
+
+// HasAny returns true if any items are contained in the set.
+func (s String) HasAny(items ...string) bool {
+	for _, item := range items {
+		if s.Has(item) {
+			return true
+		}
+	}
+	return false
+}
+
+// Difference returns a set of objects that are not in s2
+// For example:
+// s1 = {a1, a2, a3}
+// s2 = {a1, a2, a4, a5}
+// s1.Difference(s2) = {a3}
+// s2.Difference(s1) = {a4, a5}
+func (s String) Difference(s2 String) String {
+	result := NewString()
+	for key := range s {
+		if !s2.Has(key) {
+			result.Insert(key)
+		}
+	}
+	return result
+}
+
+// Union returns a new set which includes items in either s1 or s2.
+// For example:
+// s1 = {a1, a2}
+// s2 = {a3, a4}
+// s1.Union(s2) = {a1, a2, a3, a4}
+// s2.Union(s1) = {a1, a2, a3, a4}
+func (s1 String) Union(s2 String) String {
+	result := NewString()
+	for key := range s1 {
+		result.Insert(key)
+	}
+	for key := range s2 {
+		result.Insert(key)
+	}
+	return result
+}
+
+// Intersection returns a new set which includes the item in BOTH s1 and s2
+// For example:
+// s1 = {a1, a2}
+// s2 = {a2, a3}
+// s1.Intersection(s2) = {a2}
+func (s1 String) Intersection(s2 String) String {
+	var walk, other String
+	result := NewString()
+	if s1.Len() < s2.Len() {
+		walk = s1
+		other = s2
+	} else {
+		walk = s2
+		other = s1
+	}
+	for key := range walk {
+		if other.Has(key) {
+			result.Insert(key)
+		}
+	}
+	return result
+}
+
+// IsSuperset returns true if and only if s1 is a superset of s2.
+func (s1 String) IsSuperset(s2 String) bool {
+	for item := range s2 {
+		if !s1.Has(item) {
+			return false
+		}
+	}
+	return true
+}
+
+// Equal returns true if and only if s1 is equal (as a set) to s2.
+// Two sets are equal if their membership is identical.
+// (In practice, this means same elements, order doesn't matter)
+func (s1 String) Equal(s2 String) bool {
+	return len(s1) == len(s2) && s1.IsSuperset(s2)
+}
+
+type sortableSliceOfString []string
+
+func (s sortableSliceOfString) Len() int           { return len(s) }
+func (s sortableSliceOfString) Less(i, j int) bool { return lessString(s[i], s[j]) }
+func (s sortableSliceOfString) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
+
+// List returns the contents as a sorted string slice.
+func (s String) List() []string {
+	res := make(sortableSliceOfString, 0, len(s))
+	for key := range s {
+		res = append(res, key)
+	}
+	sort.Sort(res)
+	return []string(res)
+}
+
+// UnsortedList returns the slice with contents in random order.
+func (s String) UnsortedList() []string {
+	res := make([]string, 0, len(s))
+	for key := range s {
+		res = append(res, key)
+	}
+	return res
+}
+
+// Returns a single element from the set.
+func (s String) PopAny() (string, bool) {
+	for key := range s {
+		s.Delete(key)
+		return key, true
+	}
+	var zeroValue string
+	return zeroValue, false
+}
+
+// Len returns the size of the set.
+func (s String) Len() int {
+	return len(s)
+}
+
+func lessString(lhs, rhs string) bool {
+	return lhs < rhs
+}
diff --git a/vendor/modules.txt b/vendor/modules.txt
index e4a7ae374..938c9a06f 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -37,6 +37,9 @@ github.com/evanphx/json-patch/v5/internal/json
 # github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d
 ## explicit
 github.com/exponent-io/jsonpath
+# github.com/fatih/color v1.18.0
+## explicit; go 1.17
+github.com/fatih/color
 # github.com/fsnotify/fsnotify v1.7.0
 ## explicit; go 1.17
 github.com/fsnotify/fsnotify
@@ -67,6 +70,9 @@ github.com/go-openapi/swag
 # github.com/go-task/slim-sprig/v3 v3.0.0
 ## explicit; go 1.20
 github.com/go-task/slim-sprig/v3
+# github.com/gobuffalo/flect v1.0.3
+## explicit; go 1.16
+github.com/gobuffalo/flect
 # github.com/gogo/protobuf v1.3.2
 ## explicit; go 1.15
 github.com/gogo/protobuf/proto
@@ -74,8 +80,8 @@ github.com/gogo/protobuf/sortkeys
 # github.com/google/btree v1.1.3
 ## explicit; go 1.18
 github.com/google/btree
-# github.com/google/gnostic-models v0.6.9
-## explicit; go 1.21
+# github.com/google/gnostic-models v0.7.0
+## explicit; go 1.22
 github.com/google/gnostic-models/compiler
 github.com/google/gnostic-models/extensions
 github.com/google/gnostic-models/jsonschema
@@ -88,7 +94,7 @@ github.com/google/go-cmp/cmp/internal/diff
 github.com/google/go-cmp/cmp/internal/flags
 github.com/google/go-cmp/cmp/internal/function
 github.com/google/go-cmp/cmp/internal/value
-# github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db
+# github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad
 ## explicit; go 1.22
 github.com/google/pprof/profile
 # github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
@@ -106,6 +112,9 @@ github.com/huandu/xstrings
 # github.com/imdario/mergo v0.3.15
 ## explicit; go 1.13
 github.com/imdario/mergo
+# github.com/inconshreveable/mousetrap v1.1.0
+## explicit; go 1.18
+github.com/inconshreveable/mousetrap
 # github.com/josharian/intern v1.0.0
 ## explicit; go 1.5
 github.com/josharian/intern
@@ -117,6 +126,12 @@ github.com/json-iterator/go
 github.com/mailru/easyjson/buffer
 github.com/mailru/easyjson/jlexer
 github.com/mailru/easyjson/jwriter
+# github.com/mattn/go-colorable v0.1.13
+## explicit; go 1.15
+github.com/mattn/go-colorable
+# github.com/mattn/go-isatty v0.0.20
+## explicit; go 1.15
+github.com/mattn/go-isatty
 # github.com/mitchellh/copystructure v1.0.0
 ## explicit
 github.com/mitchellh/copystructure
@@ -142,8 +157,8 @@ github.com/munnerz/goautoneg
 # github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f
 ## explicit
 github.com/mxk/go-flowrate/flowrate
-# github.com/onsi/ginkgo/v2 v2.22.0
-## explicit; go 1.22.0
+# github.com/onsi/ginkgo/v2 v2.23.3
+## explicit; go 1.23.0
 github.com/onsi/ginkgo/v2
 github.com/onsi/ginkgo/v2/config
 github.com/onsi/ginkgo/v2/formatter
@@ -164,8 +179,8 @@ github.com/onsi/ginkgo/v2/internal/parallel_support
 github.com/onsi/ginkgo/v2/internal/testingtproxy
 github.com/onsi/ginkgo/v2/reporters
 github.com/onsi/ginkgo/v2/types
-# github.com/onsi/gomega v1.36.1
-## explicit; go 1.22
+# github.com/onsi/gomega v1.37.0
+## explicit; go 1.23.0
 github.com/onsi/gomega
 github.com/onsi/gomega/format
 github.com/onsi/gomega/gcustom
@@ -302,7 +317,10 @@ github.com/shopspring/decimal
 # github.com/spf13/cast v1.3.1
 ## explicit
 github.com/spf13/cast
-# github.com/spf13/pflag v1.0.5
+# github.com/spf13/cobra v1.9.1
+## explicit; go 1.15
+github.com/spf13/cobra
+# github.com/spf13/pflag v1.0.6
 ## explicit; go 1.12
 github.com/spf13/pflag
 # github.com/x448/float16 v0.8.4
@@ -333,15 +351,25 @@ go.uber.org/zap/internal/exit
 go.uber.org/zap/internal/pool
 go.uber.org/zap/internal/stacktrace
 go.uber.org/zap/zapcore
-# golang.org/x/crypto v0.36.0
+# go.yaml.in/yaml/v2 v2.4.2
+## explicit; go 1.15
+go.yaml.in/yaml/v2
+# go.yaml.in/yaml/v3 v3.0.3
+## explicit; go 1.22
+go.yaml.in/yaml/v3
+# golang.org/x/crypto v0.37.0
 ## explicit; go 1.23.0
 golang.org/x/crypto/bcrypt
 golang.org/x/crypto/blowfish
 golang.org/x/crypto/pbkdf2
 golang.org/x/crypto/scrypt
-# golang.org/x/net v0.38.0
+# golang.org/x/mod v0.24.0
+## explicit; go 1.23.0
+golang.org/x/mod/internal/lazyregexp
+golang.org/x/mod/module
+golang.org/x/mod/semver
+# golang.org/x/net v0.39.0
 ## explicit; go 1.23.0
-golang.org/x/net/context
 golang.org/x/net/html
 golang.org/x/net/html/atom
 golang.org/x/net/html/charset
@@ -357,18 +385,18 @@ golang.org/x/net/websocket
 ## explicit; go 1.23.0
 golang.org/x/oauth2
 golang.org/x/oauth2/internal
-# golang.org/x/sync v0.12.0
+# golang.org/x/sync v0.13.0
 ## explicit; go 1.23.0
 golang.org/x/sync/errgroup
-# golang.org/x/sys v0.31.0
+# golang.org/x/sys v0.32.0
 ## explicit; go 1.23.0
 golang.org/x/sys/plan9
 golang.org/x/sys/unix
 golang.org/x/sys/windows
-# golang.org/x/term v0.30.0
+# golang.org/x/term v0.31.0
 ## explicit; go 1.23.0
 golang.org/x/term
-# golang.org/x/text v0.23.0
+# golang.org/x/text v0.24.0
 ## explicit; go 1.23.0
 golang.org/x/text/encoding
 golang.org/x/text/encoding/charmap
@@ -393,10 +421,33 @@ golang.org/x/text/unicode/norm
 # golang.org/x/time v0.9.0
 ## explicit; go 1.18
 golang.org/x/time/rate
-# golang.org/x/tools v0.26.0
-## explicit; go 1.22.0
+# golang.org/x/tools v0.32.0
+## explicit; go 1.23.0
 golang.org/x/tools/cover
+golang.org/x/tools/go/ast/astutil
 golang.org/x/tools/go/ast/inspector
+golang.org/x/tools/go/gcexportdata
+golang.org/x/tools/go/packages
+golang.org/x/tools/go/types/objectpath
+golang.org/x/tools/go/types/typeutil
+golang.org/x/tools/imports
+golang.org/x/tools/internal/aliases
+golang.org/x/tools/internal/astutil/edge
+golang.org/x/tools/internal/event
+golang.org/x/tools/internal/event/core
+golang.org/x/tools/internal/event/keys
+golang.org/x/tools/internal/event/label
+golang.org/x/tools/internal/gcimporter
+golang.org/x/tools/internal/gocommand
+golang.org/x/tools/internal/gopathwalk
+golang.org/x/tools/internal/imports
+golang.org/x/tools/internal/modindex
+golang.org/x/tools/internal/packagesinternal
+golang.org/x/tools/internal/pkgbits
+golang.org/x/tools/internal/stdlib
+golang.org/x/tools/internal/typeparams
+golang.org/x/tools/internal/typesinternal
+golang.org/x/tools/internal/versions
 # gomodules.xyz/jsonpatch/v2 v2.4.0
 ## explicit; go 1.20
 gomodules.xyz/jsonpatch/v2
@@ -511,6 +562,7 @@ k8s.io/api/storagemigration/v1alpha1
 ## explicit; go 1.24.0
 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions
 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1
+k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1
 # k8s.io/apimachinery v0.33.3
 ## explicit; go 1.24.0
 k8s.io/apimachinery/pkg/api/equality
@@ -866,6 +918,20 @@ k8s.io/client-go/util/jsonpath
 k8s.io/client-go/util/keyutil
 k8s.io/client-go/util/watchlist
 k8s.io/client-go/util/workqueue
+# k8s.io/code-generator v0.33.0
+## explicit; go 1.24.0
+k8s.io/code-generator/cmd/applyconfiguration-gen/args
+k8s.io/code-generator/cmd/applyconfiguration-gen/generators
+k8s.io/code-generator/cmd/client-gen/generators/util
+k8s.io/code-generator/cmd/client-gen/types
+# k8s.io/gengo/v2 v2.0.0-20250604051438-85fd79dbfd9f
+## explicit; go 1.20
+k8s.io/gengo/v2
+k8s.io/gengo/v2/codetags
+k8s.io/gengo/v2/generator
+k8s.io/gengo/v2/namer
+k8s.io/gengo/v2/parser
+k8s.io/gengo/v2/types
 # k8s.io/klog/v2 v2.130.1
 ## explicit; go 1.18
 k8s.io/klog/v2
@@ -875,10 +941,14 @@ k8s.io/klog/v2/internal/dbg
 k8s.io/klog/v2/internal/serialize
 k8s.io/klog/v2/internal/severity
 k8s.io/klog/v2/internal/sloghandler
-# k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff
-## explicit; go 1.21
+# k8s.io/kube-openapi v0.0.0-20250814151709-d7b6acb124c3
+## explicit; go 1.23
+k8s.io/kube-openapi/cmd/openapi-gen
+k8s.io/kube-openapi/cmd/openapi-gen/args
 k8s.io/kube-openapi/pkg/cached
 k8s.io/kube-openapi/pkg/common
+k8s.io/kube-openapi/pkg/generators
+k8s.io/kube-openapi/pkg/generators/rules
 k8s.io/kube-openapi/pkg/handler3
 k8s.io/kube-openapi/pkg/internal
 k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json
@@ -886,6 +956,7 @@ k8s.io/kube-openapi/pkg/schemaconv
 k8s.io/kube-openapi/pkg/spec3
 k8s.io/kube-openapi/pkg/util/proto
 k8s.io/kube-openapi/pkg/util/proto/validation
+k8s.io/kube-openapi/pkg/util/sets
 k8s.io/kube-openapi/pkg/validation/spec
 # k8s.io/kubectl v0.28.2
 ## explicit; go 1.20
@@ -951,6 +1022,23 @@ sigs.k8s.io/controller-runtime/pkg/webhook/admission
 sigs.k8s.io/controller-runtime/pkg/webhook/admission/metrics
 sigs.k8s.io/controller-runtime/pkg/webhook/conversion
 sigs.k8s.io/controller-runtime/pkg/webhook/internal/metrics
+# sigs.k8s.io/controller-tools v0.18.0
+## explicit; go 1.24.0
+sigs.k8s.io/controller-tools/cmd/controller-gen
+sigs.k8s.io/controller-tools/pkg/applyconfiguration
+sigs.k8s.io/controller-tools/pkg/crd
+sigs.k8s.io/controller-tools/pkg/crd/markers
+sigs.k8s.io/controller-tools/pkg/deepcopy
+sigs.k8s.io/controller-tools/pkg/genall
+sigs.k8s.io/controller-tools/pkg/genall/help
+sigs.k8s.io/controller-tools/pkg/genall/help/pretty
+sigs.k8s.io/controller-tools/pkg/loader
+sigs.k8s.io/controller-tools/pkg/markers
+sigs.k8s.io/controller-tools/pkg/rbac
+sigs.k8s.io/controller-tools/pkg/schemapatcher
+sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml
+sigs.k8s.io/controller-tools/pkg/version
+sigs.k8s.io/controller-tools/pkg/webhook
 # sigs.k8s.io/e2e-framework v0.3.0
 ## explicit; go 1.19
 sigs.k8s.io/e2e-framework/klient/conf
@@ -1057,6 +1145,9 @@ sigs.k8s.io/structured-merge-diff/v4/merge
 sigs.k8s.io/structured-merge-diff/v4/schema
 sigs.k8s.io/structured-merge-diff/v4/typed
 sigs.k8s.io/structured-merge-diff/v4/value
+# sigs.k8s.io/structured-merge-diff/v6 v6.2.0
+## explicit; go 1.23
+sigs.k8s.io/structured-merge-diff/v6/schema
 # sigs.k8s.io/yaml v1.4.0
 ## explicit; go 1.12
 sigs.k8s.io/yaml
diff --git a/vendor/sigs.k8s.io/controller-tools/LICENSE b/vendor/sigs.k8s.io/controller-tools/LICENSE
new file mode 100644
index 000000000..8dada3eda
--- /dev/null
+++ b/vendor/sigs.k8s.io/controller-tools/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright {yyyy} {name of copyright owner}
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go b/vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go
new file mode 100644
index 000000000..b421028a9
--- /dev/null
+++ b/vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go
@@ -0,0 +1,276 @@
+/*
+Copyright 2018 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+package main
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+
+	"github.com/spf13/cobra"
+	"golang.org/x/tools/go/packages"
+
+	"sigs.k8s.io/controller-tools/pkg/applyconfiguration"
+	"sigs.k8s.io/controller-tools/pkg/crd"
+	"sigs.k8s.io/controller-tools/pkg/deepcopy"
+	"sigs.k8s.io/controller-tools/pkg/genall"
+	"sigs.k8s.io/controller-tools/pkg/genall/help"
+	prettyhelp "sigs.k8s.io/controller-tools/pkg/genall/help/pretty"
+	"sigs.k8s.io/controller-tools/pkg/markers"
+	"sigs.k8s.io/controller-tools/pkg/rbac"
+	"sigs.k8s.io/controller-tools/pkg/schemapatcher"
+	"sigs.k8s.io/controller-tools/pkg/version"
+	"sigs.k8s.io/controller-tools/pkg/webhook"
+)
+
+//go:generate go run ../helpgen/main.go paths=../../pkg/... generate:headerFile=../../boilerplate.go.txt,year=2019
+
+// Options are specified to controller-gen by turning generators and output rules into
+// markers, and then parsing them using the standard registry logic (without the "+").
+// Each marker and output rule should thus be usable as a marker target.
+
+var (
+	// allGenerators maintains the list of all known generators, giving
+	// them names for use on the command line.
+	// each turns into a command line option,
+	// and has options for output forms.
+	allGenerators = map[string]genall.Generator{
+		"crd":                crd.Generator{},
+		"rbac":               rbac.Generator{},
+		"object":             deepcopy.Generator{},
+		"applyconfiguration": applyconfiguration.Generator{},
+		"webhook":            webhook.Generator{},
+		"schemapatch":        schemapatcher.Generator{},
+	}
+
+	// allOutputRules defines the list of all known output rules, giving
+	// them names for use on the command line.
+	// Each output rule turns into two command line options:
+	// - output::
(per-generator output) + // - output: (default output) + allOutputRules = map[string]genall.OutputRule{ + "dir": genall.OutputToDirectory(""), + "none": genall.OutputToNothing, + "stdout": genall.OutputToStdout, + "artifacts": genall.OutputArtifacts{}, + } + + // optionsRegistry contains all the marker definitions used to process command line options + optionsRegistry = &markers.Registry{} +) + +func init() { + for genName, gen := range allGenerators { + // make the generator options marker itself + defn := markers.Must(markers.MakeDefinition(genName, markers.DescribesPackage, gen)) + if err := optionsRegistry.Register(defn); err != nil { + panic(err) + } + if helpGiver, hasHelp := gen.(genall.HasHelp); hasHelp { + if help := helpGiver.Help(); help != nil { + optionsRegistry.AddHelp(defn, help) + } + } + + // make per-generation output rule markers + for ruleName, rule := range allOutputRules { + ruleMarker := markers.Must(markers.MakeDefinition(fmt.Sprintf("output:%s:%s", genName, ruleName), markers.DescribesPackage, rule)) + if err := optionsRegistry.Register(ruleMarker); err != nil { + panic(err) + } + if helpGiver, hasHelp := rule.(genall.HasHelp); hasHelp { + if help := helpGiver.Help(); help != nil { + optionsRegistry.AddHelp(ruleMarker, help) + } + } + } + } + + // make "default output" output rule markers + for ruleName, rule := range allOutputRules { + ruleMarker := markers.Must(markers.MakeDefinition("output:"+ruleName, markers.DescribesPackage, rule)) + if err := optionsRegistry.Register(ruleMarker); err != nil { + panic(err) + } + if helpGiver, hasHelp := rule.(genall.HasHelp); hasHelp { + if help := helpGiver.Help(); help != nil { + optionsRegistry.AddHelp(ruleMarker, help) + } + } + } + + // add in the common options markers + if err := genall.RegisterOptionsMarkers(optionsRegistry); err != nil { + panic(err) + } +} + +// noUsageError suppresses usage printing when it occurs +// (since cobra doesn't provide a good way to avoid printing +// out usage in only certain situations). +type noUsageError struct{ error } + +func main() { + helpLevel := 0 + whichLevel := 0 + showVersion := false + var buildTags []string + + cmd := &cobra.Command{ + Use: "controller-gen", + Short: "Generate Kubernetes API extension resources and code.", + Long: "Generate Kubernetes API extension resources and code.", + Example: ` # Generate RBAC manifests and crds for all types under apis/, + # outputting crds to /tmp/crds and everything else to stdout + controller-gen rbac:roleName= crd paths=./apis/... output:crd:dir=/tmp/crds output:stdout + + # Generate deepcopy/runtime.Object implementations for a particular file + controller-gen object paths=./apis/v1beta1/some_types.go + + # Generate OpenAPI v3 schemas for API packages and merge them into existing CRD manifests + controller-gen schemapatch:manifests=./manifests output:dir=./manifests paths=./pkg/apis/... + + # Run all the generators for a given project + controller-gen paths=./apis/... + + # Explain the markers for generating CRDs, and their arguments + controller-gen crd -ww + + # Generate applyconfigurations for CRDs for use with Server Side Apply. They will be placed + # into a "applyconfiguration/" subdirectory + + controller-gen applyconfiguration paths=./apis/... +`, + RunE: func(c *cobra.Command, rawOpts []string) error { + // print version if asked for it + if showVersion { + version.Print() + return nil + } + + // print the help if we asked for it (since we've got a different help flag :-/), then bail + if helpLevel > 0 { + return c.Usage() + } + + // print the marker docs if we asked for them, then bail + if whichLevel > 0 { + return printMarkerDocs(c, rawOpts, whichLevel) + } + + // otherwise, set up the runtime for actually running the generators + tagsFlag := fmt.Sprintf("-tags=%s", strings.Join(buildTags, ",")) + rt, err := genall.FromOptionsWithConfig(&packages.Config{BuildFlags: []string{tagsFlag}}, optionsRegistry, rawOpts) + if err != nil { + return err + } + if len(rt.Generators) == 0 { + return fmt.Errorf("no generators specified") + } + + if hadErrs := rt.Run(); hadErrs { + // don't obscure the actual error with a bunch of usage + return noUsageError{fmt.Errorf("not all generators ran successfully")} + } + return nil + }, + SilenceUsage: true, // silence the usage, then print it out ourselves if it wasn't suppressed + } + cmd.Flags().CountVarP(&whichLevel, "which-markers", "w", "print out all markers available with the requested generators\n(up to -www for the most detailed output, or -wwww for json output)") + cmd.Flags().CountVarP(&helpLevel, "detailed-help", "h", "print out more detailed help\n(up to -hhh for the most detailed output, or -hhhh for json output)") + cmd.Flags().BoolVar(&showVersion, "version", false, "show version") + cmd.Flags().StringSliceVar(&buildTags, "load-build-tags", []string{"ignore_autogenerated"}, "build tags to use when loading Go packages") + cmd.Flags().Bool("help", false, "print out usage and a summary of options") + oldUsage := cmd.UsageFunc() + cmd.SetUsageFunc(func(c *cobra.Command) error { + if err := oldUsage(c); err != nil { + return err + } + if helpLevel == 0 { + helpLevel = summaryHelp + } + fmt.Fprintf(c.OutOrStderr(), "\n\nOptions\n\n") + return helpForLevels(c.OutOrStdout(), c.OutOrStderr(), helpLevel, optionsRegistry, help.SortByOption) + }) + + if err := cmd.Execute(); err != nil { + var errNoUsage noUsageError + if !errors.As(err, &errNoUsage) { + // print the usage unless we suppressed it + if err := cmd.Usage(); err != nil { + panic(err) + } + } + fmt.Fprintf(cmd.OutOrStderr(), "run `%[1]s %[2]s -w` to see all available markers, or `%[1]s %[2]s -h` for usage\n", cmd.CalledAs(), strings.Join(os.Args[1:], " ")) + os.Exit(1) + } +} + +// printMarkerDocs prints out marker help for the given generators specified in +// the rawOptions, at the given level. +func printMarkerDocs(c *cobra.Command, rawOptions []string, whichLevel int) error { + // just grab a registry so we don't lag while trying to load roots + // (like we'd do if we just constructed the full runtime). + reg, err := genall.RegistryFromOptions(optionsRegistry, rawOptions) + if err != nil { + return err + } + + return helpForLevels(c.OutOrStdout(), c.OutOrStderr(), whichLevel, reg, help.SortByCategory) +} + +func helpForLevels(mainOut io.Writer, errOut io.Writer, whichLevel int, reg *markers.Registry, sorter help.SortGroup) error { + helpInfo := help.ByCategory(reg, sorter) + switch whichLevel { + case jsonHelp: + if err := json.NewEncoder(mainOut).Encode(helpInfo); err != nil { + return err + } + case detailedHelp, fullHelp: + fullDetail := whichLevel == fullHelp + for _, cat := range helpInfo { + if cat.Category == "" { + continue + } + contents := prettyhelp.MarkersDetails(fullDetail, cat.Category, cat.Markers) + if err := contents.WriteTo(errOut); err != nil { + return err + } + } + case summaryHelp: + for _, cat := range helpInfo { + if cat.Category == "" { + continue + } + contents := prettyhelp.MarkersSummary(cat.Category, cat.Markers) + if err := contents.WriteTo(errOut); err != nil { + return err + } + } + } + return nil +} + +const ( + _ = iota + summaryHelp + detailedHelp + fullHelp + jsonHelp +) diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/doc.go new file mode 100644 index 000000000..de9f9206a --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package applyconfigurations generates types for constructing declarative apply configurations. +package applyconfiguration diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/gen.go new file mode 100644 index 000000000..73c727ab4 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/gen.go @@ -0,0 +1,236 @@ +/* +Copyright 2021 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package applyconfiguration + +import ( + "fmt" + "go/ast" + "os" + "path/filepath" + + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/code-generator/cmd/applyconfiguration-gen/args" + "k8s.io/code-generator/cmd/applyconfiguration-gen/generators" + + "k8s.io/gengo/v2" + "k8s.io/gengo/v2/generator" + "k8s.io/gengo/v2/parser" + + kerrors "k8s.io/apimachinery/pkg/util/errors" + crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// Based on deepcopy gen but with legacy marker support removed. + +var ( + isCRDMarker = markers.Must(markers.MakeDefinition("kubebuilder:resource", markers.DescribesType, crdmarkers.Resource{})) + enablePkgMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:generate", markers.DescribesPackage, false)) + outputPkgMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:output:package", markers.DescribesPackage, "")) + enableTypeMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:generate", markers.DescribesType, false)) +) + +const defaultOutputPackage = "applyconfiguration" + +// +controllertools:marker:generateHelp + +// Generator generates code containing apply configuration type implementations. +type Generator struct { + // HeaderFile specifies the header text (e.g. license) to prepend to generated files. + HeaderFile string `marker:",optional"` +} + +func (Generator) CheckFilter() loader.NodeFilter { + return func(node ast.Node) bool { + // ignore interfaces + _, isIface := node.(*ast.InterfaceType) + return !isIface + } +} + +func (Generator) RegisterMarkers(into *markers.Registry) error { + if err := markers.RegisterAll(into, + isCRDMarker, enablePkgMarker, enableTypeMarker, outputPkgMarker); err != nil { + return err + } + + into.AddHelp(isCRDMarker, + markers.SimpleHelp("apply", "enables apply configuration generation for this type")) + into.AddHelp( + enableTypeMarker, markers.SimpleHelp("apply", "overrides enabling or disabling applyconfiguration generation for the type, can be used to generate applyconfiguration for a single type when the package generation is disabled, or to disable generation for a single type when the package generation is enabled")) + into.AddHelp( + enablePkgMarker, markers.SimpleHelp("apply", "overrides enabling or disabling applyconfiguration generation for the package")) + into.AddHelp( + outputPkgMarker, markers.SimpleHelp("apply", "overrides the default output package for the applyconfiguration generation, supports relative paths to the API directory. The default value is \"applyconfiguration\"")) + return nil +} + +func enabledOnPackage(col *markers.Collector, pkg *loader.Package) (bool, error) { + pkgMarkers, err := markers.PackageMarkers(col, pkg) + if err != nil { + return false, err + } + pkgMarker := pkgMarkers.Get(enablePkgMarker.Name) + if pkgMarker != nil { + return pkgMarker.(bool), nil + } + return false, nil +} + +func enabledOnType(info *markers.TypeInfo) bool { + if typeMarker := info.Markers.Get(enableTypeMarker.Name); typeMarker != nil { + return typeMarker.(bool) + } + return isCRD(info) +} + +func outputPkg(col *markers.Collector, pkg *loader.Package) string { + pkgMarkers, err := markers.PackageMarkers(col, pkg) + if err != nil { + // Use the default when there's an error. + return defaultOutputPackage + } + + pkgMarker := pkgMarkers.Get(outputPkgMarker.Name) + if pkgMarker != nil { + return pkgMarker.(string) + } + + return defaultOutputPackage +} + +func isCRD(info *markers.TypeInfo) bool { + objectEnabled := info.Markers.Get(isCRDMarker.Name) + return objectEnabled != nil +} + +func (d Generator) Generate(ctx *genall.GenerationContext) error { + headerFilePath := d.HeaderFile + + if headerFilePath == "" { + tmpFile, err := os.CreateTemp("", "applyconfig-header-*.txt") + if err != nil { + return fmt.Errorf("failed to create temporary file: %w", err) + } + if err := tmpFile.Close(); err != nil { + return fmt.Errorf("failed to close temporary file: %w", err) + } + + defer os.Remove(tmpFile.Name()) + + headerFilePath = tmpFile.Name() + } + + objGenCtx := ObjectGenCtx{ + Collector: ctx.Collector, + Checker: ctx.Checker, + HeaderFilePath: headerFilePath, + } + + errs := []error{} + for _, pkg := range ctx.Roots { + if err := objGenCtx.generateForPackage(pkg); err != nil { + errs = append(errs, err) + } + } + + if len(errs) > 0 { + return kerrors.NewAggregate(errs) + } + + return nil +} + +// ObjectGenCtx contains the common info for generating apply configuration implementations. +// It mostly exists so that generating for a package can be easily tested without +// requiring a full set of output rules, etc. +type ObjectGenCtx struct { + Collector *markers.Collector + Checker *loader.TypeChecker + HeaderFilePath string +} + +// generateForPackage generates apply configuration implementations for +// types in the given package, writing the formatted result to given writer. +func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) error { + enabled, _ := enabledOnPackage(ctx.Collector, root) + if !enabled { + return nil + } + if len(root.GoFiles) == 0 { + return nil + } + + arguments := args.New() + arguments.GoHeaderFile = ctx.HeaderFilePath + + outpkg := outputPkg(ctx.Collector, root) + + arguments.OutputDir = filepath.Join(root.Dir, outpkg) + arguments.OutputPkg = filepath.Join(root.Package.PkgPath, outpkg) + + // The following code is based on gengo/v2.Execute. + // We have lifted it from there so that we can adjust the markers on the types to make sure + // that Kubebuilder generation markers are converted into the genclient marker + // prior to executing the targets. + buildTags := []string{gengo.StdBuildTag} + p := parser.NewWithOptions(parser.Options{BuildTags: buildTags}) + if err := p.LoadPackages(root.PkgPath); err != nil { + return fmt.Errorf("failed making a parser: %w", err) + } + + c, err := generator.NewContext(p, generators.NameSystems(), generators.DefaultNameSystem()) + if err != nil { + return fmt.Errorf("failed making a context: %w", err) + } + + pkg, ok := c.Universe[root.PkgPath] + if !ok { + return fmt.Errorf("package %q not found in universe", root.Name) + } + + // For each type we think should be generated, make sure it has a genclient + // marker else the apply generator will not generate it. + if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) { + if !enabledOnType(info) { + return + } + + typ, ok := pkg.Types[info.Name] + if !ok { + return + } + + comments := sets.NewString(typ.CommentLines...) + comments.Insert(typ.SecondClosestCommentLines...) + + if !comments.Has("// +genclient") { + typ.CommentLines = append(typ.CommentLines, "+genclient") + } + }); err != nil { + return err + } + + targets := generators.GetTargets(c, arguments) + if err := c.ExecuteTargets(targets); err != nil { + return fmt.Errorf("failed executing generator: %w", err) + } + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/zz_generated.markerhelp.go new file mode 100644 index 000000000..6e0a0af27 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/applyconfiguration/zz_generated.markerhelp.go @@ -0,0 +1,41 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package applyconfiguration + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "generates code containing apply configuration type implementations.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "HeaderFile": { + Summary: "specifies the header text (e.g. license) to prepend to generated files.", + Details: "", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/conv.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/conv.go new file mode 100644 index 000000000..374e02c37 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/conv.go @@ -0,0 +1,43 @@ +package crd + +import ( + "fmt" + + apiextinternal "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var ( + conversionScheme = runtime.NewScheme() +) + +func init() { + if err := apiextinternal.AddToScheme(conversionScheme); err != nil { + panic("must be able to add internal apiextensions to the CRD conversion Scheme") + } + if err := apiext.AddToScheme(conversionScheme); err != nil { + panic("must be able to add apiextensions/v1 to the CRD conversion Scheme") + } +} + +// AsVersion converts a CRD from the canonical internal form (currently v1) to some external form. +func AsVersion(original apiext.CustomResourceDefinition, gv schema.GroupVersion) (runtime.Object, error) { + // TODO: Do we need to keep maintaining this conversion function + // post 1.22 when only CRDv1 is served by the apiserver? + if gv == apiextv1beta1.SchemeGroupVersion { + return nil, fmt.Errorf("apiVersion %q is not supported", gv.String()) + } + // We can use the internal versions an existing conversions from kubernetes, since they're not in k/k itself. + // This punts the problem of conversion down the road for a future maintainer (or future instance of @directxman12) + // when we have to support older versions that get removed, or when API machinery decides to yell at us for this + // questionable decision. + intVer, err := conversionScheme.ConvertToVersion(&original, apiextinternal.SchemeGroupVersion) + if err != nil { + return nil, fmt.Errorf("unable to convert to internal CRD version: %w", err) + } + + return conversionScheme.ConvertToVersion(intVer, gv) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/desc_visitor.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/desc_visitor.go new file mode 100644 index 000000000..1a5698bec --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/desc_visitor.go @@ -0,0 +1,90 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + "strings" + "unicode" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" +) + +// TruncateDescription truncates the description of fields in given schema if it +// exceeds maxLen. +// It tries to chop off the description at the closest sentence boundary. +func TruncateDescription(schema *apiext.JSONSchemaProps, maxLen int) { + EditSchema(schema, descVisitor{maxLen: maxLen}) +} + +// descVisitor recursively visits all fields in the schema and truncates the +// description of the fields to specified maxLen. +type descVisitor struct { + // maxLen is the maximum allowed length for description of a field + maxLen int +} + +func (v descVisitor) Visit(schema *apiext.JSONSchemaProps) SchemaVisitor { + if schema == nil { + return v + } + if v.maxLen < 0 { + return nil /* no further work to be done for this schema */ + } + if v.maxLen == 0 { + schema.Description = "" + return v + } + if len(schema.Description) > v.maxLen { + schema.Description = truncateString(schema.Description, v.maxLen) + return v + } + return v +} + +// truncateString truncates given desc string if it exceeds maxLen. It may +// return string with length less than maxLen even in cases where original desc +// exceeds maxLen because it tries to chop off the desc at the closest sentence +// boundary to avoid incomplete sentences. +func truncateString(desc string, maxLen int) string { + if len(desc) <= maxLen { + return desc + } + + desc = desc[0:maxLen] + + // Trying to chop off at closest sentence boundary. + if n := strings.LastIndexFunc(desc, isSentenceTerminal); n > 0 { + return desc[0 : n+1] + } + + // Trying to chop off at closest word boundary (i.e. whitespace). + if n := strings.LastIndexFunc(desc, isWhiteSpace); n > 0 { + return desc[0:n] + "..." + } + + return desc[0:maxLen] + "..." +} + +// helper function to determine if given rune is a sentence terminal or not. +func isSentenceTerminal(r rune) bool { + return unicode.Is(unicode.STerm, r) +} + +// helper function to determine if given rune is whitespace or not. +func isWhiteSpace(r rune) bool { + return unicode.Is(unicode.White_Space, r) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/doc.go new file mode 100644 index 000000000..914af94d9 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/doc.go @@ -0,0 +1,63 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package crd contains utilities for generating CustomResourceDefinitions and +// their corresponding OpenAPI validation schemata. +// +// # Markers +// +// Markers live under the markers subpackage. Two types of markers exist: +// those that modify schema generation (for validation), and those that modify +// the rest of the CRD. See the subpackage for more information and all +// supported markers. +// +// # Collecting Types and Generating CRDs +// +// The Parser is the entrypoint for collecting the information required to +// generate CRDs. Like loader and collector, its methods are idemptotent, not +// doing extra work if called multiple times. +// +// Parser's method start with Need. Calling NeedXYZ indicates that XYZ should +// be made present in the eqivalent field in the Parser, where it can then be +// loaded from. Each Need method will in turn call Need on anything it needs. +// +// In general, root packages should first be loaded into the Parser with +// NeedPackage. Then, CRDs can be generated with NeedCRDFor. +// +// Errors are generally attached directly to the relevant Package with +// AddError. +// +// # Known Packages +// +// There are a few types from Kubernetes that have special meaning, but don't +// have validation markers attached. Those specific types have overrides +// listed in KnownPackages that can be added as overrides to any parser. +// +// # Flattening +// +// Once schemata are generated, they can be used directly by external tooling +// (like JSONSchema validators), but must first be "flattened" to not contain +// references before use in a CRD (Kubernetes doesn't allow references in the +// CRD's validation schema). +// +// The Flattener built in to the Parser takes care of flattening out references +// when requesting the CRDs, but can be invoked manually. It will not modify +// the input schemata. +// +// Flattened schemata may further be passed to FlattenEmbedded to remove the +// use of AllOf (which is used to describe embedded struct fields when +// references are in use). This done automatically when fetching CRDs. +package crd diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/flatten.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/flatten.go new file mode 100644 index 000000000..cf02c9b71 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/flatten.go @@ -0,0 +1,446 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + "fmt" + "reflect" + "sort" + "strings" + "sync" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// ErrorRecorder knows how to record errors. It wraps the part of +// pkg/loader.Package that we need to record errors in places were it might not +// make sense to have a loader.Package +type ErrorRecorder interface { + // AddError records that the given error occurred. + // See the documentation on loader.Package.AddError for more information. + AddError(error) +} + +// isOrNil checks if val is nil if val is of a nillable type, otherwise, +// it compares val to valInt (which should probably be the zero value). +func isOrNil(val reflect.Value, valInt interface{}, zeroInt interface{}) bool { + switch valKind := val.Kind(); valKind { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return val.IsNil() + default: + return valInt == zeroInt + } +} + +// flattenAllOfInto copies properties from src to dst, then copies the properties +// of each item in src's allOf to dst's properties as well. +func flattenAllOfInto(dst *apiext.JSONSchemaProps, src apiext.JSONSchemaProps, errRec ErrorRecorder) { + if len(src.AllOf) > 0 { + for _, embedded := range src.AllOf { + flattenAllOfInto(dst, embedded, errRec) + } + } + + dstVal := reflect.Indirect(reflect.ValueOf(dst)) + srcVal := reflect.ValueOf(src) + typ := dstVal.Type() + + srcRemainder := apiext.JSONSchemaProps{} + srcRemVal := reflect.Indirect(reflect.ValueOf(&srcRemainder)) + dstRemainder := apiext.JSONSchemaProps{} + dstRemVal := reflect.Indirect(reflect.ValueOf(&dstRemainder)) + hoisted := false + + for i := 0; i < srcVal.NumField(); i++ { + fieldName := typ.Field(i).Name + switch fieldName { + case "AllOf": + // don't merge because we deal with it above + continue + case "Title", "Description", "Example", "ExternalDocs": + // don't merge because we pre-merge to properly preserve field docs + continue + } + srcField := srcVal.Field(i) + fldTyp := srcField.Type() + zeroVal := reflect.Zero(fldTyp) + zeroInt := zeroVal.Interface() + srcInt := srcField.Interface() + + if isOrNil(srcField, srcInt, zeroInt) { + // nothing to copy from src, continue + continue + } + + dstField := dstVal.Field(i) + dstInt := dstField.Interface() + if isOrNil(dstField, dstInt, zeroInt) { + // dst is empty, continue + dstField.Set(srcField) + continue + } + + if fldTyp.Comparable() && srcInt == dstInt { + // same value, continue + continue + } + + // resolve conflict + switch fieldName { + case "Properties": + // merge if possible, use all of otherwise + srcMap := srcInt.(map[string]apiext.JSONSchemaProps) + dstMap := dstInt.(map[string]apiext.JSONSchemaProps) + + for k, v := range srcMap { + dstProp, exists := dstMap[k] + if !exists { + dstMap[k] = v + continue + } + flattenAllOfInto(&dstProp, v, errRec) + dstMap[k] = dstProp + } + case "Required": + // merge + dstField.Set(reflect.AppendSlice(dstField, srcField)) + case "Type": + if srcInt != dstInt { + // TODO(directxman12): figure out how to attach this back to a useful point in the Go source or in the schema + errRec.AddError(fmt.Errorf("conflicting types in allOf branches in schema: %s vs %s", dstInt, srcInt)) + } + // keep the destination value, for now + // TODO(directxman12): Default -- use field? + // TODO(directxman12): + // - Dependencies: if field x is present, then either schema validates or all props are present + // - AdditionalItems: like AdditionalProperties + // - Definitions: common named validation sets that can be references (merge, bail if duplicate) + case "AdditionalProperties": + // as of the time of writing, `allows: false` is not allowed, so we don't have to handle it + srcProps := srcInt.(*apiext.JSONSchemaPropsOrBool) + if srcProps.Schema == nil { + // nothing to merge + continue + } + dstProps := dstInt.(*apiext.JSONSchemaPropsOrBool) + if dstProps.Schema == nil { + dstProps.Schema = &apiext.JSONSchemaProps{} + } + flattenAllOfInto(dstProps.Schema, *srcProps.Schema, errRec) + case "XPreserveUnknownFields": + dstField.Set(srcField) + case "XMapType": + dstField.Set(srcField) + case "XValidations": + dstField.Set(reflect.AppendSlice(srcField, dstField)) + // NB(directxman12): no need to explicitly handle nullable -- false is considered to be the zero value + // TODO(directxman12): src isn't necessarily the field value -- it's just the most recent allOf entry + default: + // hoist into allOf... + hoisted = true + + srcRemVal.Field(i).Set(srcField) + dstRemVal.Field(i).Set(dstField) + // ...and clear the original + dstField.Set(zeroVal) + } + } + + if hoisted { + dst.AllOf = append(dst.AllOf, dstRemainder, srcRemainder) + } + + // dedup required + if len(dst.Required) > 0 { + reqUniq := make(map[string]struct{}) + for _, req := range dst.Required { + reqUniq[req] = struct{}{} + } + dst.Required = make([]string, 0, len(reqUniq)) + for req := range reqUniq { + dst.Required = append(dst.Required, req) + } + // be deterministic + sort.Strings(dst.Required) + } +} + +// allOfVisitor recursively visits allOf fields in the schema, +// merging nested allOf properties into the root schema. +type allOfVisitor struct { + // errRec is used to record errors while flattening (like two conflicting + // field values used in an allOf) + errRec ErrorRecorder +} + +func (v *allOfVisitor) Visit(schema *apiext.JSONSchemaProps) SchemaVisitor { + if schema == nil { + return v + } + + // clear this now so that we can safely preserve edits made my flattenAllOfInto + origAllOf := schema.AllOf + schema.AllOf = nil + + for _, embedded := range origAllOf { + flattenAllOfInto(schema, embedded, v.errRec) + } + return v +} + +// NB(directxman12): FlattenEmbedded is separate from Flattener because +// some tooling wants to flatten out embedded fields, but only actually +// flatten a few specific types first. + +// FlattenEmbedded flattens embedded fields (represented via AllOf) which have +// already had their references resolved into simple properties in the containing +// schema. +func FlattenEmbedded(schema *apiext.JSONSchemaProps, errRec ErrorRecorder) *apiext.JSONSchemaProps { + outSchema := schema.DeepCopy() + EditSchema(outSchema, &allOfVisitor{errRec: errRec}) + return outSchema +} + +// Flattener knows how to take a root type, and flatten all references in it +// into a single, flat type. Flattened types are cached, so it's relatively +// cheap to make repeated calls with the same type. +type Flattener struct { + // Parser is used to lookup package and type details, and parse in new packages. + Parser *Parser + + LookupReference func(ref string, contextPkg *loader.Package) (TypeIdent, error) + + // flattenedTypes hold the flattened version of each seen type for later reuse. + flattenedTypes map[TypeIdent]apiext.JSONSchemaProps + initOnce sync.Once +} + +func (f *Flattener) init() { + f.initOnce.Do(func() { + f.flattenedTypes = make(map[TypeIdent]apiext.JSONSchemaProps) + if f.LookupReference == nil { + f.LookupReference = identFromRef + } + }) +} + +// cacheType saves the flattened version of the given type for later reuse +func (f *Flattener) cacheType(typ TypeIdent, schema apiext.JSONSchemaProps) { + f.init() + f.flattenedTypes[typ] = schema +} + +// loadUnflattenedSchema fetches a fresh, unflattened schema from the parser. +func (f *Flattener) loadUnflattenedSchema(typ TypeIdent) (*apiext.JSONSchemaProps, error) { + f.Parser.NeedSchemaFor(typ) + + baseSchema, found := f.Parser.Schemata[typ] + if !found { + return nil, fmt.Errorf("unable to locate schema for type %s", typ) + } + return &baseSchema, nil +} + +// FlattenType flattens the given pre-loaded type, removing any references from it. +// It deep-copies the schema first, so it won't affect the parser's version of the schema. +func (f *Flattener) FlattenType(typ TypeIdent) *apiext.JSONSchemaProps { + f.init() + if cachedSchema, isCached := f.flattenedTypes[typ]; isCached { + return &cachedSchema + } + baseSchema, err := f.loadUnflattenedSchema(typ) + if err != nil { + typ.Package.AddError(err) + return nil + } + resSchema := f.FlattenSchema(*baseSchema, typ.Package) + f.cacheType(typ, *resSchema) + return resSchema +} + +// FlattenSchema flattens the given schema, removing any references. +// It deep-copies the schema first, so the input schema won't be affected. +func (f *Flattener) FlattenSchema(baseSchema apiext.JSONSchemaProps, currentPackage *loader.Package) *apiext.JSONSchemaProps { + resSchema := baseSchema.DeepCopy() + EditSchema(resSchema, &flattenVisitor{ + Flattener: f, + currentPackage: currentPackage, + }) + + return resSchema +} + +// RefParts splits a reference produced by the schema generator into its component +// type name and package name (if it's a cross-package reference). Note that +// referenced packages *must* be looked up relative to the current package. +func RefParts(ref string) (typ string, pkgName string, err error) { + if !strings.HasPrefix(ref, defPrefix) { + return "", "", fmt.Errorf("non-standard reference link %q", ref) + } + ref = ref[len(defPrefix):] + // decode the json pointer encodings + ref = strings.ReplaceAll(ref, "~1", "/") + ref = strings.ReplaceAll(ref, "~0", "~") + nameParts := strings.SplitN(ref, "~", 2) + + if len(nameParts) == 1 { + // local reference + return nameParts[0], "", nil + } + // cross-package reference + return nameParts[1], nameParts[0], nil +} + +// identFromRef converts the given schema ref from the given package back +// into the TypeIdent that it represents. +func identFromRef(ref string, contextPkg *loader.Package) (TypeIdent, error) { + typ, pkgName, err := RefParts(ref) + if err != nil { + return TypeIdent{}, err + } + + if pkgName == "" { + // a local reference + return TypeIdent{ + Name: typ, + Package: contextPkg, + }, nil + } + + // an external reference + return TypeIdent{ + Name: typ, + Package: contextPkg.Imports()[pkgName], + }, nil +} + +// preserveFields copies documentation fields from src into dst, preserving +// field-level documentation when flattening, and preserving field-level validation +// as allOf entries. +func preserveFields(dst *apiext.JSONSchemaProps, src apiext.JSONSchemaProps) { + srcDesc := src.Description + srcTitle := src.Title + srcExDoc := src.ExternalDocs + srcEx := src.Example + + src.Description, src.Title, src.ExternalDocs, src.Example = "", "", nil, nil + + src.Ref = nil + *dst = apiext.JSONSchemaProps{ + AllOf: []apiext.JSONSchemaProps{*dst, src}, + + // keep these, in case the source field doesn't specify anything useful + Description: dst.Description, + Title: dst.Title, + ExternalDocs: dst.ExternalDocs, + Example: dst.Example, + } + + if srcDesc != "" { + dst.Description = srcDesc + } + if srcTitle != "" { + dst.Title = srcTitle + } + if srcExDoc != nil { + dst.ExternalDocs = srcExDoc + } + if srcEx != nil { + dst.Example = srcEx + } +} + +// flattenVisitor visits each node in the schema, recursively flattening references. +type flattenVisitor struct { + *Flattener + + currentPackage *loader.Package + currentType *TypeIdent + currentSchema *apiext.JSONSchemaProps + originalField apiext.JSONSchemaProps +} + +func (f *flattenVisitor) Visit(baseSchema *apiext.JSONSchemaProps) SchemaVisitor { + if baseSchema == nil { + // end-of-node marker, cache the results + if f.currentType != nil { + f.cacheType(*f.currentType, *f.currentSchema) + // preserve field information *after* caching so that we don't + // accidentally cache field-level information onto the schema for + // the type in general. + preserveFields(f.currentSchema, f.originalField) + } + return f + } + + // if we get a type that's just a ref, resolve it + if baseSchema.Ref != nil && len(*baseSchema.Ref) > 0 { + // resolve this ref + refIdent, err := f.LookupReference(*baseSchema.Ref, f.currentPackage) + if err != nil { + f.currentPackage.AddError(err) + return nil + } + + // load and potentially flatten the schema + + // check the cache first... + if refSchemaCached, isCached := f.flattenedTypes[refIdent]; isCached { + // shallow copy is fine, it's just to avoid overwriting the doc fields + preserveFields(&refSchemaCached, *baseSchema) + *baseSchema = refSchemaCached + return nil // don't recurse, we're done + } + + // ...otherwise, we need to flatten + refSchema, err := f.loadUnflattenedSchema(refIdent) + if err != nil { + f.currentPackage.AddError(err) + return nil + } + refSchema = refSchema.DeepCopy() + + // keep field around to preserve field-level validation, docs, etc + origField := *baseSchema + *baseSchema = *refSchema + + // avoid loops (which shouldn't exist, but just in case) + // by marking a nil cached pointer before we start recursing + f.cacheType(refIdent, apiext.JSONSchemaProps{}) + + return &flattenVisitor{ + Flattener: f.Flattener, + + currentPackage: refIdent.Package, + currentType: &refIdent, + currentSchema: baseSchema, + originalField: origField, + } + } + + // otherwise, continue recursing... + if f.currentType != nil { + // ...but don't accidentally end this node early (for caching purposes) + return &flattenVisitor{ + Flattener: f.Flattener, + currentPackage: f.currentPackage, + } + } + + return f +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go new file mode 100644 index 000000000..5fad65a71 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go @@ -0,0 +1,355 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + "fmt" + "go/ast" + "go/types" + "sort" + "strings" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" + "sigs.k8s.io/controller-tools/pkg/version" +) + +// The identifier for v1 CustomResourceDefinitions. +const v1 = "v1" + +// The default CustomResourceDefinition version to generate. +const defaultVersion = v1 + +// +controllertools:marker:generateHelp + +// Generator generates CustomResourceDefinition objects. +type Generator struct { + // IgnoreUnexportedFields indicates that we should skip unexported fields. + // + // Left unspecified, the default is false. + IgnoreUnexportedFields *bool `marker:",optional"` + + // AllowDangerousTypes allows types which are usually omitted from CRD generation + // because they are not recommended. + // + // Currently the following additional types are allowed when this is true: + // float32 + // float64 + // + // Left unspecified, the default is false + AllowDangerousTypes *bool `marker:",optional"` + + // MaxDescLen specifies the maximum description length for fields in CRD's OpenAPI schema. + // + // 0 indicates drop the description for all fields completely. + // n indicates limit the description to at most n characters and truncate the description to + // closest sentence boundary if it exceeds n characters. + MaxDescLen *int `marker:",optional"` + + // CRDVersions specifies the target API versions of the CRD type itself to + // generate. Defaults to v1. + // + // Currently, the only supported value is v1. + // + // The first version listed will be assumed to be the "default" version and + // will not get a version suffix in the output filename. + // + // You'll need to use "v1" to get support for features like defaulting, + // along with an API server that supports it (Kubernetes 1.16+). + CRDVersions []string `marker:"crdVersions,optional"` + + // GenerateEmbeddedObjectMeta specifies if any embedded ObjectMeta in the CRD should be generated + GenerateEmbeddedObjectMeta *bool `marker:",optional"` + + // HeaderFile specifies the header text (e.g. license) to prepend to generated files. + HeaderFile string `marker:",optional"` + + // Year specifies the year to substitute for " YEAR" in the header file. + Year string `marker:",optional"` + + // DeprecatedV1beta1CompatibilityPreserveUnknownFields indicates whether + // or not we should turn off field pruning for this resource. + // + // Specifies spec.preserveUnknownFields value that is false and omitted by default. + // This value can only be specified for CustomResourceDefinitions that were created with + // `apiextensions.k8s.io/v1beta1`. + // + // The field can be set for compatibility reasons, although strongly discouraged, resource + // authors should move to a structural OpenAPI schema instead. + // + // See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning + // for more information about field pruning and v1beta1 resources compatibility. + DeprecatedV1beta1CompatibilityPreserveUnknownFields *bool `marker:",optional"` +} + +func (Generator) CheckFilter() loader.NodeFilter { + return filterTypesForCRDs +} +func (Generator) RegisterMarkers(into *markers.Registry) error { + return crdmarkers.Register(into) +} + +// transformRemoveCRDStatus ensures we do not write the CRD status field. +func transformRemoveCRDStatus(obj map[string]interface{}) error { + delete(obj, "status") + return nil +} + +// transformPreserveUnknownFields adds spec.preserveUnknownFields=value. +func transformPreserveUnknownFields(value bool) func(map[string]interface{}) error { + return func(obj map[string]interface{}) error { + if spec, ok := obj["spec"].(map[interface{}]interface{}); ok { + spec["preserveUnknownFields"] = value + } + return nil + } +} + +func (g Generator) Generate(ctx *genall.GenerationContext) error { + parser := &Parser{ + Collector: ctx.Collector, + Checker: ctx.Checker, + // Perform defaulting here to avoid ambiguity later + IgnoreUnexportedFields: g.IgnoreUnexportedFields != nil && *g.IgnoreUnexportedFields, + AllowDangerousTypes: g.AllowDangerousTypes != nil && *g.AllowDangerousTypes, + // Indicates the parser on whether to register the ObjectMeta type or not + GenerateEmbeddedObjectMeta: g.GenerateEmbeddedObjectMeta != nil && *g.GenerateEmbeddedObjectMeta, + } + + AddKnownTypes(parser) + for _, root := range ctx.Roots { + parser.NeedPackage(root) + } + + metav1Pkg := FindMetav1(ctx.Roots) + if metav1Pkg == nil { + // no objects in the roots, since nothing imported metav1 + return nil + } + + // TODO: allow selecting a specific object + kubeKinds := FindKubeKinds(parser, metav1Pkg) + if len(kubeKinds) == 0 { + // no objects in the roots + return nil + } + + crdVersions := g.CRDVersions + + if len(crdVersions) == 0 { + crdVersions = []string{defaultVersion} + } + + var headerText string + + if g.HeaderFile != "" { + headerBytes, err := ctx.ReadFile(g.HeaderFile) + if err != nil { + return err + } + headerText = string(headerBytes) + } + headerText = strings.ReplaceAll(headerText, " YEAR", " "+g.Year) + + yamlOpts := []*genall.WriteYAMLOptions{ + genall.WithTransform(transformRemoveCRDStatus), + genall.WithTransform(genall.TransformRemoveCreationTimestamp), + } + if g.DeprecatedV1beta1CompatibilityPreserveUnknownFields != nil { + yamlOpts = append(yamlOpts, genall.WithTransform(transformPreserveUnknownFields(*g.DeprecatedV1beta1CompatibilityPreserveUnknownFields))) + } + + for _, groupKind := range kubeKinds { + parser.NeedCRDFor(groupKind, g.MaxDescLen) + crdRaw := parser.CustomResourceDefinitions[groupKind] + addAttribution(&crdRaw) + + // Prevent the top level metadata for the CRD to be generate regardless of the intention in the arguments + FixTopLevelMetadata(crdRaw) + + versionedCRDs := make([]interface{}, len(crdVersions)) + for i, ver := range crdVersions { + conv, err := AsVersion(crdRaw, schema.GroupVersion{Group: apiext.SchemeGroupVersion.Group, Version: ver}) + if err != nil { + return err + } + versionedCRDs[i] = conv + } + + for i, crd := range versionedCRDs { + removeDescriptionFromMetadata(crd.(*apiext.CustomResourceDefinition)) + var fileName string + if i == 0 { + fileName = fmt.Sprintf("%s_%s.yaml", crdRaw.Spec.Group, crdRaw.Spec.Names.Plural) + } else { + fileName = fmt.Sprintf("%s_%s.%s.yaml", crdRaw.Spec.Group, crdRaw.Spec.Names.Plural, crdVersions[i]) + } + if err := ctx.WriteYAML(fileName, headerText, []interface{}{crd}, yamlOpts...); err != nil { + return err + } + } + } + + return nil +} + +func removeDescriptionFromMetadata(crd *apiext.CustomResourceDefinition) { + for _, versionSpec := range crd.Spec.Versions { + if versionSpec.Schema != nil { + removeDescriptionFromMetadataProps(versionSpec.Schema.OpenAPIV3Schema) + } + } +} + +func removeDescriptionFromMetadataProps(v *apiext.JSONSchemaProps) { + if m, ok := v.Properties["metadata"]; ok { + meta := &m + if meta.Description != "" { + meta.Description = "" + v.Properties["metadata"] = m + } + } +} + +// FixTopLevelMetadata resets the schema for the top-level metadata field which is needed for CRD validation +func FixTopLevelMetadata(crd apiext.CustomResourceDefinition) { + for _, v := range crd.Spec.Versions { + if v.Schema != nil && v.Schema.OpenAPIV3Schema != nil && v.Schema.OpenAPIV3Schema.Properties != nil { + schemaProperties := v.Schema.OpenAPIV3Schema.Properties + if _, ok := schemaProperties["metadata"]; ok { + schemaProperties["metadata"] = apiext.JSONSchemaProps{Type: "object"} + } + } + } +} + +// addAttribution adds attribution info to indicate controller-gen tool was used +// to generate this CRD definition along with the version info. +func addAttribution(crd *apiext.CustomResourceDefinition) { + if crd.ObjectMeta.Annotations == nil { + crd.ObjectMeta.Annotations = map[string]string{} + } + crd.ObjectMeta.Annotations["controller-gen.kubebuilder.io/version"] = version.Version() +} + +// FindMetav1 locates the actual package representing metav1 amongst +// the imports of the roots. +func FindMetav1(roots []*loader.Package) *loader.Package { + for _, root := range roots { + pkg := root.Imports()["k8s.io/apimachinery/pkg/apis/meta/v1"] + if pkg != nil { + return pkg + } + } + return nil +} + +// FindKubeKinds locates all types that contain TypeMeta and ObjectMeta +// (and thus may be a Kubernetes object), and returns the corresponding +// group-kinds. +func FindKubeKinds(parser *Parser, metav1Pkg *loader.Package) []schema.GroupKind { + // TODO(directxman12): technically, we should be finding metav1 per-package + kubeKinds := map[schema.GroupKind]struct{}{} + for typeIdent, info := range parser.Types { + hasObjectMeta := false + hasTypeMeta := false + + pkg := typeIdent.Package + pkg.NeedTypesInfo() + typesInfo := pkg.TypesInfo + + for _, field := range info.Fields { + if field.Name != "" { + // type and object meta are embedded, + // so they can't be this + continue + } + + fieldType := typesInfo.TypeOf(field.RawField.Type) + namedField, isNamed := fieldType.(*types.Named) + if !isNamed { + // ObjectMeta and TypeMeta are named types + continue + } + if namedField.Obj().Pkg() == nil { + // Embedded non-builtin universe type (specifically, it's probably `error`), + // so it can't be ObjectMeta or TypeMeta + continue + } + fieldPkgPath := loader.NonVendorPath(namedField.Obj().Pkg().Path()) + fieldPkg := pkg.Imports()[fieldPkgPath] + + // Compare the metav1 package by ID and not by the actual instance + // of the object. The objects in memory could be different due to + // loading from different root paths, even when they both refer to + // the same metav1 package. + if fieldPkg == nil || fieldPkg.ID != metav1Pkg.ID { + continue + } + + switch namedField.Obj().Name() { + case "ObjectMeta": + hasObjectMeta = true + case "TypeMeta": + hasTypeMeta = true + } + } + + if !hasObjectMeta || !hasTypeMeta { + continue + } + + groupKind := schema.GroupKind{ + Group: parser.GroupVersions[pkg].Group, + Kind: typeIdent.Name, + } + kubeKinds[groupKind] = struct{}{} + } + + groupKindList := make([]schema.GroupKind, 0, len(kubeKinds)) + for groupKind := range kubeKinds { + groupKindList = append(groupKindList, groupKind) + } + sort.Slice(groupKindList, func(i, j int) bool { + return groupKindList[i].String() < groupKindList[j].String() + }) + + return groupKindList +} + +// filterTypesForCRDs filters out all nodes that aren't used in CRD generation, +// like interfaces and struct fields without JSON tag. +func filterTypesForCRDs(node ast.Node) bool { + switch node := node.(type) { + case *ast.InterfaceType: + // skip interfaces, we never care about references in them + return false + case *ast.StructType: + return true + case *ast.Field: + _, hasTag := loader.ParseAstTag(node.Tag).Lookup("json") + // fields without JSON tags mean we have custom serialization, + // so only visit fields with tags. + return hasTag + default: + return true + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go new file mode 100644 index 000000000..fd2a663a2 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go @@ -0,0 +1,167 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package crd + +import ( + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// KnownPackages overrides types in some comment packages that have custom validation +// but don't have validation markers on them (since they're from core Kubernetes). +var KnownPackages = map[string]PackageOverride{ + "k8s.io/apimachinery/pkg/apis/meta/v1": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "ObjectMeta", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "object", + } + p.Schemata[TypeIdent{Name: "Time", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "string", + Format: "date-time", + } + p.Schemata[TypeIdent{Name: "MicroTime", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "string", + Format: "date-time", + } + p.Schemata[TypeIdent{Name: "Duration", Package: pkg}] = apiext.JSONSchemaProps{ + // TODO(directxman12): regexp validation for this (or get kube to support it as a format value) + Type: "string", + } + p.Schemata[TypeIdent{Name: "Fields", Package: pkg}] = apiext.JSONSchemaProps{ + // this is a recursive structure that can't be flattened or, for that matter, properly generated. + // so just treat it as an arbitrary map + Type: "object", + AdditionalProperties: &apiext.JSONSchemaPropsOrBool{Allows: true}, + } + p.AddPackage(pkg) // get the rest of the types + }, + + "k8s.io/apimachinery/pkg/api/resource": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "Quantity", Package: pkg}] = apiext.JSONSchemaProps{ + // TODO(directxman12): regexp validation for this (or get kube to support it as a format value) + XIntOrString: true, + AnyOf: []apiext.JSONSchemaProps{ + {Type: "integer"}, + {Type: "string"}, + }, + Pattern: "^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$", + } + // No point in calling AddPackage, this is the sole inhabitant + }, + + "k8s.io/apimachinery/pkg/runtime": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "RawExtension", Package: pkg}] = apiext.JSONSchemaProps{ + // TODO(directxman12): regexp validation for this (or get kube to support it as a format value) + Type: "object", + XPreserveUnknownFields: ptr.To(true), + } + p.AddPackage(pkg) // get the rest of the types + }, + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "Unstructured", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "object", + } + p.AddPackage(pkg) // get the rest of the types + }, + + "k8s.io/apimachinery/pkg/util/intstr": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "IntOrString", Package: pkg}] = apiext.JSONSchemaProps{ + XIntOrString: true, + AnyOf: []apiext.JSONSchemaProps{ + {Type: "integer"}, + {Type: "string"}, + }, + } + // No point in calling AddPackage, this is the sole inhabitant + }, + + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "JSON", Package: pkg}] = apiext.JSONSchemaProps{ + XPreserveUnknownFields: ptr.To(true), + } + p.AddPackage(pkg) // get the rest of the types + }, + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1": func(p *Parser, pkg *loader.Package) { + p.Schemata[TypeIdent{Name: "JSON", Package: pkg}] = apiext.JSONSchemaProps{ + XPreserveUnknownFields: ptr.To(true), + } + p.AddPackage(pkg) // get the rest of the types + }, +} + +// ObjectMetaPackages overrides the ObjectMeta in all types +var ObjectMetaPackages = map[string]PackageOverride{ + "k8s.io/apimachinery/pkg/apis/meta/v1": func(p *Parser, pkg *loader.Package) { + // execute the KnowPackages for `k8s.io/apimachinery/pkg/apis/meta/v1` if any + if f, ok := KnownPackages["k8s.io/apimachinery/pkg/apis/meta/v1"]; ok { + f(p, pkg) + } + // This is an allow-listed set of properties of ObjectMeta, other runtime properties are not part of this list + // See more discussion: https://github.com/kubernetes-sigs/controller-tools/pull/395#issuecomment-691919433 + p.Schemata[TypeIdent{Name: "ObjectMeta", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiext.JSONSchemaProps{ + "name": { + Type: "string", + }, + "namespace": { + Type: "string", + }, + "annotations": { + Type: "object", + AdditionalProperties: &apiext.JSONSchemaPropsOrBool{ + Schema: &apiext.JSONSchemaProps{ + Type: "string", + }, + }, + }, + "labels": { + Type: "object", + AdditionalProperties: &apiext.JSONSchemaPropsOrBool{ + Schema: &apiext.JSONSchemaProps{ + Type: "string", + }, + }, + }, + "finalizers": { + Type: "array", + Items: &apiext.JSONSchemaPropsOrArray{ + Schema: &apiext.JSONSchemaProps{ + Type: "string", + }, + }, + }, + }, + } + }, +} + +// AddKnownTypes registers the packages overrides in KnownPackages with the given parser. +func AddKnownTypes(parser *Parser) { + // ensure everything is there before adding to PackageOverrides + // TODO(directxman12): this is a bit of a hack, maybe just use constructors? + parser.init() + for pkgName, override := range KnownPackages { + parser.PackageOverrides[pkgName] = override + } + // if we want to generate the embedded ObjectMeta in the CRD we need to add the ObjectMetaPackages + if parser.GenerateEmbeddedObjectMeta { + for pkgName, override := range ObjectMetaPackages { + parser.PackageOverrides[pkgName] = override + } + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/crd.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/crd.go new file mode 100644 index 000000000..bd3cef563 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/crd.go @@ -0,0 +1,421 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "fmt" + "strings" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// CRDMarkers lists all markers that directly modify the CRD (not validation +// schemas). +var CRDMarkers = []*definitionWithHelp{ + // TODO(directxman12): more detailed help + must(markers.MakeDefinition("kubebuilder:subresource:status", markers.DescribesType, SubresourceStatus{})). + WithHelp(SubresourceStatus{}.Help()), + + must(markers.MakeDefinition("kubebuilder:subresource:scale", markers.DescribesType, SubresourceScale{})). + WithHelp(SubresourceScale{}.Help()), + + must(markers.MakeDefinition("kubebuilder:printcolumn", markers.DescribesType, PrintColumn{})). + WithHelp(PrintColumn{}.Help()), + + must(markers.MakeDefinition("kubebuilder:resource", markers.DescribesType, Resource{})). + WithHelp(Resource{}.Help()), + + must(markers.MakeDefinition("kubebuilder:storageversion", markers.DescribesType, StorageVersion{})). + WithHelp(StorageVersion{}.Help()), + + must(markers.MakeDefinition("kubebuilder:skipversion", markers.DescribesType, SkipVersion{})). + WithHelp(SkipVersion{}.Help()), + + must(markers.MakeDefinition("kubebuilder:unservedversion", markers.DescribesType, UnservedVersion{})). + WithHelp(UnservedVersion{}.Help()), + + must(markers.MakeDefinition("kubebuilder:deprecatedversion", markers.DescribesType, DeprecatedVersion{})). + WithHelp(DeprecatedVersion{}.Help()), + + must(markers.MakeDefinition("kubebuilder:metadata", markers.DescribesType, Metadata{})). + WithHelp(Metadata{}.Help()), + + must(markers.MakeDefinition("kubebuilder:selectablefield", markers.DescribesType, SelectableField{})). + WithHelp(SelectableField{}.Help()), +} + +// TODO: categories and singular used to be annotations types +// TODO: doc + +func init() { + AllDefinitions = append(AllDefinitions, CRDMarkers...) +} + +// +controllertools:marker:generateHelp:category=CRD + +// SubresourceStatus enables the "/status" subresource on a CRD. +type SubresourceStatus struct{} + +func (s SubresourceStatus) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + var subresources *apiext.CustomResourceSubresources + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + if ver.Subresources == nil { + ver.Subresources = &apiext.CustomResourceSubresources{} + } + subresources = ver.Subresources + break + } + if subresources == nil { + return fmt.Errorf("status subresource applied to version %q not in CRD", version) + } + subresources.Status = &apiext.CustomResourceSubresourceStatus{} + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// SubresourceScale enables the "/scale" subresource on a CRD. +type SubresourceScale struct { + // marker names are leftover legacy cruft + + // SpecPath specifies the jsonpath to the replicas field for the scale's spec. + SpecPath string `marker:"specpath"` + + // StatusPath specifies the jsonpath to the replicas field for the scale's status. + StatusPath string `marker:"statuspath"` + + // SelectorPath specifies the jsonpath to the pod label selector field for the scale's status. + // + // The selector field must be the *string* form (serialized form) of a selector. + // Setting a pod label selector is necessary for your type to work with the HorizontalPodAutoscaler. + SelectorPath *string `marker:"selectorpath"` +} + +func (s SubresourceScale) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + var subresources *apiext.CustomResourceSubresources + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + if ver.Subresources == nil { + ver.Subresources = &apiext.CustomResourceSubresources{} + } + subresources = ver.Subresources + break + } + if subresources == nil { + return fmt.Errorf("scale subresource applied to version %q not in CRD", version) + } + subresources.Scale = &apiext.CustomResourceSubresourceScale{ + SpecReplicasPath: s.SpecPath, + StatusReplicasPath: s.StatusPath, + LabelSelectorPath: s.SelectorPath, + } + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// StorageVersion marks this version as the "storage version" for the CRD for conversion. +// +// When conversion is enabled for a CRD (i.e. it's not a trivial-versions/single-version CRD), +// one version is set as the "storage version" to be stored in etcd. Attempting to store any +// other version will result in conversion to the storage version via a conversion webhook. +type StorageVersion struct{} + +func (s StorageVersion) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + if version == "" { + // single-version, do nothing + return nil + } + // multi-version + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + ver.Storage = true + break + } + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// SkipVersion removes the particular version of the CRD from the CRDs spec. +// +// This is useful if you need to skip generating and listing version entries +// for 'internal' resource versions, which typically exist if using the +// Kubernetes upstream conversion-gen tool. +type SkipVersion struct{} + +func (s SkipVersion) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + if version == "" { + // single-version, this is an invalid state + return fmt.Errorf("cannot skip a version if there is only a single version") + } + var versions []apiext.CustomResourceDefinitionVersion + // multi-version + for i := range crd.Versions { + ver := crd.Versions[i] + if ver.Name == version { + // skip the skipped version + continue + } + versions = append(versions, ver) + } + crd.Versions = versions + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// PrintColumn adds a column to "kubectl get" output for this CRD. +type PrintColumn struct { + // Name specifies the name of the column. + Name string + + // Type indicates the type of the column. + // + // It may be any OpenAPI data type listed at + // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types. + Type string + + // JSONPath specifies the jsonpath expression used to extract the value of the column. + JSONPath string `marker:"JSONPath"` // legacy cruft + + // Description specifies the help/description for this column. + Description string `marker:",optional"` + + // Format specifies the format of the column. + // + // It may be any OpenAPI data format corresponding to the type, listed at + // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types. + Format string `marker:",optional"` + + // Priority indicates how important it is that this column be displayed. + // + // Lower priority (*higher* numbered) columns will be hidden if the terminal + // width is too small. + Priority int32 `marker:",optional"` +} + +func (s PrintColumn) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + var columns *[]apiext.CustomResourceColumnDefinition + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + if ver.Subresources == nil { + ver.Subresources = &apiext.CustomResourceSubresources{} + } + columns = &ver.AdditionalPrinterColumns + break + } + if columns == nil { + return fmt.Errorf("printer columns applied to version %q not in CRD", version) + } + + *columns = append(*columns, apiext.CustomResourceColumnDefinition{ + Name: s.Name, + Type: s.Type, + JSONPath: s.JSONPath, + Description: s.Description, + Format: s.Format, + Priority: s.Priority, + }) + + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// Resource configures naming and scope for a CRD. +type Resource struct { + // Path specifies the plural "resource" for this CRD. + // + // It generally corresponds to a plural, lower-cased version of the Kind. + // See https://book.kubebuilder.io/cronjob-tutorial/gvks.html. + Path string `marker:",optional"` + + // ShortName specifies aliases for this CRD. + // + // Short names are often used when people have work with your resource + // over and over again. For instance, "rs" for "replicaset" or + // "crd" for customresourcedefinition. + ShortName []string `marker:",optional"` + + // Categories specifies which group aliases this resource is part of. + // + // Group aliases are used to work with groups of resources at once. + // The most common one is "all" which covers about a third of the base + // resources in Kubernetes, and is generally used for "user-facing" resources. + Categories []string `marker:",optional"` + + // Singular overrides the singular form of your resource. + // + // The singular form is otherwise defaulted off the plural (path). + Singular string `marker:",optional"` + + // Scope overrides the scope of the CRD (Cluster vs Namespaced). + // + // Scope defaults to "Namespaced". Cluster-scoped ("Cluster") resources + // don't exist in namespaces. + Scope string `marker:",optional"` +} + +func (s Resource) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, _ string) error { + if s.Path != "" { + crd.Names.Plural = s.Path + } + if s.Singular != "" { + crd.Names.Singular = s.Singular + } + crd.Names.ShortNames = s.ShortName + crd.Names.Categories = s.Categories + + switch s.Scope { + case "": + crd.Scope = apiext.NamespaceScoped + default: + crd.Scope = apiext.ResourceScope(s.Scope) + } + + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// UnservedVersion does not serve this version. +// +// This is useful if you need to drop support for a version in favor of a newer version. +type UnservedVersion struct{} + +func (s UnservedVersion) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + ver.Served = false + break + } + return nil +} + +// NB(directxman12): singular was historically distinct, so we keep it here for backwards compat + +// +controllertools:marker:generateHelp:category=CRD + +// DeprecatedVersion marks this version as deprecated. +type DeprecatedVersion struct { + // Warning message to be shown on the deprecated version + Warning *string `marker:",optional"` +} + +func (s DeprecatedVersion) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + if version == "" { + // single-version, do nothing + return nil + } + // multi-version + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + ver.Deprecated = true + ver.DeprecationWarning = s.Warning + break + } + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// Metadata configures the additional annotations or labels for this CRD. +// For example adding annotation "api-approved.kubernetes.io" for a CRD with Kubernetes groups, +// or annotation "cert-manager.io/inject-ca-from-secret" for a CRD that needs CA injection. +type Metadata struct { + // Annotations will be added into the annotations of this CRD. + Annotations []string `marker:",optional"` + // Labels will be added into the labels of this CRD. + Labels []string `marker:",optional"` +} + +func (s Metadata) ApplyToCRD(crd *apiext.CustomResourceDefinition, _ string) error { + if len(s.Annotations) > 0 { + if crd.Annotations == nil { + crd.Annotations = map[string]string{} + } + for _, str := range s.Annotations { + kv := strings.SplitN(str, "=", 2) + if len(kv) < 2 { + return fmt.Errorf("annotation %s is not in 'xxx=xxx' format", str) + } + crd.Annotations[kv[0]] = kv[1] + } + } + + if len(s.Labels) > 0 { + if crd.Labels == nil { + crd.Labels = map[string]string{} + } + for _, str := range s.Labels { + kv := strings.SplitN(str, "=", 2) + crd.Labels[kv[0]] = kv[1] + } + } + + return nil +} + +// +controllertools:marker:generateHelp:category=CRD + +// SelectableField adds a field that may be used with field selectors. +type SelectableField struct { + // JSONPath specifies the jsonpath expression which is used to produce a field selector value. + JSONPath string `marker:"JSONPath"` +} + +func (s SelectableField) ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error { + var selectableFields *[]apiext.SelectableField + for i := range crd.Versions { + ver := &crd.Versions[i] + if ver.Name != version { + continue + } + selectableFields = &ver.SelectableFields + break + } + if selectableFields == nil { + return fmt.Errorf("selectable field applied to version %q not in CRD", version) + } + + *selectableFields = append(*selectableFields, apiext.SelectableField{ + JSONPath: s.JSONPath, + }) + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/doc.go new file mode 100644 index 000000000..f01e9f1b3 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/doc.go @@ -0,0 +1,59 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package markers defines markers for generating schema valiation +// and CRD structure. +// +// All markers related to CRD generation live in AllDefinitions. +// +// # Validation Markers +// +// Validation markers have values that implement ApplyToSchema +// (crd.SchemaMarker). Any marker implementing this will automatically +// be run after the rest of a given schema node has been generated. +// Markers that need to be run before any other markers can also +// implement ApplyFirst, but this is discouraged and may change +// in the future. It is recommended to implement the ApplyPriority +// interface in combination with ApplyPriorityDefault and +// ApplyPriorityFirst constants. Following is an example of how to +// implement such a marker: +// +// type MyCustomMarker string +// +// func (m MyCustomMarker) ApplyPriority() ApplyPriority { +// return ApplyPriorityFirst +// } +// +// func (m MyCustomMarker) ApplyToSchema(schema *apiext.JSONSchemaProps) error { +// ... +// } +// +// All validation markers start with "+kubebuilder:validation", and +// have the same name as their type name. +// +// # CRD Markers +// +// Markers that modify anything in the CRD itself *except* for the schema +// implement ApplyToCRD (crd.SpecMarker). They are expected to detect whether +// they should apply themselves to a specific version in the CRD (as passed to +// them), or to the root-level CRD for legacy cases. They are applied *after* +// the rest of the CRD is computed. +// +// # Misc +// +// This package also defines the "+groupName" and "+versionName" package-level +// markers, for defining package<->group-version mappings. +package markers diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/package.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/package.go new file mode 100644 index 000000000..86851b2c4 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/package.go @@ -0,0 +1,40 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func init() { + AllDefinitions = append(AllDefinitions, + mustOptional(markers.MakeDefinition("groupName", markers.DescribesPackage, "")). + WithHelp(markers.SimpleHelp("CRD", "specifies the API group name for this package.")), + + must(markers.MakeDefinition("versionName", markers.DescribesPackage, "")). + WithHelp(markers.SimpleHelp("CRD", "overrides the API group version for this package (defaults to the package name).")), + + must(markers.MakeDefinition("kubebuilder:validation:Optional", markers.DescribesPackage, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that all fields in this package are optional by default.")), + + must(markers.MakeDefinition("kubebuilder:validation:Required", markers.DescribesPackage, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that all fields in this package are required by default.")), + + must(markers.MakeDefinition("kubebuilder:skip", markers.DescribesPackage, struct{}{})). + WithHelp(markers.SimpleHelp("CRD", "don't consider this package as an API version.")), + ) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/priority.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/priority.go new file mode 100644 index 000000000..1b4482521 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/priority.go @@ -0,0 +1,37 @@ +/* +Copyright 2022 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +// ApplyPriority designates the order markers should be applied. +// Lower priority indicates it should be applied first +type ApplyPriority int64 + +const ( + // ApplyPriorityDefault is the default priority for markers + // that don't implement ApplyPriorityMarker + ApplyPriorityDefault ApplyPriority = 10 + + // ApplyPriorityFirst is the priority value assigned to markers + // that implement the ApplyFirst() method + ApplyPriorityFirst ApplyPriority = 1 +) + +// ApplyPriorityMarker designates the order validation markers should be applied. +// Lower priority indicates it should be applied first +type ApplyPriorityMarker interface { + ApplyPriority() ApplyPriority +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/register.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/register.go new file mode 100644 index 000000000..b5a2760b0 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/register.go @@ -0,0 +1,105 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "fmt" + "reflect" + + "sigs.k8s.io/controller-tools/pkg/markers" +) + +type definitionWithHelp struct { + *markers.Definition + Help *markers.DefinitionHelp +} + +func (d *definitionWithHelp) WithHelp(help *markers.DefinitionHelp) *definitionWithHelp { + d.Help = help + return d +} + +func (d *definitionWithHelp) Register(reg *markers.Registry) error { + if err := reg.Register(d.Definition); err != nil { + return err + } + if d.Help != nil { + reg.AddHelp(d.Definition, d.Help) + } + return nil +} + +func (d *definitionWithHelp) clone() *definitionWithHelp { + newDef, newHelp := *d.Definition, *d.Help + return &definitionWithHelp{ + Definition: &newDef, + Help: &newHelp, + } +} + +func must(def *markers.Definition, err error) *definitionWithHelp { + return &definitionWithHelp{ + Definition: markers.Must(def, err), + } +} + +func mustOptional(def *markers.Definition, err error) *definitionWithHelp { + def = markers.Must(def, err) + if !def.AnonymousField() { + def = markers.Must(def, fmt.Errorf("not an anonymous field: %v", def)) + } + field := def.Fields[""] + field.Optional = true + def.Fields[""] = field + return &definitionWithHelp{ + Definition: def, + } +} + +// AllDefinitions contains all marker definitions for this package. +var AllDefinitions []*definitionWithHelp + +type hasHelp interface { + Help() *markers.DefinitionHelp +} + +// mustMakeAllWithPrefix converts each object into a marker definition using +// the object's type's with the prefix to form the marker name. +func mustMakeAllWithPrefix(prefix string, target markers.TargetType, objs ...interface{}) []*definitionWithHelp { + defs := make([]*definitionWithHelp, len(objs)) + for i, obj := range objs { + name := prefix + reflect.TypeOf(obj).Name() + def, err := markers.MakeDefinition(name, target, obj) + if err != nil { + panic(err) + } + defs[i] = &definitionWithHelp{Definition: def, Help: obj.(hasHelp).Help()} + } + + return defs +} + +// Register registers all definitions for CRD generation to the given registry. +func Register(reg *markers.Registry) error { + for _, def := range AllDefinitions { + if err := def.Register(reg); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/topology.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/topology.go new file mode 100644 index 000000000..3a660dfe3 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/topology.go @@ -0,0 +1,175 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "fmt" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// TopologyMarkers specify topology markers (i.e. markers that describe if a +// list behaves as an associative-list or a set, if a map is atomic or not). +var TopologyMarkers = []*definitionWithHelp{ + must(markers.MakeDefinition("listMapKey", markers.DescribesField, ListMapKey(""))). + WithHelp(ListMapKey("").Help()), + must(markers.MakeDefinition("listMapKey", markers.DescribesType, ListMapKey(""))). + WithHelp(ListMapKey("").Help()), + must(markers.MakeDefinition("listType", markers.DescribesField, ListType(""))). + WithHelp(ListType("").Help()), + must(markers.MakeDefinition("listType", markers.DescribesType, ListType(""))). + WithHelp(ListType("").Help()), + must(markers.MakeDefinition("mapType", markers.DescribesField, MapType(""))). + WithHelp(MapType("").Help()), + must(markers.MakeDefinition("mapType", markers.DescribesType, MapType(""))). + WithHelp(MapType("").Help()), + must(markers.MakeDefinition("structType", markers.DescribesField, StructType(""))). + WithHelp(StructType("").Help()), + must(markers.MakeDefinition("structType", markers.DescribesType, StructType(""))). + WithHelp(StructType("").Help()), +} + +func init() { + AllDefinitions = append(AllDefinitions, TopologyMarkers...) +} + +// +controllertools:marker:generateHelp:category="CRD processing" + +// ListType specifies the type of data-structure that the list +// represents (map, set, atomic). +// +// Possible data-structure types of a list are: +// +// - "map": it needs to have a key field, which will be used to build an +// associative list. A typical example is a the pod container list, +// which is indexed by the container name. +// +// - "set": Fields need to be "scalar", and there can be only one +// occurrence of each. +// +// - "atomic": All the fields in the list are treated as a single value, +// are typically manipulated together by the same actor. +type ListType string + +const ( + Map ListType = "map" + Set ListType = "set" + Atomic ListType = "atomic" + Array ListType = "array" + Object ListType = "object" + Integer ListType = "integer" + Number ListType = "number" +) + +// +controllertools:marker:generateHelp:category="CRD processing" + +// ListMapKey specifies the keys to map listTypes. +// +// It indicates the index of a map list. They can be repeated if multiple keys +// must be used. It can only be used when ListType is set to map, and the keys +// should be scalar types. +type ListMapKey string + +// +controllertools:marker:generateHelp:category="CRD processing" + +// MapType specifies the level of atomicity of the map; +// i.e. whether each item in the map is independent of the others, +// or all fields are treated as a single unit. +// +// Possible values: +// +// - "granular": items in the map are independent of each other, +// and can be manipulated by different actors. +// This is the default behavior. +// +// - "atomic": all fields are treated as one unit. +// Any changes have to replace the entire map. +type MapType string + +// +controllertools:marker:generateHelp:category="CRD processing" + +// StructType specifies the level of atomicity of the struct; +// i.e. whether each field in the struct is independent of the others, +// or all fields are treated as a single unit. +// +// Possible values: +// +// - "granular": fields in the struct are independent of each other, +// and can be manipulated by different actors. +// This is the default behavior. +// +// - "atomic": all fields are treated as one unit. +// Any changes have to replace the entire struct. +type StructType string + +func (l ListType) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Array) { + return fmt.Errorf("must apply listType to an array, found %s", schema.Type) + } + if l != Map && l != Atomic && l != Set { + return fmt.Errorf(`ListType must be either "map", "set" or "atomic"`) + } + p := string(l) + schema.XListType = &p + return nil +} + +func (l ListType) ApplyPriority() ApplyPriority { + return ApplyPriorityDefault - 1 +} + +func (l ListMapKey) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Array) { + return fmt.Errorf("must apply listMapKey to an array, found %s", schema.Type) + } + if schema.XListType == nil || *schema.XListType != string(Map) { + return fmt.Errorf("must apply listMapKey to an associative-list") + } + schema.XListMapKeys = append(schema.XListMapKeys, string(l)) + return nil +} + +func (m MapType) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Object) { + return fmt.Errorf("must apply mapType to an object") + } + + if m != "atomic" && m != "granular" { + return fmt.Errorf(`MapType must be either "granular" or "atomic"`) + } + + p := string(m) + schema.XMapType = &p + + return nil +} + +func (s StructType) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Object) && schema.Type != "" { + return fmt.Errorf("must apply structType to an object; either explicitly set or defaulted through an empty schema type") + } + + if s != "atomic" && s != "granular" { + return fmt.Errorf(`StructType must be either "granular" or "atomic"`) + } + + p := string(s) + schema.XMapType = &p + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go new file mode 100644 index 000000000..e1cad593c --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go @@ -0,0 +1,637 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "encoding/json" + "fmt" + "math" + "strings" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +const ( + validationPrefix = "kubebuilder:validation:" + + SchemalessName = "kubebuilder:validation:Schemaless" + ValidationItemsPrefix = validationPrefix + "items:" +) + +// ValidationMarkers lists all available markers that affect CRD schema generation, +// except for the few that don't make sense as type-level markers (see FieldOnlyMarkers). +// All markers start with `+kubebuilder:validation:`, and continue with their type name. +// A copy is produced of all markers that describes types as well, for making types +// reusable and writing complex validations on slice items. +// At last a copy of all markers with the prefix `+kubebuilder:validation:items:` is +// produced for marking slice fields and types. +var ValidationMarkers = mustMakeAllWithPrefix(validationPrefix, markers.DescribesField, + + // numeric markers + + Maximum(0), + Minimum(0), + ExclusiveMaximum(false), + ExclusiveMinimum(false), + MultipleOf(0), + MinProperties(0), + MaxProperties(0), + + // string markers + + MaxLength(0), + MinLength(0), + Pattern(""), + + // slice markers + + MaxItems(0), + MinItems(0), + UniqueItems(false), + + // general markers + + Enum(nil), + Format(""), + Type(""), + XPreserveUnknownFields{}, + XEmbeddedResource{}, + XIntOrString{}, + XValidation{}, +) + +// FieldOnlyMarkers list field-specific validation markers (i.e. those markers that don't make +// sense on a type, and thus aren't in ValidationMarkers). +var FieldOnlyMarkers = []*definitionWithHelp{ + must(markers.MakeDefinition("kubebuilder:validation:Required", markers.DescribesField, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is required.")), + must(markers.MakeDefinition("kubebuilder:validation:Optional", markers.DescribesField, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is optional.")), + must(markers.MakeDefinition("required", markers.DescribesField, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is required.")), + must(markers.MakeDefinition("optional", markers.DescribesField, struct{}{})). + WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is optional.")), + + must(markers.MakeDefinition("nullable", markers.DescribesField, Nullable{})). + WithHelp(Nullable{}.Help()), + + must(markers.MakeAnyTypeDefinition("kubebuilder:default", markers.DescribesField, Default{})). + WithHelp(Default{}.Help()), + must(markers.MakeDefinition("default", markers.DescribesField, KubernetesDefault{})). + WithHelp(KubernetesDefault{}.Help()), + + must(markers.MakeAnyTypeDefinition("kubebuilder:example", markers.DescribesField, Example{})). + WithHelp(Example{}.Help()), + + must(markers.MakeDefinition("kubebuilder:validation:EmbeddedResource", markers.DescribesField, XEmbeddedResource{})). + WithHelp(XEmbeddedResource{}.Help()), + + must(markers.MakeDefinition(SchemalessName, markers.DescribesField, Schemaless{})). + WithHelp(Schemaless{}.Help()), + + must(markers.MakeAnyTypeDefinition("kubebuilder:title", markers.DescribesField, Title{})). + WithHelp(Title{}.Help()), +} + +// ValidationIshMarkers are field-and-type markers that don't fall under the +// :validation: prefix, and/or don't have a name that directly matches their +// type. +var ValidationIshMarkers = []*definitionWithHelp{ + must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesField, XPreserveUnknownFields{})). + WithHelp(XPreserveUnknownFields{}.Help()), + must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesType, XPreserveUnknownFields{})). + WithHelp(XPreserveUnknownFields{}.Help()), +} + +func init() { + AllDefinitions = append(AllDefinitions, ValidationMarkers...) + + for _, def := range ValidationMarkers { + typDef := def.clone() + typDef.Target = markers.DescribesType + AllDefinitions = append(AllDefinitions, typDef) + + itemsName := ValidationItemsPrefix + strings.TrimPrefix(def.Name, validationPrefix) + + itemsFieldDef := def.clone() + itemsFieldDef.Name = itemsName + itemsFieldDef.Help.Summary = "for array items " + itemsFieldDef.Help.Summary + AllDefinitions = append(AllDefinitions, itemsFieldDef) + + itemsTypDef := def.clone() + itemsTypDef.Name = itemsName + itemsTypDef.Help.Summary = "for array items " + itemsTypDef.Help.Summary + itemsTypDef.Target = markers.DescribesType + AllDefinitions = append(AllDefinitions, itemsTypDef) + } + + AllDefinitions = append(AllDefinitions, FieldOnlyMarkers...) + AllDefinitions = append(AllDefinitions, ValidationIshMarkers...) +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Maximum specifies the maximum numeric value that this field can have. +type Maximum float64 + +func (m Maximum) Value() float64 { + return float64(m) +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Minimum specifies the minimum numeric value that this field can have. Negative numbers are supported. +type Minimum float64 + +func (m Minimum) Value() float64 { + return float64(m) +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// ExclusiveMinimum indicates that the minimum is "up to" but not including that value. +type ExclusiveMinimum bool + +// +controllertools:marker:generateHelp:category="CRD validation" +// ExclusiveMaximum indicates that the maximum is "up to" but not including that value. +type ExclusiveMaximum bool + +// +controllertools:marker:generateHelp:category="CRD validation" +// MultipleOf specifies that this field must have a numeric value that's a multiple of this one. +type MultipleOf float64 + +func (m MultipleOf) Value() float64 { + return float64(m) +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// MaxLength specifies the maximum length for this string. +type MaxLength int + +// +controllertools:marker:generateHelp:category="CRD validation" +// MinLength specifies the minimum length for this string. +type MinLength int + +// +controllertools:marker:generateHelp:category="CRD validation" +// Pattern specifies that this string must match the given regular expression. +type Pattern string + +// +controllertools:marker:generateHelp:category="CRD validation" +// MaxItems specifies the maximum length for this list. +type MaxItems int + +// +controllertools:marker:generateHelp:category="CRD validation" +// MinItems specifies the minimum length for this list. +type MinItems int + +// +controllertools:marker:generateHelp:category="CRD validation" +// UniqueItems specifies that all items in this list must be unique. +type UniqueItems bool + +// +controllertools:marker:generateHelp:category="CRD validation" +// MaxProperties restricts the number of keys in an object +type MaxProperties int + +// +controllertools:marker:generateHelp:category="CRD validation" +// MinProperties restricts the number of keys in an object +type MinProperties int + +// +controllertools:marker:generateHelp:category="CRD validation" +// Enum specifies that this (scalar) field is restricted to the *exact* values specified here. +type Enum []interface{} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Format specifies additional "complex" formatting for this field. +// +// For example, a date-time field would be marked as "type: string" and +// "format: date-time". +type Format string + +// +controllertools:marker:generateHelp:category="CRD validation" +// Type overrides the type for this field (which defaults to the equivalent of the Go type). +// +// This generally must be paired with custom serialization. For example, the +// metav1.Time field would be marked as "type: string" and "format: date-time". +type Type string + +// +controllertools:marker:generateHelp:category="CRD validation" +// Nullable marks this field as allowing the "null" value. +// +// This is often not necessary, but may be helpful with custom serialization. +type Nullable struct{} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Default sets the default value for this field. +// +// A default value will be accepted as any value valid for the +// field. Formatting for common types include: boolean: `true`, string: +// `Cluster`, numerical: `1.24`, array: `{1,2}`, object: `{policy: +// "delete"}`). Defaults should be defined in pruned form, and only best-effort +// validation will be performed. Full validation of a default requires +// submission of the containing CRD to an apiserver. +type Default struct { + Value interface{} +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Title sets the title for this field. +// +// The title is metadata that makes the OpenAPI documentation more user-friendly, +// making the schema more understandable when viewed in documentation tools. +// It's a metadata field that doesn't affect validation but provides +// important context about what the schema represents. +type Title struct { + Value interface{} +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Default sets the default value for this field. +// +// A default value will be accepted as any value valid for the field. +// Only JSON-formatted values are accepted. `ref(...)` values are ignored. +// Formatting for common types include: boolean: `true`, string: +// `"Cluster"`, numerical: `1.24`, array: `[1,2]`, object: `{"policy": +// "delete"}`). Defaults should be defined in pruned form, and only best-effort +// validation will be performed. Full validation of a default requires +// submission of the containing CRD to an apiserver. +type KubernetesDefault struct { + Value interface{} +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Example sets the example value for this field. +// +// An example value will be accepted as any value valid for the +// field. Formatting for common types include: boolean: `true`, string: +// `Cluster`, numerical: `1.24`, array: `{1,2}`, object: `{policy: +// "delete"}`). Examples should be defined in pruned form, and only best-effort +// validation will be performed. Full validation of an example requires +// submission of the containing CRD to an apiserver. +type Example struct { + Value interface{} +} + +// +controllertools:marker:generateHelp:category="CRD processing" +// PreserveUnknownFields stops the apiserver from pruning fields which are not specified. +// +// By default the apiserver drops unknown fields from the request payload +// during the decoding step. This marker stops the API server from doing so. +// It affects fields recursively, but switches back to normal pruning behaviour +// if nested properties or additionalProperties are specified in the schema. +// This can either be true or undefined. False +// is forbidden. +// +// NB: The kubebuilder:validation:XPreserveUnknownFields variant is deprecated +// in favor of the kubebuilder:pruning:PreserveUnknownFields variant. They function +// identically. +type XPreserveUnknownFields struct{} + +// +controllertools:marker:generateHelp:category="CRD validation" +// EmbeddedResource marks a fields as an embedded resource with apiVersion, kind and metadata fields. +// +// An embedded resource is a value that has apiVersion, kind and metadata fields. +// They are validated implicitly according to the semantics of the currently +// running apiserver. It is not necessary to add any additional schema for these +// field, yet it is possible. This can be combined with PreserveUnknownFields. +type XEmbeddedResource struct{} + +// +controllertools:marker:generateHelp:category="CRD validation" +// IntOrString marks a fields as an IntOrString. +// +// This is required when applying patterns or other validations to an IntOrString +// field. Known information about the type is applied during the collapse phase +// and as such is not normally available during marker application. +type XIntOrString struct{} + +// +controllertools:marker:generateHelp:category="CRD validation" +// Schemaless marks a field as being a schemaless object. +// +// Schemaless objects are not introspected, so you must provide +// any type and validation information yourself. One use for this +// tag is for embedding fields that hold JSONSchema typed objects. +// Because this field disables all type checking, it is recommended +// to be used only as a last resort. +type Schemaless struct{} + +func hasNumericType(schema *apiext.JSONSchemaProps) bool { + return schema.Type == string(Integer) || schema.Type == string(Number) +} + +func hasTextualType(schema *apiext.JSONSchemaProps) bool { + return schema.Type == "string" || schema.XIntOrString +} + +func isIntegral(value float64) bool { + return value == math.Trunc(value) && !math.IsNaN(value) && !math.IsInf(value, 0) +} + +// +controllertools:marker:generateHelp:category="CRD validation" +// XValidation marks a field as requiring a value for which a given +// expression evaluates to true. +// +// This marker may be repeated to specify multiple expressions, all of +// which must evaluate to true. +type XValidation struct { + Rule string + Message string `marker:",optional"` + MessageExpression string `marker:"messageExpression,optional"` + Reason string `marker:"reason,optional"` + FieldPath string `marker:"fieldPath,optional"` + OptionalOldSelf *bool `marker:"optionalOldSelf,optional"` +} + +func (m Maximum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasNumericType(schema) { + return fmt.Errorf("must apply maximum to a numeric value, found %s", schema.Type) + } + + if schema.Type == string(Integer) && !isIntegral(m.Value()) { + return fmt.Errorf("cannot apply non-integral maximum validation (%v) to integer value", m.Value()) + } + + val := m.Value() + schema.Maximum = &val + return nil +} + +func (m Minimum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasNumericType(schema) { + return fmt.Errorf("must apply minimum to a numeric value, found %s", schema.Type) + } + + if schema.Type == "integer" && !isIntegral(m.Value()) { + return fmt.Errorf("cannot apply non-integral minimum validation (%v) to integer value", m.Value()) + } + + val := m.Value() + schema.Minimum = &val + return nil +} + +func (m ExclusiveMaximum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasNumericType(schema) { + return fmt.Errorf("must apply exclusivemaximum to a numeric value, found %s", schema.Type) + } + schema.ExclusiveMaximum = bool(m) + return nil +} + +func (m ExclusiveMinimum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasNumericType(schema) { + return fmt.Errorf("must apply exclusiveminimum to a numeric value, found %s", schema.Type) + } + + schema.ExclusiveMinimum = bool(m) + return nil +} + +func (m MultipleOf) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasNumericType(schema) { + return fmt.Errorf("must apply multipleof to a numeric value, found %s", schema.Type) + } + + if schema.Type == "integer" && !isIntegral(m.Value()) { + return fmt.Errorf("cannot apply non-integral multipleof validation (%v) to integer value", m.Value()) + } + + val := m.Value() + schema.MultipleOf = &val + return nil +} + +func (m MaxLength) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasTextualType(schema) { + return fmt.Errorf("must apply maxlength to a textual value, found type %q", schema.Type) + } + val := int64(m) + schema.MaxLength = &val + return nil +} + +func (m MinLength) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasTextualType(schema) { + return fmt.Errorf("must apply minlength to a textual value, found type %q", schema.Type) + } + val := int64(m) + schema.MinLength = &val + return nil +} + +func (m Pattern) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if !hasTextualType(schema) { + return fmt.Errorf("must apply pattern to a textual value, found type %q", schema.Type) + } + schema.Pattern = string(m) + return nil +} + +func (m MaxItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Array) { + return fmt.Errorf("must apply maxitem to an array") + } + val := int64(m) + schema.MaxItems = &val + return nil +} + +func (m MinItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != string(Array) { + return fmt.Errorf("must apply minitems to an array") + } + val := int64(m) + schema.MinItems = &val + return nil +} + +func (m UniqueItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != "array" { + return fmt.Errorf("must apply uniqueitems to an array") + } + schema.UniqueItems = bool(m) + return nil +} + +func (m MinProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != "object" { + return fmt.Errorf("must apply minproperties to an object") + } + val := int64(m) + schema.MinProperties = &val + return nil +} + +func (m MaxProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != "object" { + return fmt.Errorf("must apply maxproperties to an object") + } + val := int64(m) + schema.MaxProperties = &val + return nil +} + +func (m Enum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + // TODO(directxman12): this is a bit hacky -- we should + // probably support AnyType better + using the schema structure + vals := make([]apiext.JSON, len(m)) + for i, val := range m { + // TODO(directxman12): check actual type with schema type? + // if we're expecting a string, marshal the string properly... + // NB(directxman12): we use json.Marshal to ensure we handle JSON escaping properly + valMarshalled, err := json.Marshal(val) + if err != nil { + return err + } + vals[i] = apiext.JSON{Raw: valMarshalled} + } + schema.Enum = vals + return nil +} + +func (m Format) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + schema.Format = string(m) + return nil +} + +// NB(directxman12): we "typecheck" on target schema properties here, +// which means the "Type" marker *must* be applied first. +// TODO(directxman12): find a less hacky way to do this +// (we could preserve ordering of markers, but that feels bad in its own right). + +func (m Type) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + schema.Type = string(m) + return nil +} + +func (m Type) ApplyPriority() ApplyPriority { + return ApplyPriorityDefault - 1 +} + +func (m Nullable) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + schema.Nullable = true + return nil +} + +// Defaults are only valid CRDs created with the v1 API +func (m Default) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + marshalledDefault, err := json.Marshal(m.Value) + if err != nil { + return err + } + if schema.Type == "array" && string(marshalledDefault) == "{}" { + marshalledDefault = []byte("[]") + } + schema.Default = &apiext.JSON{Raw: marshalledDefault} + return nil +} + +func (m Default) ApplyPriority() ApplyPriority { + // explicitly go after +default markers, so kubebuilder-specific defaults get applied last and stomp + return 10 +} + +func (m Title) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if m.Value == nil { + // only apply to the schema if we have a non-nil title + return nil + } + title, isStr := m.Value.(string) + if !isStr { + return fmt.Errorf("expected string, got %T", m.Value) + } + schema.Title = title + return nil +} + +func (m *KubernetesDefault) ParseMarker(_ string, _ string, restFields string) error { + if strings.HasPrefix(strings.TrimSpace(restFields), "ref(") { + // Skip +default=ref(...) values for now, since we don't have a good way to evaluate go constant values via AST. + // See https://github.com/kubernetes-sigs/controller-tools/pull/938#issuecomment-2096790018 + return nil + } + return json.Unmarshal([]byte(restFields), &m.Value) +} + +// Defaults are only valid CRDs created with the v1 API +func (m KubernetesDefault) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if m.Value == nil { + // only apply to the schema if we have a non-nil default value + return nil + } + marshalledDefault, err := json.Marshal(m.Value) + if err != nil { + return err + } + schema.Default = &apiext.JSON{Raw: marshalledDefault} + return nil +} + +func (m KubernetesDefault) ApplyPriority() ApplyPriority { + // explicitly go before +kubebuilder:default markers, so kubebuilder-specific defaults get applied last and stomp + return 9 +} + +func (m Example) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + marshalledExample, err := json.Marshal(m.Value) + if err != nil { + return err + } + schema.Example = &apiext.JSON{Raw: marshalledExample} + return nil +} + +func (m XPreserveUnknownFields) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + defTrue := true + schema.XPreserveUnknownFields = &defTrue + return nil +} + +func (m XEmbeddedResource) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + schema.XEmbeddedResource = true + return nil +} + +// NB(JoelSpeed): we use this property in other markers here, +// which means the "XIntOrString" marker *must* be applied first. + +func (m XIntOrString) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + schema.XIntOrString = true + return nil +} + +func (m XIntOrString) ApplyPriority() ApplyPriority { + return ApplyPriorityDefault - 1 +} + +func (m XValidation) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + var reason *apiext.FieldValueErrorReason + if m.Reason != "" { + switch m.Reason { + case string(apiext.FieldValueRequired), string(apiext.FieldValueInvalid), string(apiext.FieldValueForbidden), string(apiext.FieldValueDuplicate): + reason = (*apiext.FieldValueErrorReason)(&m.Reason) + default: + return fmt.Errorf("invalid reason %s, valid values are %s, %s, %s and %s", m.Reason, apiext.FieldValueRequired, apiext.FieldValueInvalid, apiext.FieldValueForbidden, apiext.FieldValueDuplicate) + } + } + + schema.XValidations = append(schema.XValidations, apiext.ValidationRule{ + Rule: m.Rule, + Message: m.Message, + MessageExpression: m.MessageExpression, + Reason: reason, + FieldPath: m.FieldPath, + OptionalOldSelf: m.OptionalOldSelf, + }) + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go new file mode 100644 index 000000000..7d8282cfc --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go @@ -0,0 +1,588 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package markers + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Default) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "sets the default value for this field.", + Details: "A default value will be accepted as any value valid for the\nfield. Formatting for common types include: boolean: `true`, string:\n`Cluster`, numerical: `1.24`, array: `{1,2}`, object: `{policy:\n\"delete\"}`). Defaults should be defined in pruned form, and only best-effort\nvalidation will be performed. Full validation of a default requires\nsubmission of the containing CRD to an apiserver.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Value": { + Summary: "", + Details: "", + }, + }, + } +} + +func (DeprecatedVersion) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks this version as deprecated.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Warning": { + Summary: "message to be shown on the deprecated version", + Details: "", + }, + }, + } +} + +func (Enum) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies that this (scalar) field is restricted to the *exact* values specified here.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Example) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "sets the example value for this field.", + Details: "An example value will be accepted as any value valid for the\nfield. Formatting for common types include: boolean: `true`, string:\n`Cluster`, numerical: `1.24`, array: `{1,2}`, object: `{policy:\n\"delete\"}`). Examples should be defined in pruned form, and only best-effort\nvalidation will be performed. Full validation of an example requires\nsubmission of the containing CRD to an apiserver.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Value": { + Summary: "", + Details: "", + }, + }, + } +} + +func (ExclusiveMaximum) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "indicates that the maximum is \"up to\" but not including that value.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (ExclusiveMinimum) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "indicates that the minimum is \"up to\" but not including that value.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Format) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies additional \"complex\" formatting for this field.", + Details: "For example, a date-time field would be marked as \"type: string\" and\n\"format: date-time\".", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (KubernetesDefault) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "Default sets the default value for this field.", + Details: "A default value will be accepted as any value valid for the field.\nOnly JSON-formatted values are accepted. `ref(...)` values are ignored.\nFormatting for common types include: boolean: `true`, string:\n`\"Cluster\"`, numerical: `1.24`, array: `[1,2]`, object: `{\"policy\":\n\"delete\"}`). Defaults should be defined in pruned form, and only best-effort\nvalidation will be performed. Full validation of a default requires\nsubmission of the containing CRD to an apiserver.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Value": { + Summary: "", + Details: "", + }, + }, + } +} + +func (ListMapKey) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD processing", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the keys to map listTypes.", + Details: "It indicates the index of a map list. They can be repeated if multiple keys\nmust be used. It can only be used when ListType is set to map, and the keys\nshould be scalar types.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (ListType) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD processing", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the type of data-structure that the list", + Details: "represents (map, set, atomic).\n\nPossible data-structure types of a list are:\n\n - \"map\": it needs to have a key field, which will be used to build an\n associative list. A typical example is a the pod container list,\n which is indexed by the container name.\n\n - \"set\": Fields need to be \"scalar\", and there can be only one\n occurrence of each.\n\n - \"atomic\": All the fields in the list are treated as a single value,\n are typically manipulated together by the same actor.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MapType) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD processing", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the level of atomicity of the map;", + Details: "i.e. whether each item in the map is independent of the others,\nor all fields are treated as a single unit.\n\nPossible values:\n\n - \"granular\": items in the map are independent of each other,\n and can be manipulated by different actors.\n This is the default behavior.\n\n - \"atomic\": all fields are treated as one unit.\n Any changes have to replace the entire map.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MaxItems) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the maximum length for this list.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MaxLength) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the maximum length for this string.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MaxProperties) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "restricts the number of keys in an object", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Maximum) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the maximum numeric value that this field can have.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Metadata) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "configures the additional annotations or labels for this CRD.", + Details: "For example adding annotation \"api-approved.kubernetes.io\" for a CRD with Kubernetes groups,\nor annotation \"cert-manager.io/inject-ca-from-secret\" for a CRD that needs CA injection.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Annotations": { + Summary: "will be added into the annotations of this CRD.", + Details: "", + }, + "Labels": { + Summary: "will be added into the labels of this CRD.", + Details: "", + }, + }, + } +} + +func (MinItems) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the minimum length for this list.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MinLength) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the minimum length for this string.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MinProperties) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "restricts the number of keys in an object", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Minimum) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the minimum numeric value that this field can have. Negative numbers are supported.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (MultipleOf) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies that this field must have a numeric value that's a multiple of this one.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Nullable) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks this field as allowing the \"null\" value.", + Details: "This is often not necessary, but may be helpful with custom serialization.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Pattern) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies that this string must match the given regular expression.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (PrintColumn) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "adds a column to \"kubectl get\" output for this CRD.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Name": { + Summary: "specifies the name of the column.", + Details: "", + }, + "Type": { + Summary: "indicates the type of the column.", + Details: "It may be any OpenAPI data type listed at\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types.", + }, + "JSONPath": { + Summary: "specifies the jsonpath expression used to extract the value of the column.", + Details: "", + }, + "Description": { + Summary: "specifies the help/description for this column.", + Details: "", + }, + "Format": { + Summary: "specifies the format of the column.", + Details: "It may be any OpenAPI data format corresponding to the type, listed at\nhttps://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types.", + }, + "Priority": { + Summary: "indicates how important it is that this column be displayed.", + Details: "Lower priority (*higher* numbered) columns will be hidden if the terminal\nwidth is too small.", + }, + }, + } +} + +func (Resource) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "configures naming and scope for a CRD.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Path": { + Summary: "specifies the plural \"resource\" for this CRD.", + Details: "It generally corresponds to a plural, lower-cased version of the Kind.\nSee https://book.kubebuilder.io/cronjob-tutorial/gvks.html.", + }, + "ShortName": { + Summary: "specifies aliases for this CRD.", + Details: "Short names are often used when people have work with your resource\nover and over again. For instance, \"rs\" for \"replicaset\" or\n\"crd\" for customresourcedefinition.", + }, + "Categories": { + Summary: "specifies which group aliases this resource is part of.", + Details: "Group aliases are used to work with groups of resources at once.\nThe most common one is \"all\" which covers about a third of the base\nresources in Kubernetes, and is generally used for \"user-facing\" resources.", + }, + "Singular": { + Summary: "overrides the singular form of your resource.", + Details: "The singular form is otherwise defaulted off the plural (path).", + }, + "Scope": { + Summary: "overrides the scope of the CRD (Cluster vs Namespaced).", + Details: "Scope defaults to \"Namespaced\". Cluster-scoped (\"Cluster\") resources\ndon't exist in namespaces.", + }, + }, + } +} + +func (Schemaless) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks a field as being a schemaless object.", + Details: "Schemaless objects are not introspected, so you must provide\nany type and validation information yourself. One use for this\ntag is for embedding fields that hold JSONSchema typed objects.\nBecause this field disables all type checking, it is recommended\nto be used only as a last resort.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (SelectableField) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "adds a field that may be used with field selectors.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "JSONPath": { + Summary: "specifies the jsonpath expression which is used to produce a field selector value.", + Details: "", + }, + }, + } +} + +func (SkipVersion) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "removes the particular version of the CRD from the CRDs spec.", + Details: "This is useful if you need to skip generating and listing version entries\nfor 'internal' resource versions, which typically exist if using the\nKubernetes upstream conversion-gen tool.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (StorageVersion) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks this version as the \"storage version\" for the CRD for conversion.", + Details: "When conversion is enabled for a CRD (i.e. it's not a trivial-versions/single-version CRD),\none version is set as the \"storage version\" to be stored in etcd. Attempting to store any\nother version will result in conversion to the storage version via a conversion webhook.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (StructType) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD processing", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies the level of atomicity of the struct;", + Details: "i.e. whether each field in the struct is independent of the others,\nor all fields are treated as a single unit.\n\nPossible values:\n\n - \"granular\": fields in the struct are independent of each other,\n and can be manipulated by different actors.\n This is the default behavior.\n\n - \"atomic\": all fields are treated as one unit.\n Any changes have to replace the entire struct.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (SubresourceScale) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "enables the \"/scale\" subresource on a CRD.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "SpecPath": { + Summary: "specifies the jsonpath to the replicas field for the scale's spec.", + Details: "", + }, + "StatusPath": { + Summary: "specifies the jsonpath to the replicas field for the scale's status.", + Details: "", + }, + "SelectorPath": { + Summary: "specifies the jsonpath to the pod label selector field for the scale's status.", + Details: "The selector field must be the *string* form (serialized form) of a selector.\nSetting a pod label selector is necessary for your type to work with the HorizontalPodAutoscaler.", + }, + }, + } +} + +func (SubresourceStatus) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "enables the \"/status\" subresource on a CRD.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (Title) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "sets the title for this field.", + Details: "The title is metadata that makes the OpenAPI documentation more user-friendly,\nmaking the schema more understandable when viewed in documentation tools.\nIt's a metadata field that doesn't affect validation but provides\nimportant context about what the schema represents.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Value": { + Summary: "", + Details: "", + }, + }, + } +} + +func (Type) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "overrides the type for this field (which defaults to the equivalent of the Go type).", + Details: "This generally must be paired with custom serialization. For example, the\nmetav1.Time field would be marked as \"type: string\" and \"format: date-time\".", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (UniqueItems) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies that all items in this list must be unique.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (UnservedVersion) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD", + DetailedHelp: markers.DetailedHelp{ + Summary: "does not serve this version.", + Details: "This is useful if you need to drop support for a version in favor of a newer version.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (XEmbeddedResource) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "EmbeddedResource marks a fields as an embedded resource with apiVersion, kind and metadata fields.", + Details: "An embedded resource is a value that has apiVersion, kind and metadata fields.\nThey are validated implicitly according to the semantics of the currently\nrunning apiserver. It is not necessary to add any additional schema for these\nfield, yet it is possible. This can be combined with PreserveUnknownFields.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (XIntOrString) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "IntOrString marks a fields as an IntOrString.", + Details: "This is required when applying patterns or other validations to an IntOrString\nfield. Known information about the type is applied during the collapse phase\nand as such is not normally available during marker application.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (XPreserveUnknownFields) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD processing", + DetailedHelp: markers.DetailedHelp{ + Summary: "PreserveUnknownFields stops the apiserver from pruning fields which are not specified.", + Details: "By default the apiserver drops unknown fields from the request payload\nduring the decoding step. This marker stops the API server from doing so.\nIt affects fields recursively, but switches back to normal pruning behaviour\nif nested properties or additionalProperties are specified in the schema.\nThis can either be true or undefined. False\nis forbidden.\n\nNB: The kubebuilder:validation:XPreserveUnknownFields variant is deprecated\nin favor of the kubebuilder:pruning:PreserveUnknownFields variant. They function\nidentically.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (XValidation) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks a field as requiring a value for which a given", + Details: "expression evaluates to true.\n\nThis marker may be repeated to specify multiple expressions, all of\nwhich must evaluate to true.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Rule": { + Summary: "", + Details: "", + }, + "Message": { + Summary: "", + Details: "", + }, + "MessageExpression": { + Summary: "", + Details: "", + }, + "Reason": { + Summary: "", + Details: "", + }, + "FieldPath": { + Summary: "", + Details: "", + }, + "OptionalOldSelf": { + Summary: "", + Details: "", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go new file mode 100644 index 000000000..4b96ee96f --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go @@ -0,0 +1,242 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + "fmt" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// TypeIdent represents some type in a Package. +type TypeIdent struct { + Package *loader.Package + Name string +} + +func (t TypeIdent) String() string { + return fmt.Sprintf("%q.%s", t.Package.ID, t.Name) +} + +// PackageOverride overrides the loading of some package +// (potentially setting custom schemata, etc). It must +// call AddPackage if it wants to continue with the default +// loading behavior. +type PackageOverride func(p *Parser, pkg *loader.Package) + +// Parser knows how to parse out CRD information and generate +// OpenAPI schemata from some collection of types and markers. +// Most methods on Parser cache their results automatically, +// and thus may be called any number of times. +type Parser struct { + Collector *markers.Collector + + // Types contains the known TypeInfo for this parser. + Types map[TypeIdent]*markers.TypeInfo + // Schemata contains the known OpenAPI JSONSchemata for this parser. + Schemata map[TypeIdent]apiext.JSONSchemaProps + // GroupVersions contains the known group-versions of each package in this parser. + GroupVersions map[*loader.Package]schema.GroupVersion + // CustomResourceDefinitions contains the known CustomResourceDefinitions for types in this parser. + CustomResourceDefinitions map[schema.GroupKind]apiext.CustomResourceDefinition + // FlattenedSchemata contains fully flattened schemata for use in building + // CustomResourceDefinition validation. Each schema has been flattened by the flattener, + // and then embedded fields have been flattened with FlattenEmbedded. + FlattenedSchemata map[TypeIdent]apiext.JSONSchemaProps + + // PackageOverrides indicates that the loading of any package with + // the given path should be handled by the given overrider. + PackageOverrides map[string]PackageOverride + + // checker stores persistent partial type-checking/reference-traversal information. + Checker *loader.TypeChecker + // packages marks packages as loaded, to avoid re-loading them. + packages map[*loader.Package]struct{} + + flattener *Flattener + + // AllowDangerousTypes controls the handling of non-recommended types such as float. If + // false (the default), these types are not supported. + // There is a continuum here: + // 1. Types that are always supported. + // 2. Types that are allowed by default, but not recommended (warning emitted when they are encountered as per PR #443). + // Possibly they are allowed by default for historical reasons and may even be "on their way out" at some point in the future. + // 3. Types that are not allowed by default, not recommended, but there are some legitimate reasons to need them in certain corner cases. + // Possibly these types should also emit a warning as per PR #443 even when they are "switched on" (an integration point between + // this feature and #443 if desired). This is the category that this flag deals with. + // 4. Types that are not allowed and will not be allowed, possibly because it just "doesn't make sense" or possibly + // because the implementation is too difficult/clunky to promote them to category 3. + // TODO: Should we have a more formal mechanism for putting "type patterns" in each of the above categories? + AllowDangerousTypes bool + + // IgnoreUnexportedFields specifies if unexported fields on the struct should be skipped + IgnoreUnexportedFields bool + + // GenerateEmbeddedObjectMeta specifies if any embedded ObjectMeta should be generated + GenerateEmbeddedObjectMeta bool +} + +func (p *Parser) init() { + if p.packages == nil { + p.packages = make(map[*loader.Package]struct{}) + } + if p.flattener == nil { + p.flattener = &Flattener{ + Parser: p, + } + } + if p.Schemata == nil { + p.Schemata = make(map[TypeIdent]apiext.JSONSchemaProps) + } + if p.Types == nil { + p.Types = make(map[TypeIdent]*markers.TypeInfo) + } + if p.PackageOverrides == nil { + p.PackageOverrides = make(map[string]PackageOverride) + } + if p.GroupVersions == nil { + p.GroupVersions = make(map[*loader.Package]schema.GroupVersion) + } + if p.CustomResourceDefinitions == nil { + p.CustomResourceDefinitions = make(map[schema.GroupKind]apiext.CustomResourceDefinition) + } + if p.FlattenedSchemata == nil { + p.FlattenedSchemata = make(map[TypeIdent]apiext.JSONSchemaProps) + } +} + +// indexTypes loads all types in the package into Types. +func (p *Parser) indexTypes(pkg *loader.Package) { + // autodetect + pkgMarkers, err := markers.PackageMarkers(p.Collector, pkg) + if err != nil { + pkg.AddError(err) + } else { + if skipPkg := pkgMarkers.Get("kubebuilder:skip"); skipPkg != nil { + return + } + if nameVal := pkgMarkers.Get("groupName"); nameVal != nil { + versionVal := pkg.Name // a reasonable guess + if versionMarker := pkgMarkers.Get("versionName"); versionMarker != nil { + versionVal = versionMarker.(string) + } + + p.GroupVersions[pkg] = schema.GroupVersion{ + Version: versionVal, + Group: nameVal.(string), + } + } + } + + if err := markers.EachType(p.Collector, pkg, func(info *markers.TypeInfo) { + ident := TypeIdent{ + Package: pkg, + Name: info.Name, + } + + p.Types[ident] = info + }); err != nil { + pkg.AddError(err) + } +} + +// LookupType fetches type info from Types. +func (p *Parser) LookupType(pkg *loader.Package, name string) *markers.TypeInfo { + return p.Types[TypeIdent{Package: pkg, Name: name}] +} + +// NeedSchemaFor indicates that a schema should be generated for the given type. +func (p *Parser) NeedSchemaFor(typ TypeIdent) { + p.init() + + p.NeedPackage(typ.Package) + if _, knownSchema := p.Schemata[typ]; knownSchema { + return + } + + info, knownInfo := p.Types[typ] + if !knownInfo { + typ.Package.AddError(fmt.Errorf("unknown type %s", typ)) + return + } + + // avoid tripping recursive schemata, like ManagedFields, by adding an empty WIP schema + p.Schemata[typ] = apiext.JSONSchemaProps{} + + schemaCtx := newSchemaContext(typ.Package, p, p.AllowDangerousTypes, p.IgnoreUnexportedFields) + ctxForInfo := schemaCtx.ForInfo(info) + + pkgMarkers, err := markers.PackageMarkers(p.Collector, typ.Package) + if err != nil { + typ.Package.AddError(err) + } + ctxForInfo.PackageMarkers = pkgMarkers + + schema := infoToSchema(ctxForInfo) + + p.Schemata[typ] = *schema +} + +func (p *Parser) NeedFlattenedSchemaFor(typ TypeIdent) { + p.init() + + if _, knownSchema := p.FlattenedSchemata[typ]; knownSchema { + return + } + + p.NeedSchemaFor(typ) + partialFlattened := p.flattener.FlattenType(typ) + fullyFlattened := FlattenEmbedded(partialFlattened, typ.Package) + + p.FlattenedSchemata[typ] = *fullyFlattened +} + +// NeedCRDFor lives off in spec.go + +// AddPackage indicates that types and type-checking information is needed +// for the the given package, *ignoring* overrides. +// Generally, consumers should call NeedPackage, while PackageOverrides should +// call AddPackage to continue with the normal loading procedure. +func (p *Parser) AddPackage(pkg *loader.Package) { + p.init() + if _, checked := p.packages[pkg]; checked { + return + } + p.indexTypes(pkg) + p.Checker.Check(pkg) + p.packages[pkg] = struct{}{} +} + +// NeedPackage indicates that types and type-checking information +// is needed for the given package. +func (p *Parser) NeedPackage(pkg *loader.Package) { + p.init() + if _, checked := p.packages[pkg]; checked { + return + } + // overrides are going to be written without vendor. This is why we index by the actual + // object when we can. + if override, overridden := p.PackageOverrides[loader.NonVendorPath(pkg.PkgPath)]; overridden { + override(p, pkg) + p.packages[pkg] = struct{}{} + return + } + p.AddPackage(pkg) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go new file mode 100644 index 000000000..616141cb1 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go @@ -0,0 +1,548 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + "errors" + "fmt" + "go/ast" + "go/token" + "go/types" + "sort" + "strings" + + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// Schema flattening is done in a recursive mapping method. +// Start reading at infoToSchema. + +const ( + // defPrefix is the prefix used to link to definitions in the OpenAPI schema. + defPrefix = "#/definitions/" +) + +// byteType is the types.Type for byte (see the types documention +// for why we need to look this up in the Universe), saved +// for quick comparison. +var byteType = types.Universe.Lookup("byte").Type() + +// SchemaMarker is any marker that needs to modify the schema of the underlying type or field. +type SchemaMarker interface { + // ApplyToSchema is called after the rest of the schema for a given type + // or field is generated, to modify the schema appropriately. + ApplyToSchema(*apiext.JSONSchemaProps) error +} + +// applyFirstMarker is applied before any other markers. It's a bit of a hack. +type applyFirstMarker interface { + ApplyFirst() +} + +// schemaRequester knows how to marker that another schema (e.g. via an external reference) is necessary. +type schemaRequester interface { + NeedSchemaFor(typ TypeIdent) +} + +// schemaContext stores and provides information across a hierarchy of schema generation. +type schemaContext struct { + pkg *loader.Package + info *markers.TypeInfo + + schemaRequester schemaRequester + PackageMarkers markers.MarkerValues + + allowDangerousTypes bool + ignoreUnexportedFields bool +} + +// newSchemaContext constructs a new schemaContext for the given package and schema requester. +// It must have type info added before use via ForInfo. +func newSchemaContext(pkg *loader.Package, req schemaRequester, allowDangerousTypes, ignoreUnexportedFields bool) *schemaContext { + pkg.NeedTypesInfo() + return &schemaContext{ + pkg: pkg, + schemaRequester: req, + allowDangerousTypes: allowDangerousTypes, + ignoreUnexportedFields: ignoreUnexportedFields, + } +} + +// ForInfo produces a new schemaContext with containing the same information +// as this one, except with the given type information. +func (c *schemaContext) ForInfo(info *markers.TypeInfo) *schemaContext { + return &schemaContext{ + pkg: c.pkg, + info: info, + schemaRequester: c.schemaRequester, + allowDangerousTypes: c.allowDangerousTypes, + ignoreUnexportedFields: c.ignoreUnexportedFields, + } +} + +// requestSchema asks for the schema for a type in the package with the +// given import path. +func (c *schemaContext) requestSchema(pkgPath, typeName string) { + pkg := c.pkg + if pkgPath != "" { + pkg = c.pkg.Imports()[pkgPath] + } + c.schemaRequester.NeedSchemaFor(TypeIdent{ + Package: pkg, + Name: typeName, + }) +} + +// infoToSchema creates a schema for the type in the given set of type information. +func infoToSchema(ctx *schemaContext) *apiext.JSONSchemaProps { + if obj := ctx.pkg.Types.Scope().Lookup(ctx.info.Name); obj != nil { + switch { + // If the obj implements a JSON marshaler and has a marker, use the + // markers value and do not traverse as the marshaler could be doing + // anything. If there is no marker, fall back to traversing. + case implements(obj.Type(), jsonMarshaler): + schema := &apiext.JSONSchemaProps{} + applyMarkers(ctx, ctx.info.Markers, schema, ctx.info.RawSpec.Type) + if schema.Type != "" { + return schema + } + + // If the obj implements a text marshaler, encode it as a string. + case implements(obj.Type(), textMarshaler): + schema := &apiext.JSONSchemaProps{Type: "string"} + applyMarkers(ctx, ctx.info.Markers, schema, ctx.info.RawSpec.Type) + if schema.Type != "string" { + err := fmt.Errorf("%q implements encoding.TextMarshaler but schema type is not string: %q", ctx.info.RawSpec.Name, schema.Type) + ctx.pkg.AddError(loader.ErrFromNode(err, ctx.info.RawSpec.Type)) + } + return schema + } + } + return typeToSchema(ctx, ctx.info.RawSpec.Type) +} + +type schemaMarkerWithName struct { + SchemaMarker SchemaMarker + Name string +} + +// applyMarkers applies schema markers given their priority to the given schema +func applyMarkers(ctx *schemaContext, markerSet markers.MarkerValues, props *apiext.JSONSchemaProps, node ast.Node) { + markers := make([]schemaMarkerWithName, 0, len(markerSet)) + itemsMarkers := make([]schemaMarkerWithName, 0, len(markerSet)) + + for markerName, markerValues := range markerSet { + for _, markerValue := range markerValues { + if schemaMarker, isSchemaMarker := markerValue.(SchemaMarker); isSchemaMarker { + if strings.HasPrefix(markerName, crdmarkers.ValidationItemsPrefix) { + itemsMarkers = append(itemsMarkers, schemaMarkerWithName{ + SchemaMarker: schemaMarker, + Name: markerName, + }) + } else { + markers = append(markers, schemaMarkerWithName{ + SchemaMarker: schemaMarker, + Name: markerName, + }) + } + } + } + } + + cmpPriority := func(markers []schemaMarkerWithName, i, j int) bool { + var iPriority, jPriority crdmarkers.ApplyPriority + + switch m := markers[i].SchemaMarker.(type) { + case crdmarkers.ApplyPriorityMarker: + iPriority = m.ApplyPriority() + case applyFirstMarker: + iPriority = crdmarkers.ApplyPriorityFirst + default: + iPriority = crdmarkers.ApplyPriorityDefault + } + + switch m := markers[j].SchemaMarker.(type) { + case crdmarkers.ApplyPriorityMarker: + jPriority = m.ApplyPriority() + case applyFirstMarker: + jPriority = crdmarkers.ApplyPriorityFirst + default: + jPriority = crdmarkers.ApplyPriorityDefault + } + + return iPriority < jPriority + } + sort.Slice(markers, func(i, j int) bool { return cmpPriority(markers, i, j) }) + sort.Slice(itemsMarkers, func(i, j int) bool { return cmpPriority(itemsMarkers, i, j) }) + + for _, schemaMarker := range markers { + if err := schemaMarker.SchemaMarker.ApplyToSchema(props); err != nil { + ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node)) + } + } + + for _, schemaMarker := range itemsMarkers { + if props.Type != "array" || props.Items == nil || props.Items.Schema == nil { + err := fmt.Errorf("must apply %s to an array value, found %s", schemaMarker.Name, props.Type) + ctx.pkg.AddError(loader.ErrFromNode(err, node)) + } else { + itemsSchema := props.Items.Schema + if err := schemaMarker.SchemaMarker.ApplyToSchema(itemsSchema); err != nil { + ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node)) + } + } + } +} + +// typeToSchema creates a schema for the given AST type. +func typeToSchema(ctx *schemaContext, rawType ast.Expr) *apiext.JSONSchemaProps { + var props *apiext.JSONSchemaProps + switch expr := rawType.(type) { + case *ast.Ident: + props = localNamedToSchema(ctx, expr) + case *ast.SelectorExpr: + props = namedToSchema(ctx, expr) + case *ast.ArrayType: + props = arrayToSchema(ctx, expr) + case *ast.MapType: + props = mapToSchema(ctx, expr) + case *ast.StarExpr: + props = typeToSchema(ctx, expr.X) + case *ast.StructType: + props = structToSchema(ctx, expr) + default: + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unsupported AST kind %T", expr), rawType)) + // NB(directxman12): we explicitly don't handle interfaces + return &apiext.JSONSchemaProps{} + } + + props.Description = ctx.info.Doc + + applyMarkers(ctx, ctx.info.Markers, props, rawType) + + return props +} + +// qualifiedName constructs a JSONSchema-safe qualified name for a type +// (`` or `~0`, where `` +// is the package path with `/` replaced by `~1`, according to JSONPointer +// escapes). +func qualifiedName(pkgName, typeName string) string { + if pkgName != "" { + return strings.ReplaceAll(pkgName, "/", "~1") + "~0" + typeName + } + return typeName +} + +// TypeRefLink creates a definition link for the given type and package. +func TypeRefLink(pkgName, typeName string) string { + return defPrefix + qualifiedName(pkgName, typeName) +} + +// localNamedToSchema creates a schema (ref) for a *potentially* local type reference +// (could be external from a dot-import). +func localNamedToSchema(ctx *schemaContext, ident *ast.Ident) *apiext.JSONSchemaProps { + typeInfo := ctx.pkg.TypesInfo.TypeOf(ident) + if typeInfo == types.Typ[types.Invalid] { + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %s", ident.Name), ident)) + return &apiext.JSONSchemaProps{} + } + // This reproduces the behavior we had pre gotypesalias=1 (needed if this + // project is compiled with default settings and Go >= 1.23). + if aliasInfo, isAlias := typeInfo.(*types.Alias); isAlias { + typeInfo = aliasInfo.Rhs() + } + if basicInfo, isBasic := typeInfo.(*types.Basic); isBasic { + typ, fmt, err := builtinToType(basicInfo, ctx.allowDangerousTypes) + if err != nil { + ctx.pkg.AddError(loader.ErrFromNode(err, ident)) + } + // Check for type aliasing to a basic type for gotypesalias=0. See more + // in documentation https://pkg.go.dev/go/types#Alias: + // > For gotypesalias=1, alias declarations produce an Alias type. + // > Otherwise, the alias information is only in the type name, which + // > points directly to the actual (aliased) type. + if basicInfo.Name() != ident.Name { + ctx.requestSchema("", ident.Name) + link := TypeRefLink("", ident.Name) + return &apiext.JSONSchemaProps{ + Type: typ, + Format: fmt, + Ref: &link, + } + } + return &apiext.JSONSchemaProps{ + Type: typ, + Format: fmt, + } + } + // NB(directxman12): if there are dot imports, this might be an external reference, + // so use typechecking info to get the actual object + typeNameInfo := typeInfo.(interface{ Obj() *types.TypeName }).Obj() + pkg := typeNameInfo.Pkg() + pkgPath := loader.NonVendorPath(pkg.Path()) + if pkg == ctx.pkg.Types { + pkgPath = "" + } + ctx.requestSchema(pkgPath, typeNameInfo.Name()) + link := TypeRefLink(pkgPath, typeNameInfo.Name()) + return &apiext.JSONSchemaProps{ + Ref: &link, + } +} + +// namedSchema creates a schema (ref) for an explicitly external type reference. +func namedToSchema(ctx *schemaContext, named *ast.SelectorExpr) *apiext.JSONSchemaProps { + typeInfoRaw := ctx.pkg.TypesInfo.TypeOf(named) + if typeInfoRaw == types.Typ[types.Invalid] { + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %v.%s", named.X, named.Sel.Name), named)) + return &apiext.JSONSchemaProps{} + } + typeInfo := typeInfoRaw.(interface{ Obj() *types.TypeName }) + typeNameInfo := typeInfo.Obj() + nonVendorPath := loader.NonVendorPath(typeNameInfo.Pkg().Path()) + ctx.requestSchema(nonVendorPath, typeNameInfo.Name()) + link := TypeRefLink(nonVendorPath, typeNameInfo.Name()) + return &apiext.JSONSchemaProps{ + Ref: &link, + } + // NB(directxman12): we special-case things like resource.Quantity during the "collapse" phase. +} + +// arrayToSchema creates a schema for the items of the given array, dealing appropriately +// with the special `[]byte` type (according to OpenAPI standards). +func arrayToSchema(ctx *schemaContext, array *ast.ArrayType) *apiext.JSONSchemaProps { + eltType := ctx.pkg.TypesInfo.TypeOf(array.Elt) + if eltType == byteType && array.Len == nil { + // byte slices are represented as base64-encoded strings + // (the format is defined in OpenAPI v3, but not JSON Schema) + return &apiext.JSONSchemaProps{ + Type: "string", + Format: "byte", + } + } + // TODO(directxman12): backwards-compat would require access to markers from base info + items := typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), array.Elt) + + return &apiext.JSONSchemaProps{ + Type: "array", + Items: &apiext.JSONSchemaPropsOrArray{Schema: items}, + } +} + +// mapToSchema creates a schema for items of the given map. Key types must eventually resolve +// to string (other types aren't allowed by JSON, and thus the kubernetes API standards). +func mapToSchema(ctx *schemaContext, mapType *ast.MapType) *apiext.JSONSchemaProps { + keyInfo := ctx.pkg.TypesInfo.TypeOf(mapType.Key) + // check that we've got a type that actually corresponds to a string + for keyInfo != nil { + switch typedKey := keyInfo.(type) { + case *types.Basic: + if typedKey.Info()&types.IsString == 0 { + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key)) + return &apiext.JSONSchemaProps{} + } + keyInfo = nil // stop iterating + case *types.Named: + keyInfo = typedKey.Underlying() + default: + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key)) + return &apiext.JSONSchemaProps{} + } + } + + // TODO(directxman12): backwards-compat would require access to markers from base info + var valSchema *apiext.JSONSchemaProps + switch val := mapType.Value.(type) { + case *ast.Ident: + valSchema = localNamedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val) + case *ast.SelectorExpr: + valSchema = namedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val) + case *ast.ArrayType: + valSchema = arrayToSchema(ctx.ForInfo(&markers.TypeInfo{}), val) + case *ast.StarExpr: + valSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), val) + case *ast.MapType: + valSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), val) + default: + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("not a supported map value type: %T", mapType.Value), mapType.Value)) + return &apiext.JSONSchemaProps{} + } + + return &apiext.JSONSchemaProps{ + Type: "object", + AdditionalProperties: &apiext.JSONSchemaPropsOrBool{ + Schema: valSchema, + Allows: true, /* set automatically by serialization, but useful for testing */ + }, + } +} + +// structToSchema creates a schema for the given struct. Embedded fields are placed in AllOf, +// and can be flattened later with a Flattener. +func structToSchema(ctx *schemaContext, structType *ast.StructType) *apiext.JSONSchemaProps { + props := &apiext.JSONSchemaProps{ + Type: "object", + Properties: make(map[string]apiext.JSONSchemaProps), + } + + if ctx.info.RawSpec.Type != structType { + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered non-top-level struct (possibly embedded), those aren't allowed"), structType)) + return props + } + + for _, field := range ctx.info.Fields { + // Skip if the field is not an inline field, ignoreUnexportedFields is true, and the field is not exported + if field.Name != "" && ctx.ignoreUnexportedFields && !ast.IsExported(field.Name) { + continue + } + + jsonTag, hasTag := field.Tag.Lookup("json") + if !hasTag { + // if the field doesn't have a JSON tag, it doesn't belong in output (and shouldn't exist in a serialized type) + ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered struct field %q without JSON tag in type %q", field.Name, ctx.info.Name), field.RawField)) + continue + } + jsonOpts := strings.Split(jsonTag, ",") + if len(jsonOpts) == 1 && jsonOpts[0] == "-" { + // skipped fields have the tag "-" (note that "-," means the field is named "-") + continue + } + + inline := false + omitEmpty := false + for _, opt := range jsonOpts[1:] { + switch opt { + case "inline": + inline = true + case "omitempty": + omitEmpty = true + } + } + fieldName := jsonOpts[0] + inline = inline || fieldName == "" // anonymous fields are inline fields in YAML/JSON + + // if no default required mode is set, default to required + defaultMode := "required" + if ctx.PackageMarkers.Get("kubebuilder:validation:Optional") != nil { + defaultMode = "optional" + } + + switch { + case field.Markers.Get("kubebuilder:validation:Optional") != nil: + // explicitly optional - kubebuilder + case field.Markers.Get("kubebuilder:validation:Required") != nil: + // explicitly required - kubebuilder + props.Required = append(props.Required, fieldName) + case field.Markers.Get("optional") != nil: + // explicitly optional - kubernetes + case field.Markers.Get("required") != nil: + // explicitly required - kubernetes + props.Required = append(props.Required, fieldName) + + // if this package isn't set to optional default... + case defaultMode == "required": + // ...everything that's not inline / omitempty is required + if !inline && !omitEmpty { + props.Required = append(props.Required, fieldName) + } + + // if this package isn't set to required default... + case defaultMode == "optional": + // implicitly optional + } + + var propSchema *apiext.JSONSchemaProps + if field.Markers.Get(crdmarkers.SchemalessName) != nil { + propSchema = &apiext.JSONSchemaProps{} + } else { + propSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), field.RawField.Type) + } + propSchema.Description = field.Doc + + applyMarkers(ctx, field.Markers, propSchema, field.RawField) + + if inline { + props.AllOf = append(props.AllOf, *propSchema) + continue + } + + props.Properties[fieldName] = *propSchema + } + + return props +} + +// builtinToType converts builtin basic types to their equivalent JSON schema form. +// It *only* handles types allowed by the kubernetes API standards. Floats are not +// allowed unless allowDangerousTypes is true +func builtinToType(basic *types.Basic, allowDangerousTypes bool) (typ string, format string, err error) { + // NB(directxman12): formats from OpenAPI v3 are slightly different than those defined + // in JSONSchema. This'll use the OpenAPI v3 ones, since they're useful for bounding our + // non-string types. + basicInfo := basic.Info() + switch { + case basicInfo&types.IsBoolean != 0: + typ = "boolean" + case basicInfo&types.IsString != 0: + typ = "string" + case basicInfo&types.IsInteger != 0: + typ = "integer" + case basicInfo&types.IsFloat != 0: + if allowDangerousTypes { + typ = "number" + } else { + return "", "", errors.New("found float, the usage of which is highly discouraged, as support for them varies across languages. Please consider serializing your float as string instead. If you are really sure you want to use them, re-run with crd:allowDangerousTypes=true") + } + default: + return "", "", fmt.Errorf("unsupported type %q", basic.String()) + } + + switch basic.Kind() { + case types.Int32, types.Uint32: + format = "int32" + case types.Int64, types.Uint64: + format = "int64" + } + + return typ, format, nil +} + +// Open coded go/types representation of encoding/json.Marshaller +var jsonMarshaler = types.NewInterfaceType([]*types.Func{ + types.NewFunc(token.NoPos, nil, "MarshalJSON", + types.NewSignatureType(nil, nil, nil, nil, + types.NewTuple( + types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Universe.Lookup("byte").Type())), + types.NewVar(token.NoPos, nil, "", types.Universe.Lookup("error").Type())), false)), +}, nil).Complete() + +// Open coded go/types representation of encoding.TextMarshaler +var textMarshaler = types.NewInterfaceType([]*types.Func{ + types.NewFunc(token.NoPos, nil, "MarshalText", + types.NewSignatureType(nil, nil, nil, nil, + types.NewTuple( + types.NewVar(token.NoPos, nil, "text", types.NewSlice(types.Universe.Lookup("byte").Type())), + types.NewVar(token.NoPos, nil, "err", types.Universe.Lookup("error").Type())), false)), +}, nil).Complete() + +func implements(typ types.Type, iface *types.Interface) bool { + return types.Implements(typ, iface) || types.Implements(types.NewPointer(typ), iface) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go new file mode 100644 index 000000000..2604d739b --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go @@ -0,0 +1,131 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package crd + +import ( + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" +) + +// SchemaVisitor walks the nodes of a schema. +type SchemaVisitor interface { + // Visit is called for each schema node. If it returns a visitor, + // the visitor will be called on each direct child node, and then + // this visitor will be called again with `nil` to indicate that + // all children have been visited. If a nil visitor is returned, + // children are not visited. + // + // It is *NOT* safe to save references to the given schema. + // Make deepcopies if you need to keep things around beyond + // the lifetime of the call. + Visit(schema *apiext.JSONSchemaProps) SchemaVisitor +} + +// EditSchema walks the given schema using the given visitor. Actual +// pointers to each schema node are passed to the visitor, so any changes +// made by the visitor will be reflected to the passed-in schema. +func EditSchema(schema *apiext.JSONSchemaProps, visitor SchemaVisitor) { + walker := schemaWalker{visitor: visitor} + walker.walkSchema(schema) +} + +// schemaWalker knows how to walk the schema, saving modifications +// made by the given visitor. +type schemaWalker struct { + visitor SchemaVisitor +} + +// walkSchema walks the given schema, saving modifications made by the visitor +// (this is as simple as passing a pointer in most cases, but special care +// needs to be taken to persist with maps). It also visits referenced +// schemata, dealing with circular references appropriately. The returned +// visitor will be used to visit all "children" of the current schema, followed +// by a nil schema with the returned visitor to mark completion. If a nil visitor +// is returned, traversal will no continue into the children of the current schema. +func (w schemaWalker) walkSchema(schema *apiext.JSONSchemaProps) { + // Walk a potential chain of schema references, keeping track of seen + // references to avoid circular references + subVisitor := w.visitor + seenRefs := map[string]bool{} + if schema.Ref != nil { + seenRefs[*schema.Ref] = true + } + for { + subVisitor = subVisitor.Visit(schema) + if subVisitor == nil { + return + } + // mark completion of the visitor + defer subVisitor.Visit(nil) + + // Break if schema is not a reference or a cycle is detected + if schema.Ref == nil || len(*schema.Ref) == 0 || seenRefs[*schema.Ref] { + break + } + seenRefs[*schema.Ref] = true + } + + // walk sub-schemata + subWalker := schemaWalker{visitor: subVisitor} + if schema.Items != nil { + subWalker.walkPtr(schema.Items.Schema) + subWalker.walkSlice(schema.Items.JSONSchemas) + } + subWalker.walkSlice(schema.AllOf) + subWalker.walkSlice(schema.OneOf) + subWalker.walkSlice(schema.AnyOf) + subWalker.walkPtr(schema.Not) + subWalker.walkMap(schema.Properties) + if schema.AdditionalProperties != nil { + subWalker.walkPtr(schema.AdditionalProperties.Schema) + } + subWalker.walkMap(schema.PatternProperties) + for name, dep := range schema.Dependencies { + subWalker.walkPtr(dep.Schema) + schema.Dependencies[name] = dep + } + if schema.AdditionalItems != nil { + subWalker.walkPtr(schema.AdditionalItems.Schema) + } + subWalker.walkMap(schema.Definitions) +} + +// walkMap walks over values of the given map, saving changes to them. +func (w schemaWalker) walkMap(defs map[string]apiext.JSONSchemaProps) { + for name, def := range defs { + // this is iter var reference is because we immediately preseve it below + //nolint:gosec + w.walkSchema(&def) + // make sure the edits actually go through since we can't + // take a reference to the value in the map + defs[name] = def + } +} + +// walkSlice walks over items of the given slice. +func (w schemaWalker) walkSlice(defs []apiext.JSONSchemaProps) { + for i := range defs { + w.walkSchema(&defs[i]) + } +} + +// walkPtr walks over the contents of the given pointer, if it's not nil. +func (w schemaWalker) walkPtr(def *apiext.JSONSchemaProps) { + if def == nil { + return + } + w.walkSchema(def) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go new file mode 100644 index 000000000..e4cbe3f73 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go @@ -0,0 +1,176 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package crd + +import ( + "fmt" + "sort" + "strings" + + "github.com/gobuffalo/flect" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// SpecMarker is a marker that knows how to apply itself to a particular +// version in a CRD Spec. +type SpecMarker interface { + // ApplyToCRD applies this marker to the given CRD, in the given version + // within that CRD. It's called after everything else in the CRD is populated. + ApplyToCRD(crd *apiext.CustomResourceDefinitionSpec, version string) error +} + +// Marker is a marker that knows how to apply itself to a particular +// version in a CRD. +type Marker interface { + // ApplyToCRD applies this marker to the given CRD, in the given version + // within that CRD. It's called after everything else in the CRD is populated. + ApplyToCRD(crd *apiext.CustomResourceDefinition, version string) error +} + +// NeedCRDFor requests the full CRD for the given group-kind. It requires +// that the packages containing the Go structs for that CRD have already +// been loaded with NeedPackage. +func (p *Parser) NeedCRDFor(groupKind schema.GroupKind, maxDescLen *int) { + p.init() + + if _, exists := p.CustomResourceDefinitions[groupKind]; exists { + return + } + + var packages []*loader.Package + for pkg, gv := range p.GroupVersions { + if gv.Group != groupKind.Group { + continue + } + packages = append(packages, pkg) + } + + defaultPlural := strings.ToLower(flect.Pluralize(groupKind.Kind)) + crd := apiext.CustomResourceDefinition{ + TypeMeta: metav1.TypeMeta{ + APIVersion: apiext.SchemeGroupVersion.String(), + Kind: "CustomResourceDefinition", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: defaultPlural + "." + groupKind.Group, + }, + Spec: apiext.CustomResourceDefinitionSpec{ + Group: groupKind.Group, + Names: apiext.CustomResourceDefinitionNames{ + Kind: groupKind.Kind, + ListKind: groupKind.Kind + "List", + Plural: defaultPlural, + Singular: strings.ToLower(groupKind.Kind), + }, + Scope: apiext.NamespaceScoped, + }, + } + + for _, pkg := range packages { + typeIdent := TypeIdent{Package: pkg, Name: groupKind.Kind} + typeInfo := p.Types[typeIdent] + if typeInfo == nil { + continue + } + p.NeedFlattenedSchemaFor(typeIdent) + fullSchema := p.FlattenedSchemata[typeIdent] + fullSchema = *fullSchema.DeepCopy() // don't mutate the cache (we might be truncating description, etc) + if maxDescLen != nil { + TruncateDescription(&fullSchema, *maxDescLen) + } + ver := apiext.CustomResourceDefinitionVersion{ + Name: p.GroupVersions[pkg].Version, + Served: true, + Schema: &apiext.CustomResourceValidation{ + OpenAPIV3Schema: &fullSchema, // fine to take a reference since we deepcopy above + }, + } + crd.Spec.Versions = append(crd.Spec.Versions, ver) + } + + // markers are applied *after* initial generation of objects + for _, pkg := range packages { + typeIdent := TypeIdent{Package: pkg, Name: groupKind.Kind} + typeInfo := p.Types[typeIdent] + if typeInfo == nil { + continue + } + ver := p.GroupVersions[pkg].Version + + for _, markerVals := range typeInfo.Markers { + for _, val := range markerVals { + if specMarker, isSpecMarker := val.(SpecMarker); isSpecMarker { + if err := specMarker.ApplyToCRD(&crd.Spec, ver); err != nil { + pkg.AddError(loader.ErrFromNode(err /* an okay guess */, typeInfo.RawSpec)) + } + } else if crdMarker, isCRDMarker := val.(Marker); isCRDMarker { + if err := crdMarker.ApplyToCRD(&crd, ver); err != nil { + pkg.AddError(loader.ErrFromNode(err /* an okay guess */, typeInfo.RawSpec)) + } + } + } + } + } + + // fix the name if the plural was changed (this is the form the name *has* to take, so no harm in changing it). + crd.Name = crd.Spec.Names.Plural + "." + groupKind.Group + + // nothing to actually write + if len(crd.Spec.Versions) == 0 { + return + } + + // it is necessary to make sure the order of CRD versions in crd.Spec.Versions is stable and explicitly set crd.Spec.Version. + // Otherwise, crd.Spec.Version may point to different CRD versions across different runs. + sort.Slice(crd.Spec.Versions, func(i, j int) bool { return crd.Spec.Versions[i].Name < crd.Spec.Versions[j].Name }) + + // make sure we have *a* storage version + // (default it if we only have one, otherwise, bail) + if len(crd.Spec.Versions) == 1 { + crd.Spec.Versions[0].Storage = true + } + + hasStorage := false + for _, ver := range crd.Spec.Versions { + if ver.Storage { + hasStorage = true + break + } + } + if !hasStorage { + // just add the error to the first relevant package for this CRD, + // since there's no specific error location + packages[0].AddError(fmt.Errorf("CRD for %s has no storage version", groupKind)) + } + + served := false + for _, ver := range crd.Spec.Versions { + if ver.Served { + served = true + break + } + } + if !served { + // just add the error to the first relevant package for this CRD, + // since there's no specific error location + packages[0].AddError(fmt.Errorf("CRD for %s with version(s) %v does not serve any version", groupKind, crd.Spec.Versions)) + } + + p.CustomResourceDefinitions[groupKind] = crd +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/zz_generated.markerhelp.go new file mode 100644 index 000000000..14d7a5cb6 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/zz_generated.markerhelp.go @@ -0,0 +1,69 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package crd + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "generates CustomResourceDefinition objects.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "IgnoreUnexportedFields": { + Summary: "indicates that we should skip unexported fields.", + Details: "Left unspecified, the default is false.", + }, + "AllowDangerousTypes": { + Summary: "allows types which are usually omitted from CRD generation", + Details: "because they are not recommended.\n\nCurrently the following additional types are allowed when this is true:\nfloat32\nfloat64\n\nLeft unspecified, the default is false", + }, + "MaxDescLen": { + Summary: "specifies the maximum description length for fields in CRD's OpenAPI schema.", + Details: "0 indicates drop the description for all fields completely.\nn indicates limit the description to at most n characters and truncate the description to\nclosest sentence boundary if it exceeds n characters.", + }, + "CRDVersions": { + Summary: "specifies the target API versions of the CRD type itself to", + Details: "generate. Defaults to v1.\n\nCurrently, the only supported value is v1.\n\nThe first version listed will be assumed to be the \"default\" version and\nwill not get a version suffix in the output filename.\n\nYou'll need to use \"v1\" to get support for features like defaulting,\nalong with an API server that supports it (Kubernetes 1.16+).", + }, + "GenerateEmbeddedObjectMeta": { + Summary: "specifies if any embedded ObjectMeta in the CRD should be generated", + Details: "", + }, + "HeaderFile": { + Summary: "specifies the header text (e.g. license) to prepend to generated files.", + Details: "", + }, + "Year": { + Summary: "specifies the year to substitute for \" YEAR\" in the header file.", + Details: "", + }, + "DeprecatedV1beta1CompatibilityPreserveUnknownFields": { + Summary: "indicates whether", + Details: "or not we should turn off field pruning for this resource.\n\nSpecifies spec.preserveUnknownFields value that is false and omitted by default.\nThis value can only be specified for CustomResourceDefinitions that were created with\n`apiextensions.k8s.io/v1beta1`.\n\nThe field can be set for compatibility reasons, although strongly discouraged, resource\nauthors should move to a structural OpenAPI schema instead.\n\nSee https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning\nfor more information about field pruning and v1beta1 resources compatibility.", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/doc.go new file mode 100644 index 000000000..f4200f2fc --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/doc.go @@ -0,0 +1,23 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package deepcopy generates DeepCopy, DeepCopyInto, and DeepCopyObject +// implementations for types. +// +// It's ported from k8s.io/code-generator's / k8s.io/gengo's deepcopy-gen, +// but it's scoped specifically to runtime.Object and skips support for +// deepcopying interfaces, which aren't handled in CRDs anyway. +package deepcopy diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go new file mode 100644 index 000000000..a85cc8577 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go @@ -0,0 +1,303 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package deepcopy + +import ( + "bytes" + "fmt" + "go/ast" + "go/format" + "io" + "sort" + "strings" + + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// NB(directxman12): markers.LoadRoots ignores autogenerated code via a build tag +// so any time we check for existing deepcopy functions, we only seen manually written ones. + +const ( + runtimeObjPath = "k8s.io/apimachinery/pkg/runtime.Object" +) + +var ( + enablePkgMarker = markers.Must(markers.MakeDefinition("kubebuilder:object:generate", markers.DescribesPackage, false)) + enableTypeMarker = markers.Must(markers.MakeDefinition("kubebuilder:object:generate", markers.DescribesType, false)) + isObjectMarker = markers.Must(markers.MakeDefinition("kubebuilder:object:root", markers.DescribesType, false)) + + legacyEnablePkgMarker = markers.Must(markers.MakeDefinition("k8s:deepcopy-gen", markers.DescribesPackage, markers.RawArguments(nil))) + legacyEnableTypeMarker = markers.Must(markers.MakeDefinition("k8s:deepcopy-gen", markers.DescribesType, markers.RawArguments(nil))) + legacyIsObjectMarker = markers.Must(markers.MakeDefinition("k8s:deepcopy-gen:interfaces", markers.DescribesType, "")) +) + +// +controllertools:marker:generateHelp + +// Generator generates code containing DeepCopy, DeepCopyInto, and +// DeepCopyObject method implementations. +type Generator struct { + // HeaderFile specifies the header text (e.g. license) to prepend to generated files. + HeaderFile string `marker:",optional"` + // Year specifies the year to substitute for " YEAR" in the header file. + Year string `marker:",optional"` +} + +func (Generator) CheckFilter() loader.NodeFilter { + return func(node ast.Node) bool { + // ignore interfaces + _, isIface := node.(*ast.InterfaceType) + return !isIface + } +} + +func (Generator) RegisterMarkers(into *markers.Registry) error { + if err := markers.RegisterAll(into, + enablePkgMarker, legacyEnablePkgMarker, enableTypeMarker, + legacyEnableTypeMarker, isObjectMarker, legacyIsObjectMarker); err != nil { + return err + } + into.AddHelp(enablePkgMarker, + markers.SimpleHelp("object", "enables or disables object interface & deepcopy implementation generation for this package")) + into.AddHelp( + enableTypeMarker, markers.SimpleHelp("object", "overrides enabling or disabling deepcopy generation for this type")) + into.AddHelp(isObjectMarker, + markers.SimpleHelp("object", "enables object interface implementation generation for this type")) + + into.AddHelp(legacyEnablePkgMarker, + markers.DeprecatedHelp(enablePkgMarker.Name, "object", "enables or disables object interface & deepcopy implementation generation for this package")) + into.AddHelp(legacyEnableTypeMarker, + markers.DeprecatedHelp(enableTypeMarker.Name, "object", "overrides enabling or disabling deepcopy generation for this type")) + into.AddHelp(legacyIsObjectMarker, + markers.DeprecatedHelp(isObjectMarker.Name, "object", "enables object interface implementation generation for this type")) + return nil +} + +func enabledOnPackage(col *markers.Collector, pkg *loader.Package) (bool, error) { + pkgMarkers, err := markers.PackageMarkers(col, pkg) + if err != nil { + return false, err + } + pkgMarker := pkgMarkers.Get(enablePkgMarker.Name) + if pkgMarker != nil { + return pkgMarker.(bool), nil + } + legacyMarker := pkgMarkers.Get(legacyEnablePkgMarker.Name) + if legacyMarker != nil { + legacyMarkerVal := string(legacyMarker.(markers.RawArguments)) + firstArg := strings.Split(legacyMarkerVal, ",")[0] + return firstArg == "package", nil + } + + return false, nil +} + +func enabledOnType(allTypes bool, info *markers.TypeInfo) bool { + if typeMarker := info.Markers.Get(enableTypeMarker.Name); typeMarker != nil { + return typeMarker.(bool) + } + legacyMarker := info.Markers.Get(legacyEnableTypeMarker.Name) + if legacyMarker != nil { + legacyMarkerVal := string(legacyMarker.(markers.RawArguments)) + return legacyMarkerVal == "true" + } + return allTypes || genObjectInterface(info) +} + +func genObjectInterface(info *markers.TypeInfo) bool { + objectEnabled := info.Markers.Get(isObjectMarker.Name) + if objectEnabled != nil { + return objectEnabled.(bool) + } + + for _, legacyEnabled := range info.Markers[legacyIsObjectMarker.Name] { + if legacyEnabled == runtimeObjPath { + return true + } + } + return false +} + +func (d Generator) Generate(ctx *genall.GenerationContext) error { + var headerText string + + if d.HeaderFile != "" { + headerBytes, err := ctx.ReadFile(d.HeaderFile) + if err != nil { + return err + } + headerText = string(headerBytes) + } + headerText = strings.ReplaceAll(headerText, " YEAR", " "+d.Year) + + objGenCtx := ObjectGenCtx{ + Collector: ctx.Collector, + Checker: ctx.Checker, + HeaderText: headerText, + } + + for _, root := range ctx.Roots { + outContents := objGenCtx.generateForPackage(root) + if outContents == nil { + continue + } + + writeOut(ctx, root, outContents) + } + + return nil +} + +// ObjectGenCtx contains the common info for generating deepcopy implementations. +// It mostly exists so that generating for a package can be easily tested without +// requiring a full set of output rules, etc. +type ObjectGenCtx struct { + Collector *markers.Collector + Checker *loader.TypeChecker + HeaderText string +} + +// writeHeader writes out the build tag, package declaration, and imports +func writeHeader(pkg *loader.Package, out io.Writer, packageName string, imports *importsList, headerText string) { + // NB(directxman12): blank line after build tags to distinguish them from comments + _, err := fmt.Fprintf(out, `//go:build !ignore_autogenerated + +%[3]s + +// Code generated by controller-gen. DO NOT EDIT. + +package %[1]s + +import ( +%[2]s +) + +`, packageName, strings.Join(imports.ImportSpecs(), "\n"), headerText) + if err != nil { + pkg.AddError(err) + } +} + +// generateForPackage generates DeepCopy and runtime.Object implementations for +// types in the given package, writing the formatted result to given writer. +// May return nil if source could not be generated. +func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) []byte { + allTypes, err := enabledOnPackage(ctx.Collector, root) + if err != nil { + root.AddError(err) + return nil + } + + ctx.Checker.Check(root) + + root.NeedTypesInfo() + + byType := make(map[string][]byte) + imports := &importsList{ + byPath: make(map[string]string), + byAlias: make(map[string]string), + pkg: root, + } + // avoid confusing aliases by "reserving" the root package's name as an alias + imports.byAlias[root.Name] = "" + + if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) { + outContent := new(bytes.Buffer) + + // copy when nabled for all types and not disabled, or enabled + // specifically on this type + if !enabledOnType(allTypes, info) { + return + } + + // avoid copying non-exported types, etc + if !shouldBeCopied(root, info) { + return + } + + copyCtx := ©MethodMaker{ + pkg: root, + importsList: imports, + codeWriter: &codeWriter{out: outContent}, + } + + copyCtx.GenerateMethodsFor(root, info) + + outBytes := outContent.Bytes() + if len(outBytes) > 0 { + byType[info.Name] = outBytes + } + }); err != nil { + root.AddError(err) + return nil + } + + if len(byType) == 0 { + return nil + } + + outContent := new(bytes.Buffer) + writeHeader(root, outContent, root.Name, imports, ctx.HeaderText) + writeMethods(root, outContent, byType) + + outBytes := outContent.Bytes() + formattedBytes, err := format.Source(outBytes) + if err != nil { + root.AddError(err) + // we still write the invalid source to disk to figure out what went wrong + } else { + outBytes = formattedBytes + } + + return outBytes +} + +// writeMethods writes each method to the file, sorted by type name. +func writeMethods(pkg *loader.Package, out io.Writer, byType map[string][]byte) { + sortedNames := make([]string, 0, len(byType)) + for name := range byType { + sortedNames = append(sortedNames, name) + } + sort.Strings(sortedNames) + + for _, name := range sortedNames { + _, err := out.Write(byType[name]) + if err != nil { + pkg.AddError(err) + } + } +} + +// writeFormatted outputs the given code, after gofmt-ing it. If we couldn't gofmt, +// we write the unformatted code for debugging purposes. +func writeOut(ctx *genall.GenerationContext, root *loader.Package, outBytes []byte) { + outputFile, err := ctx.Open(root, "zz_generated.deepcopy.go") + if err != nil { + root.AddError(err) + return + } + defer outputFile.Close() + n, err := outputFile.Write(outBytes) + if err != nil { + root.AddError(err) + return + } + if n < len(outBytes) { + root.AddError(io.ErrShortWrite) + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go new file mode 100644 index 000000000..b7bed1d1e --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go @@ -0,0 +1,839 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package deepcopy + +import ( + "fmt" + "go/ast" + "go/types" + "io" + "path" + "strings" + "unicode" + "unicode/utf8" + + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// NB(directxman12): This code is a bit of a byzantine mess. +// I've tried to clean it up a bit from the original in deepcopy-gen, +// but parts remain a bit convoluted. Exercise caution when changing. +// It's perhaps a tad over-commented now, but better safe than sorry. +// It also seriously needs auditing for sanity -- there's parts where we +// copy the original deepcopy-gen's output just to be safe, but some of that +// could be simplified away if we're careful. + +// codeWriter assists in writing out Go code lines and blocks to a writer. +type codeWriter struct { + out io.Writer +} + +// Line writes a single line. +func (c *codeWriter) Line(line string) { + fmt.Fprintln(c.out, line) +} + +// Linef writes a single line with formatting (as per fmt.Sprintf). +func (c *codeWriter) Linef(line string, args ...interface{}) { + fmt.Fprintf(c.out, line+"\n", args...) +} + +// If writes an if statement with the given setup/condition clause, executing +// the given function to write the contents of the block. +func (c *codeWriter) If(setup string, block func()) { + c.Linef("if %s {", setup) + block() + c.Line("}") +} + +// If writes if and else statements with the given setup/condition clause, executing +// the given functions to write the contents of the blocks. +func (c *codeWriter) IfElse(setup string, ifBlock func(), elseBlock func()) { + c.Linef("if %s {", setup) + ifBlock() + c.Line("} else {") + elseBlock() + c.Line("}") +} + +// For writes an for statement with the given setup/condition clause, executing +// the given function to write the contents of the block. +func (c *codeWriter) For(setup string, block func()) { + c.Linef("for %s {", setup) + block() + c.Line("}") +} + +// importsList keeps track of required imports, automatically assigning aliases +// to import statement. +type importsList struct { + byPath map[string]string + byAlias map[string]string + + pkg *loader.Package +} + +// NeedImport marks that the given package is needed in the list of imports, +// returning the ident (import alias) that should be used to reference the package. +func (l *importsList) NeedImport(importPath string) string { + // we get an actual path from Package, which might include venddored + // packages if running on a package in vendor. + if ind := strings.LastIndex(importPath, "/vendor/"); ind != -1 { + importPath = importPath[ind+8: /* len("/vendor/") */] + } + + // check to see if we've already assigned an alias, and just return that. + alias, exists := l.byPath[importPath] + if exists { + return alias + } + + // otherwise, calculate an import alias by joining path parts till we get something unique + restPath, nextWord := path.Split(importPath) + + for otherPath, exists := "", true; exists && otherPath != importPath; otherPath, exists = l.byAlias[alias] { + if restPath == "" { + // do something else to disambiguate if we're run out of parts and + // still have duplicates, somehow + alias += "x" + } + + // can't have a first digit, per Go identifier rules, so just skip them + for firstRune, runeLen := utf8.DecodeRuneInString(nextWord); unicode.IsDigit(firstRune); firstRune, runeLen = utf8.DecodeRuneInString(nextWord) { + nextWord = nextWord[runeLen:] + } + + // make a valid identifier by replacing "bad" characters with underscores + nextWord = strings.Map(func(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { + return r + } + return '_' + }, nextWord) + + alias = nextWord + alias + if len(restPath) > 0 { + restPath, nextWord = path.Split(restPath[:len(restPath)-1] /* chop off final slash */) + } + } + + l.byPath[importPath] = alias + l.byAlias[alias] = importPath + return alias +} + +// ImportSpecs returns a string form of each import spec +// (i.e. `alias "path/to/import"). Aliases are only present +// when they don't match the package name. +func (l *importsList) ImportSpecs() []string { + res := make([]string, 0, len(l.byPath)) + for importPath, alias := range l.byPath { + pkg := l.pkg.Imports()[importPath] + if pkg != nil && pkg.Name == alias { + // don't print if alias is the same as package name + // (we've already taken care of duplicates). + res = append(res, fmt.Sprintf("%q", importPath)) + } else { + res = append(res, fmt.Sprintf("%s %q", alias, importPath)) + } + } + return res +} + +// namingInfo holds package and syntax for referencing a field, type, +// etc. It's used to allow lazily marking import usage. +// You should generally retrieve the syntax using Syntax. +type namingInfo struct { + // typeInfo is the type being named. + typeInfo types.Type + nameOverride string +} + +// Syntax calculates the code representation of the given type or name, +// and marks that is used (potentially marking an import as used). +func (n *namingInfo) Syntax(basePkg *loader.Package, imports *importsList) string { + if n.nameOverride != "" { + return n.nameOverride + } + + // NB(directxman12): typeInfo.String gets us most of the way there, + // but fails (for us) on named imports, since it uses the full package path. + var typeName *types.TypeName + switch typeInfo := n.typeInfo.(type) { + case *types.Alias: + typeName = typeInfo.Obj() + case *types.Named: + typeName = typeInfo.Obj() + case *types.Basic: + return typeInfo.String() + case *types.Pointer: + return "*" + (&namingInfo{typeInfo: typeInfo.Elem()}).Syntax(basePkg, imports) + case *types.Slice: + return "[]" + (&namingInfo{typeInfo: typeInfo.Elem()}).Syntax(basePkg, imports) + case *types.Map: + return fmt.Sprintf( + "map[%s]%s", + (&namingInfo{typeInfo: typeInfo.Key()}).Syntax(basePkg, imports), + (&namingInfo{typeInfo: typeInfo.Elem()}).Syntax(basePkg, imports)) + default: + basePkg.AddError(fmt.Errorf("name requested for invalid type: %s", typeInfo)) + return typeInfo.String() + } + + // register that we need an import for this type, + // so we can get the appropriate alias to use. + otherPkg := typeName.Pkg() + if otherPkg == basePkg.Types { + // local import + return typeName.Name() + } + alias := imports.NeedImport(loader.NonVendorPath(otherPkg.Path())) + return alias + "." + typeName.Name() +} + +// copyMethodMakers makes DeepCopy (and related) methods for Go types, +// writing them to its codeWriter. +type copyMethodMaker struct { + pkg *loader.Package + *importsList + *codeWriter +} + +// GenerateMethodsFor makes DeepCopy, DeepCopyInto, and DeepCopyObject methods +// for the given type, when appropriate +func (c *copyMethodMaker) GenerateMethodsFor(root *loader.Package, info *markers.TypeInfo) { + typeInfo := root.TypesInfo.TypeOf(info.RawSpec.Name) + if typeInfo == types.Typ[types.Invalid] { + root.AddError(loader.ErrFromNode(fmt.Errorf("unknown type: %s", info.Name), info.RawSpec)) + } + + // figure out if we need to use a pointer receiver -- most types get a pointer receiver, + // except those that are aliases to types that are already pass-by-reference (pointers, + // interfaces. maps, slices). + ptrReceiver := usePtrReceiver(typeInfo) + + hasManualDeepCopyInto := hasDeepCopyIntoMethod(root, typeInfo) + hasManualDeepCopy, deepCopyOnPtr := hasDeepCopyMethod(root, typeInfo) + + // only generate each method if it hasn't been implemented. + if !hasManualDeepCopyInto { + c.Line("// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.") + if ptrReceiver { + c.Linef("func (in *%s) DeepCopyInto(out *%s) {", info.Name, info.Name) + } else { + c.Linef("func (in %s) DeepCopyInto(out *%s) {", info.Name, info.Name) + c.Line("{in := &in") // add an extra block so that we can redefine `in` without type issues + } + + // just wrap the existing deepcopy if present + if hasManualDeepCopy { + if deepCopyOnPtr { + c.Line("clone := in.DeepCopy()") + c.Line("*out = *clone") + } else { + c.Line("*out = in.DeepCopy()") + } + } else { + c.genDeepCopyIntoBlock(&namingInfo{nameOverride: info.Name}, typeInfo) + } + + if !ptrReceiver { + c.Line("}") // close our extra "in redefinition" block + } + c.Line("}") + } + + if !hasManualDeepCopy { + // these are both straightforward, so we just template them out. + if ptrReceiver { + c.Linef(ptrDeepCopy, info.Name) + } else { + c.Linef(bareDeepCopy, info.Name) + } + + // maybe also generate DeepCopyObject, if asked. + if genObjectInterface(info) { + // we always need runtime.Object for DeepCopyObject + runtimeAlias := c.NeedImport("k8s.io/apimachinery/pkg/runtime") + if ptrReceiver { + c.Linef(ptrDeepCopyObj, info.Name, runtimeAlias) + } else { + c.Linef(bareDeepCopyObj, info.Name, runtimeAlias) + } + } + } +} + +// genDeepCopyBody generates a DeepCopyInto block for the given type. The +// block is *not* wrapped in curly braces. +func (c *copyMethodMaker) genDeepCopyIntoBlock(actualName *namingInfo, typeInfo types.Type) { + // we calculate *how* we should copy mostly based on the "eventual" type of + // a given type (i.e. the type that results from following all aliases) + last := eventualUnderlyingType(typeInfo) + + // we might hit a type that has a manual deepcopy method written on non-root types + // (this case is handled for root types in GenerateMethodFor). + // In that case (when we're not dealing with a pointer, since those need special handling + // to match 1-to-1 with k8s deepcopy-gen), just use that. + if _, isPtr := last.(*types.Pointer); !isPtr && hasAnyDeepCopyMethod(c.pkg, typeInfo) { + c.Line("*out = in.DeepCopy()") + return + } + + switch last := last.(type) { + case *types.Basic: + switch last.Kind() { + case types.Invalid, types.UnsafePointer: + c.pkg.AddError(fmt.Errorf("invalid type: %s", last)) + default: + // basic types themselves can be "shallow" copied, so all we need + // to do is check if our *actual* type (not the underlying one) has + // a custom method implemented. + if hasMethod, _ := hasDeepCopyMethod(c.pkg, typeInfo); hasMethod { + c.Line("*out = in.DeepCopy()") + } + c.Line("*out = *in") + } + case *types.Map: + c.genMapDeepCopy(actualName, last) + case *types.Slice: + c.genSliceDeepCopy(actualName, last) + case *types.Struct: + c.genStructDeepCopy(actualName, last) + case *types.Pointer: + c.genPointerDeepCopy(actualName, last) + case *types.Named: + // handled via the above loop, should never happen + c.pkg.AddError(fmt.Errorf("interface type %s encountered directly, invalid condition", last)) + default: + c.pkg.AddError(fmt.Errorf("invalid type: %s", last)) + } +} + +// genMapDeepCopy generates DeepCopy code for the given named type whose eventual +// type is the given map type. +func (c *copyMethodMaker) genMapDeepCopy(actualName *namingInfo, mapType *types.Map) { + // maps *must* have shallow-copiable types, since we just iterate + // through the keys, only trying to deepcopy the values. + if !fineToShallowCopy(mapType.Key()) { + c.pkg.AddError(fmt.Errorf("invalid map key type: %s", mapType.Key())) + return + } + + // make our actual type (not the underlying one)... + c.Linef("*out = make(%[1]s, len(*in))", actualName.Syntax(c.pkg, c.importsList)) + + // ...and copy each element appropriately + c.For("key, val := range *in", func() { + // check if we have manually written methods, + // in which case we'll just try and use those + hasDeepCopy, copyOnPtr := hasDeepCopyMethod(c.pkg, mapType.Elem()) + hasDeepCopyInto := hasDeepCopyIntoMethod(c.pkg, mapType.Elem()) + switch { + case hasDeepCopyInto || hasDeepCopy: + // use the manually-written methods + _, fieldIsPtr := mapType.Elem().(*types.Pointer) // is "out" actually a pointer + inIsPtr := resultWillBePointer(mapType.Elem(), hasDeepCopy, copyOnPtr) // does copying "in" produce a pointer + if hasDeepCopy { + // If we're calling DeepCopy, check if it's receiver needs a pointer + inIsPtr = copyOnPtr + } + switch { + case inIsPtr == fieldIsPtr: + c.Line("(*out)[key] = val.DeepCopy()") + case fieldIsPtr: + c.Line("{") // use a block because we use `x` as a temporary + c.Line("x := val.DeepCopy()") + c.Line("(*out)[key] = &x") + c.Line("}") + default: + c.Line("(*out)[key] = *val.DeepCopy()") + } + case fineToShallowCopy(mapType.Elem()): + // just shallow copy types for which it's safe to do so + c.Line("(*out)[key] = val") + default: + // otherwise, we've got some kind-specific actions, + // based on the element's eventual type. + + underlyingElem := eventualUnderlyingType(mapType.Elem()) + + // if it passes by reference, let the main switch handle it + if passesByReference(underlyingElem) { + c.Linef("var outVal %[1]s", (&namingInfo{typeInfo: underlyingElem}).Syntax(c.pkg, c.importsList)) + c.IfElse("val == nil", func() { + c.Line("(*out)[key] = nil") + }, func() { + c.Line("inVal := (*in)[key]") + c.Line("in, out := &inVal, &outVal") + c.genDeepCopyIntoBlock(&namingInfo{typeInfo: mapType.Elem()}, mapType.Elem()) + }) + c.Line("(*out)[key] = outVal") + + return + } + + // otherwise... + switch underlyingElem := underlyingElem.(type) { + case *types.Struct: + // structs will have deepcopy generated for them, so use that + c.Line("(*out)[key] = *val.DeepCopy()") + default: + c.pkg.AddError(fmt.Errorf("invalid map value type: %s", underlyingElem)) + return + } + } + }) +} + +// genSliceDeepCopy generates DeepCopy code for the given named type whose +// underlying type is the given slice. +func (c *copyMethodMaker) genSliceDeepCopy(actualName *namingInfo, sliceType *types.Slice) { + underlyingElem := eventualUnderlyingType(sliceType.Elem()) + + // make the actual type (not the underlying) + c.Linef("*out = make(%[1]s, len(*in))", actualName.Syntax(c.pkg, c.importsList)) + + // check if we need to do anything special, or just copy each element appropriately + switch { + case hasAnyDeepCopyMethod(c.pkg, sliceType.Elem()): + // just use deepcopy if it's present (deepcopyinto will be filled in by our code) + c.For("i := range *in", func() { + c.Line("(*in)[i].DeepCopyInto(&(*out)[i])") + }) + case fineToShallowCopy(underlyingElem): + // shallow copy if ok + c.Line("copy(*out, *in)") + default: + // copy each element appropriately + c.For("i := range *in", func() { + // fall back to normal code for reference types or those with custom logic + if passesByReference(underlyingElem) || hasAnyDeepCopyMethod(c.pkg, sliceType.Elem()) { + c.If("(*in)[i] != nil", func() { + c.Line("in, out := &(*in)[i], &(*out)[i]") + c.genDeepCopyIntoBlock(&namingInfo{typeInfo: sliceType.Elem()}, sliceType.Elem()) + }) + return + } + + switch underlyingElem.(type) { + case *types.Struct: + // structs will always have deepcopy + c.Linef("(*in)[i].DeepCopyInto(&(*out)[i])") + default: + c.pkg.AddError(fmt.Errorf("invalid slice element type: %s", underlyingElem)) + } + }) + } +} + +// genStructDeepCopy generates DeepCopy code for the given named type whose +// underlying type is the given struct. +func (c *copyMethodMaker) genStructDeepCopy(_ *namingInfo, structType *types.Struct) { + c.Line("*out = *in") + + for i := 0; i < structType.NumFields(); i++ { + field := structType.Field(i) + + // if we have a manual deepcopy, use that + hasDeepCopy, copyOnPtr := hasDeepCopyMethod(c.pkg, field.Type()) + hasDeepCopyInto := hasDeepCopyIntoMethod(c.pkg, field.Type()) + if hasDeepCopyInto || hasDeepCopy { + // NB(directxman12): yes, I know this is kind-of weird that we + // have all this special-casing here, but it's nice for testing + // purposes to be 1-to-1 with deepcopy-gen, which does all sorts of + // stuff like this (I'm pretty sure I found some codepaths that + // never execute there, because they're pretty clearly invalid + // syntax). + + _, fieldIsPtr := field.Type().(*types.Pointer) + inIsPtr := resultWillBePointer(field.Type(), hasDeepCopy, copyOnPtr) + if fieldIsPtr { + // we'll need a if block to check for nilness + // we'll let genDeepCopyIntoBlock handle the details, we just needed the setup + c.If(fmt.Sprintf("in.%s != nil", field.Name()), func() { + c.Linef("in, out := &in.%[1]s, &out.%[1]s", field.Name()) + c.genDeepCopyIntoBlock(&namingInfo{typeInfo: field.Type()}, field.Type()) + }) + } else { + // special-case for compatibility with deepcopy-gen + if inIsPtr == fieldIsPtr { + c.Linef("out.%[1]s = in.%[1]s.DeepCopy()", field.Name()) + } else { + c.Linef("in.%[1]s.DeepCopyInto(&out.%[1]s)", field.Name()) + } + } + continue + } + + // pass-by-reference fields get delegated to the main type + underlyingField := eventualUnderlyingType(field.Type()) + if passesByReference(underlyingField) { + c.If(fmt.Sprintf("in.%s != nil", field.Name()), func() { + c.Linef("in, out := &in.%[1]s, &out.%[1]s", field.Name()) + c.genDeepCopyIntoBlock(&namingInfo{typeInfo: field.Type()}, field.Type()) + }) + continue + } + + // otherwise... + switch underlyingField := underlyingField.(type) { + case *types.Basic: + switch underlyingField.Kind() { + case types.Invalid, types.UnsafePointer: + c.pkg.AddError(loader.ErrFromNode(fmt.Errorf("invalid field type: %s", underlyingField), field)) + return + default: + // nothing to do, initial assignment copied this + } + case *types.Struct: + if fineToShallowCopy(field.Type()) { + c.Linef("out.%[1]s = in.%[1]s", field.Name()) + } else { + c.Linef("in.%[1]s.DeepCopyInto(&out.%[1]s)", field.Name()) + } + default: + c.pkg.AddError(loader.ErrFromNode(fmt.Errorf("invalid field type: %s", underlyingField), field)) + return + } + } +} + +// genPointerDeepCopy generates DeepCopy code for the given named type whose +// underlying type is the given struct. +func (c *copyMethodMaker) genPointerDeepCopy(_ *namingInfo, pointerType *types.Pointer) { + underlyingElem := eventualUnderlyingType(pointerType.Elem()) + + // if we have a manually written deepcopy, just use that + hasDeepCopy, copyOnPtr := hasDeepCopyMethod(c.pkg, pointerType.Elem()) + hasDeepCopyInto := hasDeepCopyIntoMethod(c.pkg, pointerType.Elem()) + if hasDeepCopyInto || hasDeepCopy { + outNeedsPtr := resultWillBePointer(pointerType.Elem(), hasDeepCopy, copyOnPtr) + if hasDeepCopy { + outNeedsPtr = copyOnPtr + } + if outNeedsPtr { + c.Line("*out = (*in).DeepCopy()") + } else { + c.Line("x := (*in).DeepCopy()") + c.Line("*out = &x") + } + return + } + + // shallow-copiable types are pretty easy + if fineToShallowCopy(underlyingElem) { + c.Linef("*out = new(%[1]s)", (&namingInfo{typeInfo: pointerType.Elem()}).Syntax(c.pkg, c.importsList)) + c.Line("**out = **in") + return + } + + // pass-by-reference types get delegated to the main switch + if passesByReference(underlyingElem) { + c.Linef("*out = new(%s)", (&namingInfo{typeInfo: underlyingElem}).Syntax(c.pkg, c.importsList)) + c.If("**in != nil", func() { + c.Line("in, out := *in, *out") + c.genDeepCopyIntoBlock(&namingInfo{typeInfo: underlyingElem}, eventualUnderlyingType(underlyingElem)) + }) + return + } + + // otherwise... + switch underlyingElem := underlyingElem.(type) { + case *types.Struct: + c.Linef("*out = new(%[1]s)", (&namingInfo{typeInfo: pointerType.Elem()}).Syntax(c.pkg, c.importsList)) + c.Line("(*in).DeepCopyInto(*out)") + default: + c.pkg.AddError(fmt.Errorf("invalid pointer element type: %s", underlyingElem)) + return + } +} + +// usePtrReceiver checks if we need a pointer receiver on methods for the given type +// Pass-by-reference types don't get pointer receivers. +func usePtrReceiver(typeInfo types.Type) bool { + switch typeInfo.(type) { + case *types.Pointer: + return false + case *types.Map: + return false + case *types.Slice: + return false + case *types.Named: + return usePtrReceiver(typeInfo.Underlying()) + default: + return true + } +} + +func resultWillBePointer(typeInfo types.Type, hasDeepCopy, deepCopyOnPtr bool) bool { + // if we have a manual deepcopy, we can just check what that returns + if hasDeepCopy { + return deepCopyOnPtr + } + + // otherwise, we'll need to check its type + switch typeInfo := typeInfo.(type) { + case *types.Pointer: + // NB(directxman12): we don't have to worry about the elem having a deepcopy, + // since hasManualDeepCopy would've caught that. + + // we'll be calling on the elem, so check that + return resultWillBePointer(typeInfo.Elem(), false, false) + case *types.Map: + return false + case *types.Slice: + return false + case *types.Named: + return resultWillBePointer(typeInfo.Underlying(), false, false) + default: + return true + } +} + +// shouldBeCopied checks if we're supposed to make deepcopy methods the given type. +// +// This is the case if it's exported *and* either: +// - has a partial manual DeepCopy implementation (in which case we fill in the rest) +// - aliases to a non-basic type eventually +// - is a struct +func shouldBeCopied(pkg *loader.Package, info *markers.TypeInfo) bool { + if !ast.IsExported(info.Name) { + return false + } + + typeInfo := pkg.TypesInfo.TypeOf(info.RawSpec.Name) + if typeInfo == types.Typ[types.Invalid] { + pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type: %s", info.Name), info.RawSpec)) + return false + } + + lastType := typeInfo + if _, isNamed := typeInfo.(*types.Named); isNamed { + // according to gengo, everything named is an alias, except for an alias to a pointer, + // which is just a pointer, afaict. Just roll with it. + if asPtr, isPtr := typeInfo.(*types.Named).Underlying().(*types.Pointer); isPtr { + lastType = asPtr + typeInfo = asPtr + } + + // if it has a manual deepcopy or deepcopyinto, we're fine + if hasAnyDeepCopyMethod(pkg, typeInfo) { + return true + } + + for underlyingType := typeInfo.Underlying(); underlyingType != lastType; lastType, underlyingType = underlyingType, underlyingType.Underlying() { + // if it has a manual deepcopy or deepcopyinto, we're fine + if hasAnyDeepCopyMethod(pkg, underlyingType) { + return true + } + + // aliases to other things besides basics need copy methods + // (basics can be straight-up shallow-copied) + if _, isBasic := underlyingType.(*types.Basic); !isBasic { + return true + } + } + } + + // structs are the only thing that's not a basic that's copiable by default + _, isStruct := lastType.(*types.Struct) + return isStruct +} + +// hasDeepCopyMethod checks if this type has a manual DeepCopy method and if +// the method has a pointer receiver. +func hasDeepCopyMethod(pkg *loader.Package, typeInfo types.Type) (bool, bool) { + deepCopyMethod, ind, _ := types.LookupFieldOrMethod(typeInfo, true /* check pointers too */, pkg.Types, "DeepCopy") + if len(ind) != 1 { + // ignore embedded methods + return false, false + } + if deepCopyMethod == nil { + return false, false + } + + methodSig := deepCopyMethod.Type().(*types.Signature) + if methodSig.Params() != nil && methodSig.Params().Len() != 0 { + return false, false + } + if methodSig.Results() == nil || methodSig.Results().Len() != 1 { + return false, false + } + + recvAsPtr, recvIsPtr := methodSig.Recv().Type().(*types.Pointer) + if recvIsPtr { + // NB(directxman12): the pointer type returned here isn't comparable even though they + // have the same underlying type, for some reason (probably that + // LookupFieldOrMethod calls types.NewPointer for us), so check the + // underlying values. + + resultPtr, resultIsPtr := methodSig.Results().At(0).Type().(*types.Pointer) + if !resultIsPtr { + // pointer vs non-pointer are different types + return false, false + } + + if recvAsPtr.Elem() != resultPtr.Elem() { + return false, false + } + } else if methodSig.Results().At(0).Type() != methodSig.Recv().Type() { + return false, false + } + + return true, recvIsPtr +} + +// hasDeepCopyIntoMethod checks if this type has a manual DeepCopyInto method. +func hasDeepCopyIntoMethod(pkg *loader.Package, typeInfo types.Type) bool { + deepCopyMethod, ind, _ := types.LookupFieldOrMethod(typeInfo, true /* check pointers too */, pkg.Types, "DeepCopyInto") + if len(ind) != 1 { + // ignore embedded methods + return false + } + if deepCopyMethod == nil { + return false + } + + methodSig := deepCopyMethod.Type().(*types.Signature) + if methodSig.Params() == nil || methodSig.Params().Len() != 1 { + return false + } + paramPtr, isPtr := methodSig.Params().At(0).Type().(*types.Pointer) + if !isPtr { + return false + } + if methodSig.Results() != nil && methodSig.Results().Len() != 0 { + return false + } + + if recvPtr, recvIsPtr := methodSig.Recv().Type().(*types.Pointer); recvIsPtr { + // NB(directxman12): the pointer type returned here isn't comparable even though they + // have the same underlying type, for some reason (probably that + // LookupFieldOrMethod calls types.NewPointer for us), so check the + // underlying values. + return paramPtr.Elem() == recvPtr.Elem() + } + return methodSig.Recv().Type() == paramPtr.Elem() +} + +// hasAnyDeepCopyMethod checks if the given method has DeepCopy or DeepCopyInto +// (either of which implies the other will exist eventually). +func hasAnyDeepCopyMethod(pkg *loader.Package, typeInfo types.Type) bool { + hasDeepCopy, _ := hasDeepCopyMethod(pkg, typeInfo) + return hasDeepCopy || hasDeepCopyIntoMethod(pkg, typeInfo) +} + +// eventualUnderlyingType gets the "final" type in a sequence of named aliases. +// It's effectively a shortcut for calling Underlying in a loop. +func eventualUnderlyingType(typeInfo types.Type) types.Type { + for { + underlying := typeInfo.Underlying() + if underlying == typeInfo { + break + } + typeInfo = underlying + } + return typeInfo +} + +// fineToShallowCopy checks if a shallow-copying a type is equivalent to deepcopy-ing it. +func fineToShallowCopy(typeInfo types.Type) bool { + switch typeInfo := typeInfo.(type) { + case *types.Basic: + // basic types (int, string, etc) are always fine to shallow-copy, + // except for Invalid and UnsafePointer, which can't be copied at all. + switch typeInfo.Kind() { + case types.Invalid, types.UnsafePointer: + return false + default: + return true + } + case *types.Named: + // aliases are fine to shallow-copy as long as they resolve to a shallow-copyable type + return fineToShallowCopy(typeInfo.Underlying()) + case *types.Struct: + // structs are fine to shallow-copy if they have all shallow-copyable fields + for i := 0; i < typeInfo.NumFields(); i++ { + field := typeInfo.Field(i) + if !fineToShallowCopy(field.Type()) { + return false + } + } + return true + default: + return false + } +} + +// passesByReference checks if the given type passesByReference +// (except for interfaces, which are handled separately). +func passesByReference(typeInfo types.Type) bool { + switch typeInfo.(type) { + case *types.Slice: + return true + case *types.Map: + return true + case *types.Pointer: + return true + default: + return false + } +} + +var ( + // ptrDeepCopy is a DeepCopy for a type with an existing DeepCopyInto and a pointer receiver. + ptrDeepCopy = ` +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new %[1]s. +func (in *%[1]s) DeepCopy() *%[1]s { + if in == nil { return nil } + out := new(%[1]s) + in.DeepCopyInto(out) + return out +} +` + + // ptrDeepCopy is a DeepCopy for a type with an existing DeepCopyInto and a non-pointer receiver. + bareDeepCopy = ` +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new %[1]s. +func (in %[1]s) DeepCopy() %[1]s { + if in == nil { return nil } + out := new(%[1]s) + in.DeepCopyInto(out) + return *out +} +` + + // ptrDeepCopy is a DeepCopyObject for a type with an existing DeepCopyInto and a pointer receiver. + ptrDeepCopyObj = ` +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *%[1]s) DeepCopyObject() %[2]s.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} +` + // ptrDeepCopy is a DeepCopyObject for a type with an existing DeepCopyInto and a non-pointer receiver. + bareDeepCopyObj = ` +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in %[1]s) DeepCopyObject() %[2]s.Object { + return in.DeepCopy() +} +` +) diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/zz_generated.markerhelp.go new file mode 100644 index 000000000..081c06551 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/zz_generated.markerhelp.go @@ -0,0 +1,45 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package deepcopy + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "generates code containing DeepCopy, DeepCopyInto, and", + Details: "DeepCopyObject method implementations.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "HeaderFile": { + Summary: "specifies the header text (e.g. license) to prepend to generated files.", + Details: "", + }, + "Year": { + Summary: "specifies the year to substitute for \" YEAR\" in the header file.", + Details: "", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/doc.go new file mode 100644 index 000000000..af67402e6 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/doc.go @@ -0,0 +1,58 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package genall defines entrypoints for generation tools to hook into and +// share the same set of parsing, typechecking, and marker information. +// +// # Generators +// +// Each Generator knows how to register its markers into a central Registry, +// and then how to generate output using a Collector and some root packages. +// Each generator can be considered to be the output type of a marker, for easy +// command line parsing. +// +// # Output and Input +// +// Generators output artifacts via an OutputRule. OutputRules know how to +// write output for different package-associated (code) files, as well as +// config files. Each OutputRule should also be considered to be the output +// type as a marker, for easy command-line parsing. +// +// OutputRules groups together an OutputRule per generator, plus a default +// output rule for any not explicitly specified. +// +// OutputRules are defined for stdout, file writing, and sending to /dev/null +// (useful for doing "type-checking" without actually saving the results). +// +// InputRule defines custom input loading, but its shared across all +// Generators. There's currently only a filesystem implementation. +// +// # Runtime and Context +// +// Runtime maps together Generators, and constructs "contexts" which provide +// the common collector and roots, plus the output rule for that generator, and +// a handle for reading files (like boilerplate headers). +// +// It will run all associated generators, printing errors and automatically +// skipping type-checking errors (since those are commonly caused by the +// partial type-checking of loader.TypeChecker). +// +// # Options +// +// The FromOptions (and associated helpers) function makes it easy to use generators +// and output rules as markers that can be parsed from the command line, producing +// a registry from command line args. +package genall diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go new file mode 100644 index 000000000..b6f37409b --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go @@ -0,0 +1,283 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package genall + +import ( + "encoding/json" + "fmt" + "io" + "os" + + "golang.org/x/tools/go/packages" + rawyaml "gopkg.in/yaml.v2" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// Generators are a list of Generators. +// NB(directxman12): this is a pointer so that we can uniquely identify each +// instance of a generator, even if it's not hashable. Different *instances* +// of a generator are treated differently. +type Generators []*Generator + +// RegisterMarkers registers all markers defined by each of the Generators in +// this list into the given registry. +func (g Generators) RegisterMarkers(reg *markers.Registry) error { + for _, gen := range g { + if err := (*gen).RegisterMarkers(reg); err != nil { + return err + } + } + return nil +} + +// CheckFilters returns the set of NodeFilters for all Generators that +// implement NeedsTypeChecking. +func (g Generators) CheckFilters() []loader.NodeFilter { + var filters []loader.NodeFilter + for _, gen := range g { + withFilter, needsChecking := (*gen).(NeedsTypeChecking) + if !needsChecking { + continue + } + filters = append(filters, withFilter.CheckFilter()) + } + return filters +} + +// NeedsTypeChecking indicates that a particular generator needs & has opinions +// on typechecking. If this is not implemented, a generator will be given a +// context with a nil typechecker. +type NeedsTypeChecking interface { + // CheckFilter indicates the loader.NodeFilter (if any) that should be used + // to prune out unused types/packages when type-checking (nodes for which + // the filter returns true are considered "interesting"). This filter acts + // as a baseline -- all types the pass through this filter will be checked, + // but more than that may also be checked due to other generators' filters. + CheckFilter() loader.NodeFilter +} + +// Generator knows how to register some set of markers, and then produce +// output artifacts based on loaded code containing those markers, +// sharing common loaded data. +type Generator interface { + // RegisterMarkers registers all markers needed by this Generator + // into the given registry. + RegisterMarkers(into *markers.Registry) error + // Generate generates artifacts produced by this marker. + // It's called *after* RegisterMarkers has been called. + Generate(*GenerationContext) error +} + +// HasHelp is some Generator, OutputRule, etc with a help method. +type HasHelp interface { + // Help returns help for this generator. + Help() *markers.DefinitionHelp +} + +// Runtime collects generators, loaded program data (Collector, root Packages), +// and I/O rules, running them together. +type Runtime struct { + // Generators are the Generators to be run by this Runtime. + Generators Generators + // GenerationContext is the base generation context that's copied + // to produce the context for each Generator. + GenerationContext + // OutputRules defines how to output artifacts for each Generator. + OutputRules OutputRules + // ErrorWriter defines where to write error messages. + ErrorWriter io.Writer +} + +// GenerationContext defines the common information needed for each Generator +// to run. +type GenerationContext struct { + // Collector is the shared marker collector. + Collector *markers.Collector + // Roots are the base packages to be processed. + Roots []*loader.Package + // Checker is the shared partial type-checker. + Checker *loader.TypeChecker + // OutputRule describes how to output artifacts. + OutputRule + // InputRule describes how to load associated boilerplate artifacts. + // It should *not* be used to load source files. + InputRule +} + +// WriteYAMLOptions implements the Options Pattern for WriteYAML. +type WriteYAMLOptions struct { + transform func(obj map[string]interface{}) error +} + +// WithTransform applies a transformation to objects just before writing them. +func WithTransform(transform func(obj map[string]interface{}) error) *WriteYAMLOptions { + return &WriteYAMLOptions{ + transform: transform, + } +} + +// TransformRemoveCreationTimestamp ensures we do not write the metadata.creationTimestamp field. +func TransformRemoveCreationTimestamp(obj map[string]interface{}) error { + metadata := obj["metadata"].(map[interface{}]interface{}) + delete(metadata, "creationTimestamp") + return nil +} + +// WriteYAML writes the given objects out, serialized as YAML, using the +// context's OutputRule. Objects are written as separate documents, separated +// from each other by `---` (as per the YAML spec). +func (g GenerationContext) WriteYAML(itemPath, headerText string, objs []interface{}, options ...*WriteYAMLOptions) error { + out, err := g.Open(nil, itemPath) + if err != nil { + return err + } + defer out.Close() + + _, err = out.Write([]byte(headerText)) + if err != nil { + return err + } + + for _, obj := range objs { + yamlContent, err := yamlMarshal(obj, options...) + if err != nil { + return err + } + n, err := out.Write(append([]byte("---\n"), yamlContent...)) + if err != nil { + return err + } + if n < len(yamlContent) { + return io.ErrShortWrite + } + } + + return nil +} + +// yamlMarshal is based on sigs.k8s.io/yaml.Marshal, but allows for transforming the final data before writing. +func yamlMarshal(o interface{}, options ...*WriteYAMLOptions) ([]byte, error) { + j, err := json.Marshal(o) + if err != nil { + return nil, fmt.Errorf("error marshaling into JSON: %w", err) + } + + return yamlJSONToYAMLWithFilter(j, options...) +} + +// yamlJSONToYAMLWithFilter is based on sigs.k8s.io/yaml.JSONToYAML, but allows for transforming the final data before writing. +func yamlJSONToYAMLWithFilter(j []byte, options ...*WriteYAMLOptions) ([]byte, error) { + // Convert the JSON to an object. + var jsonObj map[string]interface{} + // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the + // Go JSON library doesn't try to pick the right number type (int, float, + // etc.) when unmarshalling to interface{}, it just picks float64 + // universally. go-yaml does go through the effort of picking the right + // number type, so we can preserve number type throughout this process. + if err := rawyaml.Unmarshal(j, &jsonObj); err != nil { + return nil, err + } + + for _, option := range options { + if option.transform != nil { + if err := option.transform(jsonObj); err != nil { + return nil, err + } + } + } + + // Marshal this object into YAML. + return rawyaml.Marshal(jsonObj) +} + +// ReadFile reads the given boilerplate artifact using the context's InputRule. +func (g GenerationContext) ReadFile(path string) ([]byte, error) { + file, err := g.OpenForRead(path) + if err != nil { + return nil, err + } + defer file.Close() + return io.ReadAll(file) +} + +// ForRoots produces a Runtime to run the given generators against the +// given packages. It outputs to /dev/null by default. +func (g Generators) ForRoots(rootPaths ...string) (*Runtime, error) { + return g.ForRootsWithConfig(&packages.Config{}, rootPaths...) +} + +func (g Generators) ForRootsWithConfig(cfg *packages.Config, rootPaths ...string) (*Runtime, error) { + roots, err := loader.LoadRootsWithConfig(cfg, rootPaths...) + if err != nil { + return nil, err + } + rt := &Runtime{ + Generators: g, + GenerationContext: GenerationContext{ + Collector: &markers.Collector{ + Registry: &markers.Registry{}, + }, + Roots: roots, + InputRule: InputFromFileSystem, + Checker: &loader.TypeChecker{ + NodeFilters: g.CheckFilters(), + }, + }, + OutputRules: OutputRules{Default: OutputToNothing}, + } + if err := rt.Generators.RegisterMarkers(rt.Collector.Registry); err != nil { + return nil, err + } + return rt, nil +} + +// Run runs the Generators in this Runtime against its packages, printing +// errors (except type errors, which common result from using TypeChecker with +// filters), returning true if errors were found. +func (r *Runtime) Run() bool { + // TODO(directxman12): we could make this parallel, + // but we'd need to ensure all underlying machinery is threadsafe + + if r.ErrorWriter == nil { + r.ErrorWriter = os.Stderr + } + if len(r.Generators) == 0 { + fmt.Fprintln(r.ErrorWriter, "no generators to run") + return true + } + + hadErrs := false + for _, gen := range r.Generators { + ctx := r.GenerationContext // make a shallow copy + ctx.OutputRule = r.OutputRules.ForGenerator(gen) + + // don't pass a typechecker to generators that don't provide a filter + // to avoid accidents + if _, needsChecking := (*gen).(NeedsTypeChecking); !needsChecking { + ctx.Checker = nil + } + + if err := (*gen).Generate(&ctx); err != nil { + fmt.Fprintln(r.ErrorWriter, err) + hadErrs = true + } + } + + // skip TypeErrors -- they're probably just from partial typechecking in crd-gen + return loader.PrintErrors(r.Roots, packages.TypeError) || hadErrs +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/doc.go new file mode 100644 index 000000000..d84d1798b --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/doc.go @@ -0,0 +1,23 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package help contains utilities for actually writing out marker help. +// +// Namely, it contains a series of structs (and helpers for producing them) +// that represent a merged view of marker definition and help that can be used +// for consumption by the pretty subpackage (for terminal help) or serialized +// as JSON (e.g. for generating HTML help). +package help diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/doc.go new file mode 100644 index 000000000..bc99e9ba9 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/doc.go @@ -0,0 +1,30 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package pretty contains utilities for formatting terminal help output, +// and a use of those to display marker help. +// +// # Terminal Output +// +// The Span interface and Table struct allow you to construct tables with +// colored formatting, without causing ANSI formatting characters to mess up width +// calculations. +// +// # Marker Help +// +// The MarkersSummary prints a summary table for marker help, while the MarkersDetails +// prints out more detailed information, with explainations of the individual marker fields. +package pretty diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/help.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/help.go new file mode 100644 index 000000000..87ea87db7 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/help.go @@ -0,0 +1,171 @@ +package pretty + +import ( + "fmt" + "io" + + "github.com/fatih/color" + "sigs.k8s.io/controller-tools/pkg/genall/help" +) + +var ( + headingStyle = Decoration(*color.New(color.Bold, color.Underline)) + markerNameStyle = Decoration(*color.New(color.Bold)) + fieldSummaryStyle = Decoration(*color.New(color.FgGreen, color.Italic)) + markerTargetStyle = Decoration(*color.New(color.Faint)) + fieldDetailStyle = Decoration(*color.New(color.Italic, color.FgGreen)) + deprecatedStyle = Decoration(*color.New(color.CrossedOut)) +) + +// MarkersSummary returns a condensed summary of help for the given markers. +func MarkersSummary(groupName string, markers []help.MarkerDoc) Span { + out := new(SpanWriter) + + out.Print(Text("\n")) + out.Print(headingStyle.Containing(Text(groupName))) + out.Print(Text("\n\n")) + + table := &Table{Sizing: &TableCalculator{Padding: 2}} + for _, marker := range markers { + table.StartRow() + table.Column(MarkerSyntaxHelp(marker)) + table.Column(markerTargetStyle.Containing(Text(marker.Target))) + + summary := new(SpanWriter) + if marker.DeprecatedInFavorOf != nil && len(*marker.DeprecatedInFavorOf) > 0 { + summary.Print(markerNameStyle.Containing(Text("(use "))) + summary.Print(markerNameStyle.Containing(Text(*marker.DeprecatedInFavorOf))) + summary.Print(markerNameStyle.Containing(Text(") "))) + } + summary.Print(Text(marker.Summary)) + table.Column(summary) + + table.EndRow() + } + out.Print(table) + + out.Print(Text("\n")) + + return out +} + +// MarkersDetails returns detailed help for the given markers, including detailed field help. +func MarkersDetails(fullDetail bool, groupName string, markers []help.MarkerDoc) Span { + out := new(SpanWriter) + + out.Print(Line(headingStyle.Containing(Text(groupName)))) + out.Print(Newlines(2)) + + for _, marker := range markers { + out.Print(Line(markerName(marker))) + out.Print(Text(" ")) + out.Print(markerTargetStyle.Containing(Text(marker.Target))) + + summary := new(SpanWriter) + if marker.DeprecatedInFavorOf != nil && len(*marker.DeprecatedInFavorOf) > 0 { + summary.Print(markerNameStyle.Containing(Text("(use "))) + summary.Print(markerNameStyle.Containing(Text(*marker.DeprecatedInFavorOf))) + summary.Print(markerNameStyle.Containing(Text(") "))) + } + summary.Print(Text(marker.Summary)) + + if !marker.AnonymousField() { + out.Print(Indented(1, Line(summary))) + if len(marker.Details) > 0 && fullDetail { + out.Print(Indented(1, Line(Text(marker.Details)))) + } + } + + switch { + case marker.AnonymousField(): + out.Print(Indented(1, Line(fieldDetailStyle.Containing(FieldSyntaxHelp(marker.Fields[0]))))) + out.Print(Text(" ")) + out.Print(summary) + if len(marker.Details) > 0 && fullDetail { + out.Print(Indented(2, Line(Text(marker.Details)))) + } + out.Print(Newlines(1)) + case !marker.Empty(): + out.Print(Newlines(1)) + if fullDetail { + for _, arg := range marker.Fields { + out.Print(Indented(1, Line(fieldDetailStyle.Containing(FieldSyntaxHelp(arg))))) + out.Print(Indented(2, Line(Text(arg.Summary)))) + if len(arg.Details) > 0 && fullDetail { + out.Print(Indented(2, Line(Text(arg.Details)))) + out.Print(Newlines(1)) + } + } + out.Print(Newlines(1)) + } else { + table := &Table{Sizing: &TableCalculator{Padding: 2}} + for _, arg := range marker.Fields { + table.StartRow() + table.Column(fieldDetailStyle.Containing(FieldSyntaxHelp(arg))) + table.Column(Text(arg.Summary)) + table.EndRow() + } + + out.Print(Indented(1, table)) + } + default: + out.Print(Newlines(1)) + } + } + + return out +} + +func FieldSyntaxHelp(arg help.FieldHelp) Span { + return fieldSyntaxHelp(arg, "") +} + +// fieldSyntaxHelp prints the syntax help for a particular marker argument. +func fieldSyntaxHelp(arg help.FieldHelp, sep string) Span { + if arg.Optional { + return FromWriter(func(out io.Writer) error { + _, err := fmt.Fprintf(out, "[%s%s=<%s>]", sep, arg.Name, arg.TypeString()) + return err + }) + } + return FromWriter(func(out io.Writer) error { + _, err := fmt.Fprintf(out, "%s%s=<%s>", sep, arg.Name, arg.TypeString()) + return err + }) +} + +// markerName returns a span containing just the appropriately-formatted marker name. +func markerName(def help.MarkerDoc) Span { + if def.DeprecatedInFavorOf != nil { + return deprecatedStyle.Containing(Text("+" + def.Name)) + } + return markerNameStyle.Containing(Text("+" + def.Name)) +} + +// MarkerSyntaxHelp assembles syntax help for a given marker. +func MarkerSyntaxHelp(def help.MarkerDoc) Span { + out := new(SpanWriter) + + out.Print(markerName(def)) + + if def.Empty() { + return out + } + + sep := ":" + if def.AnonymousField() { + sep = "" + } + + fieldStyle := fieldSummaryStyle + if def.DeprecatedInFavorOf != nil { + fieldStyle = deprecatedStyle + } + + for _, arg := range def.Fields { + out.Print(fieldStyle.Containing(fieldSyntaxHelp(arg, sep))) + sep = "," + } + + return out +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/print.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/print.go new file mode 100644 index 000000000..8d7452a0b --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/print.go @@ -0,0 +1,304 @@ +package pretty + +import ( + "bytes" + "fmt" + "io" + + "github.com/fatih/color" +) + +// NB(directxman12): this isn't particularly elegant, but it's also +// sufficiently simple as to be maintained here. Man (roff) would've +// probably worked, but it's not necessarily on Windows by default. + +// Span is a chunk of content that is writable to an output, but knows how to +// calculate its apparent visual "width" on the terminal (not to be confused +// with the raw length, which may include zero-width coloring sequences). +type Span interface { + // VisualLength reports the "width" as perceived by the user on the terminal + // (i.e. widest line, ignoring ANSI escape characters). + VisualLength() int + // WriteTo writes the full span contents to the given writer. + WriteTo(io.Writer) error +} + +// Table is a Span that writes its data in table form, with sizing controlled +// by the given table calculator. Rows are started with StartRow, followed by +// some calls to Column, followed by a call to EndRow. Once all rows are +// added, the table can be used as a Span. +type Table struct { + Sizing *TableCalculator + + cellsByRow [][]Span + colSizes []int +} + +// StartRow starts a new row. +// It must eventually be followed by EndRow. +func (t *Table) StartRow() { + t.cellsByRow = append(t.cellsByRow, []Span(nil)) +} + +// EndRow ends the currently started row. +func (t *Table) EndRow() { + lastRow := t.cellsByRow[len(t.cellsByRow)-1] + sizes := make([]int, len(lastRow)) + for i, cell := range lastRow { + sizes[i] = cell.VisualLength() + } + t.Sizing.AddRowSizes(sizes...) +} + +// Column adds the given span as a new column to the current row. +func (t *Table) Column(contents Span) { + currentRowInd := len(t.cellsByRow) - 1 + t.cellsByRow[currentRowInd] = append(t.cellsByRow[currentRowInd], contents) +} + +// SkipRow prints a span without having it contribute to the table calculation. +func (t *Table) SkipRow(contents Span) { + t.cellsByRow = append(t.cellsByRow, []Span{contents}) +} + +func (t *Table) WriteTo(out io.Writer) error { + if t.colSizes == nil { + t.colSizes = t.Sizing.ColumnWidths() + } + + for _, cells := range t.cellsByRow { + currentPosition := 0 + for colInd, cell := range cells { + colSize := t.colSizes[colInd] + diff := colSize - cell.VisualLength() + + if err := cell.WriteTo(out); err != nil { + return err + } + + if diff > 0 { + if err := writePadding(out, columnPadding, diff); err != nil { + return err + } + } + currentPosition += colSize + } + + if _, err := fmt.Fprint(out, "\n"); err != nil { + return err + } + } + + return nil +} + +func (t *Table) VisualLength() int { + if t.colSizes == nil { + t.colSizes = t.Sizing.ColumnWidths() + } + + res := 0 + for _, colSize := range t.colSizes { + res += colSize + } + return res +} + +// Text is a span that simply contains raw text. It's a good starting point. +type Text string + +func (t Text) VisualLength() int { return len(t) } +func (t Text) WriteTo(w io.Writer) error { + _, err := w.Write([]byte(t)) + return err +} + +// indented is a span that indents all lines by the given number of tabs. +type indented struct { + Amount int + Content Span +} + +func (i *indented) VisualLength() int { return i.Content.VisualLength() } +func (i *indented) WriteTo(w io.Writer) error { + var out bytes.Buffer + if err := i.Content.WriteTo(&out); err != nil { + return err + } + + lines := bytes.Split(out.Bytes(), []byte("\n")) + for lineInd, line := range lines { + if lineInd != 0 { + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + } + if len(line) == 0 { + continue + } + + if err := writePadding(w, indentPadding, i.Amount); err != nil { + return err + } + if _, err := w.Write(line); err != nil { + return err + } + } + return nil +} + +// Indented returns a span that indents all lines by the given number of tabs. +func Indented(amt int, content Span) Span { + return &indented{Amount: amt, Content: content} +} + +// fromWriter is a span that takes content from a function expecting a Writer. +type fromWriter struct { + cache []byte + cacheError error + run func(io.Writer) error +} + +func (f *fromWriter) VisualLength() int { + if f.cache == nil { + var buf bytes.Buffer + if err := f.run(&buf); err != nil { + f.cacheError = err + } + f.cache = buf.Bytes() + } + return len(f.cache) +} +func (f *fromWriter) WriteTo(w io.Writer) error { + if f.cache != nil { + if f.cacheError != nil { + return f.cacheError + } + _, err := w.Write(f.cache) + return err + } + return f.run(w) +} + +// FromWriter returns a span that takes content from a function expecting a Writer. +func FromWriter(run func(io.Writer) error) Span { + return &fromWriter{run: run} +} + +// Decoration represents a terminal decoration. +type Decoration color.Color + +// Containing returns a Span that has the given decoration applied. +func (d Decoration) Containing(contents Span) Span { + return &decorated{ + Contents: contents, + Attributes: color.Color(d), + } +} + +// decorated is a span that has some terminal decoration applied. +type decorated struct { + Contents Span + Attributes color.Color +} + +func (d *decorated) VisualLength() int { return d.Contents.VisualLength() } +func (d *decorated) WriteTo(w io.Writer) error { + oldOut := color.Output + color.Output = w + defer func() { color.Output = oldOut }() + + d.Attributes.Set() + defer color.Unset() + + return d.Contents.WriteTo(w) +} + +// SpanWriter is a span that contains multiple sub-spans. +type SpanWriter struct { + contents []Span +} + +func (m *SpanWriter) VisualLength() int { + res := 0 + for _, span := range m.contents { + res += span.VisualLength() + } + return res +} +func (m *SpanWriter) WriteTo(w io.Writer) error { + for _, span := range m.contents { + if err := span.WriteTo(w); err != nil { + return err + } + } + return nil +} + +// Print adds a new span to this SpanWriter. +func (m *SpanWriter) Print(s Span) { + m.contents = append(m.contents, s) +} + +// lines is a span that adds some newlines, optionally followed by some content. +type lines struct { + content Span + amountBefore int +} + +func (l *lines) VisualLength() int { + if l.content == nil { + return 0 + } + return l.content.VisualLength() +} +func (l *lines) WriteTo(w io.Writer) error { + if err := writePadding(w, linesPadding, l.amountBefore); err != nil { + return err + } + if l.content != nil { + if err := l.content.WriteTo(w); err != nil { + return err + } + } + return nil +} + +// Newlines returns a span just containing some newlines. +func Newlines(amt int) Span { + return &lines{amountBefore: amt} +} + +// Line returns a span that emits a newline, followed by the given content. +func Line(content Span) Span { + return &lines{amountBefore: 1, content: content} +} + +var ( + columnPadding = []byte(" ") + indentPadding = []byte("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t") + linesPadding = []byte("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") +) + +// writePadding writes out padding of the given type in the given amount to the writer. +// Each byte in the padding buffer contributes 1 to the amount -- the padding being +// a buffer is just for efficiency. +func writePadding(out io.Writer, typ []byte, amt int) error { + if amt <= len(typ) { + _, err := out.Write(typ[:amt]) + return err + } + + num := amt / len(typ) + rem := amt % len(typ) + for i := 0; i < num; i++ { + if _, err := out.Write(typ); err != nil { + return err + } + } + + if _, err := out.Write(typ[:rem]); err != nil { + return err + } + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/table.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/table.go new file mode 100644 index 000000000..c2ee9d282 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/pretty/table.go @@ -0,0 +1,64 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package pretty + +// TableCalculator calculates column widths (with optional padding) +// for a table based on the maximum required column width. +type TableCalculator struct { + cellSizesByCol [][]int + + Padding int + MaxWidth int +} + +// AddRowSizes registers a new row with cells of the given sizes. +func (c *TableCalculator) AddRowSizes(cellSizes ...int) { + if len(cellSizes) > len(c.cellSizesByCol) { + for range cellSizes[len(c.cellSizesByCol):] { + c.cellSizesByCol = append(c.cellSizesByCol, []int(nil)) + } + } + for i, size := range cellSizes { + c.cellSizesByCol[i] = append(c.cellSizesByCol[i], size) + } +} + +// ColumnWidths calculates the appropriate column sizes given the +// previously registered rows. +func (c *TableCalculator) ColumnWidths() []int { + maxColWidths := make([]int, len(c.cellSizesByCol)) + + for colInd, cellSizes := range c.cellSizesByCol { + maxValue := 0 + for _, cellSize := range cellSizes { + if maxValue < cellSize { + maxValue = cellSize + } + } + maxColWidths[colInd] = maxValue + } + + actualMaxWidth := c.MaxWidth - c.Padding + for i, width := range maxColWidths { + if actualMaxWidth > 0 && width > actualMaxWidth { + maxColWidths[i] = actualMaxWidth + } + maxColWidths[i] += c.Padding + } + + return maxColWidths +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/sort.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/sort.go new file mode 100644 index 000000000..53c923e34 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/sort.go @@ -0,0 +1,106 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package help + +import ( + "strings" + + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// SortGroup knows how to sort and group marker definitions. +type SortGroup interface { + // Less is equivalent to the Less function from sort, and is used to sort the markers. + Less(*markers.Definition, *markers.Definition) bool + // Group returns the "group" that a given marker belongs to. + Group(*markers.Definition, *markers.DefinitionHelp) string +} + +var ( + // SortByCategory sorts the markers by name and groups them by their help category. + SortByCategory = sortByCategory{} + + // SortByOption sorts by the generator that the option belongs to. + SortByOption = optionsSort{} +) + +type sortByCategory struct{} + +func (sortByCategory) Group(_ *markers.Definition, help *markers.DefinitionHelp) string { + if help == nil { + return "" + } + return help.Category +} +func (sortByCategory) Less(i, j *markers.Definition) bool { + return i.Name < j.Name +} + +type optionsSort struct{} + +func (optionsSort) Less(i, j *markers.Definition) bool { + iParts := strings.Split(i.Name, ":") + jParts := strings.Split(j.Name, ":") + + iGen := "" + iRule := "" + jGen := "" + jRule := "" + + switch len(iParts) { + case 1: + iGen = iParts[0] + // two means a default output rule, so ignore + case 2: + iRule = iParts[1] + case 3: + iGen = iParts[1] + iRule = iParts[2] + } + switch len(jParts) { + case 1: + jGen = jParts[0] + // two means a default output rule, so ignore + case 2: + jRule = jParts[1] + case 3: + jGen = jParts[1] + jRule = jParts[2] + } + + if iGen != jGen { + return iGen > jGen + } + + return iRule < jRule +} +func (optionsSort) Group(def *markers.Definition, _ *markers.DefinitionHelp) string { + parts := strings.Split(def.Name, ":") + + switch len(parts) { + case 1: + if parts[0] == "paths" { + return "generic" + } + return "generators" + case 2: + return "output rules (optionally as output::...)" + default: + return "" + // three means a marker-specific output rule, ignore + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/types.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/types.go new file mode 100644 index 000000000..be1110432 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/help/types.go @@ -0,0 +1,215 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package help + +import ( + "sort" + "strings" + + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// DetailedHelp contains both a summary and further details. +type DetailedHelp struct { + // Summary contains a one-line description. + Summary string `json:"summary"` + // Details contains further information. + Details string `json:"details,omitempty"` +} + +// Argument is the type data for a marker argument. +type Argument struct { + // Type is the data type of the argument (string, bool, int, slice, any, raw, invalid) + Type string `json:"type"` + // Optional marks this argument as optional. + Optional bool `json:"optional"` + // ItemType contains the type of the slice item, if this is a slice + ItemType *Argument `json:"itemType,omitempty"` +} + +func (a Argument) typeString(out *strings.Builder) { + if a.Type == "slice" { + out.WriteString("[]") + a.ItemType.typeString(out) + return + } + + out.WriteString(a.Type) +} + +// TypeString returns a string roughly equivalent +// (but not identical) to the underlying Go type that +// this argument would parse to. It's mainly useful +// for user-friendly formatting of this argument (e.g. +// help strings). +func (a Argument) TypeString() string { + out := &strings.Builder{} + a.typeString(out) + return out.String() +} + +// FieldHelp contains information required to print documentation for a marker field. +type FieldHelp struct { + // Name is the field name. + Name string `json:"name"` + // Argument is the type of the field. + Argument `json:",inline"` + + // DetailedHelp contains the textual help for the field. + DetailedHelp `json:",inline"` +} + +// MarkerDoc contains information required to print documentation for a marker. +type MarkerDoc struct { + // definition + + // Name is the name of the marker. + Name string `json:"name"` + // Target is the target (field, package, type) of the marker. + Target string `json:"target"` + + // help + + // DetailedHelp is the textual help for the marker. + DetailedHelp `json:",inline"` + // Category is the general "category" that this marker belongs to. + Category string `json:"category"` + // DeprecatedInFavorOf marks that this marker shouldn't be used when + // non-nil. If also non-empty, another marker should be used instead. + DeprecatedInFavorOf *string `json:"deprecatedInFavorOf,omitempty"` + // Fields is the type and help data for each field of this marker. + Fields []FieldHelp `json:"fields,omitempty"` +} + +// Empty checks if this marker has any arguments, returning true if not. +func (m MarkerDoc) Empty() bool { + return len(m.Fields) == 0 +} + +// AnonymousField chekcs if this is an single-valued marker +// (as opposed to having named fields). +func (m MarkerDoc) AnonymousField() bool { + return len(m.Fields) == 1 && m.Fields[0].Name == "" +} + +// ForArgument returns the equivalent documentation for a marker argument. +func ForArgument(argRaw markers.Argument) Argument { + res := Argument{ + Optional: argRaw.Optional, + } + + if argRaw.ItemType != nil { + itemType := ForArgument(*argRaw.ItemType) + res.ItemType = &itemType + } + + switch argRaw.Type { + case markers.IntType: + res.Type = "int" + case markers.StringType: + res.Type = "string" + case markers.BoolType: + res.Type = "bool" + case markers.AnyType: + res.Type = "any" + case markers.SliceType: + res.Type = "slice" + case markers.RawType: + res.Type = "raw" + case markers.InvalidType: + res.Type = "invalid" + } + + return res +} + +// ForDefinition returns the equivalent marker documentation for a given marker definition and spearate help. +func ForDefinition(defn *markers.Definition, maybeHelp *markers.DefinitionHelp) MarkerDoc { + var help markers.DefinitionHelp + if maybeHelp != nil { + help = *maybeHelp + } + + res := MarkerDoc{ + Name: defn.Name, + Category: help.Category, + DeprecatedInFavorOf: help.DeprecatedInFavorOf, + Target: defn.Target.String(), + DetailedHelp: DetailedHelp{Summary: help.Summary, Details: help.Details}, + } + + helpByField := help.FieldsHelp(defn) + + // TODO(directxman12): deterministic ordering + for fieldName, fieldHelpRaw := range helpByField { + fieldInfo := defn.Fields[fieldName] + fieldHelp := FieldHelp{ + Name: fieldName, + DetailedHelp: DetailedHelp{Summary: fieldHelpRaw.Summary, Details: fieldHelpRaw.Details}, + Argument: ForArgument(fieldInfo), + } + + res.Fields = append(res.Fields, fieldHelp) + } + + sort.Slice(res.Fields, func(i, j int) bool { return res.Fields[i].Name < res.Fields[j].Name }) + + return res +} + +// CategoryDoc contains help information for all markers in a Category. +type CategoryDoc struct { + Category string `json:"category"` + Markers []MarkerDoc `json:"markers"` +} + +// ByCategory returns the marker help for markers in the given +// registry, grouped and sorted according to the given method. +func ByCategory(reg *markers.Registry, sorter SortGroup) []CategoryDoc { + groupedMarkers := make(map[string][]*markers.Definition) + + for _, marker := range reg.AllDefinitions() { + group := sorter.Group(marker, reg.HelpFor(marker)) + groupedMarkers[group] = append(groupedMarkers[group], marker) + } + allGroups := make([]string, 0, len(groupedMarkers)) + for groupName := range groupedMarkers { + allGroups = append(allGroups, groupName) + } + + sort.Strings(allGroups) + + res := make([]CategoryDoc, len(allGroups)) + for i, groupName := range allGroups { + markers := groupedMarkers[groupName] + sort.Slice(markers, func(i, j int) bool { + return sorter.Less(markers[i], markers[j]) + }) + + markerDocs := make([]MarkerDoc, len(markers)) + for i, marker := range markers { + markerDocs[i] = ForDefinition(marker, reg.HelpFor(marker)) + } + + res[i] = CategoryDoc{ + Category: groupName, + Markers: markerDocs, + } + } + + return res +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/input.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/input.go new file mode 100644 index 000000000..46e191c0c --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/input.go @@ -0,0 +1,37 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package genall + +import ( + "io" + "os" +) + +// InputRule describes how to load non-code boilerplate artifacts. +// It's not used for loading code. +type InputRule interface { + // OpenForRead opens the given non-code artifact for reading. + OpenForRead(path string) (io.ReadCloser, error) +} +type inputFromFileSystem struct{} + +func (inputFromFileSystem) OpenForRead(path string) (io.ReadCloser, error) { + return os.Open(path) +} + +// InputFromFileSystem reads from the filesystem as normal. +var InputFromFileSystem = inputFromFileSystem{} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/options.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/options.go new file mode 100644 index 000000000..192235b76 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/options.go @@ -0,0 +1,201 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package genall + +import ( + "fmt" + "strings" + + "golang.org/x/tools/go/packages" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +var ( + InputPathsMarker = markers.Must(markers.MakeDefinition("paths", markers.DescribesPackage, InputPaths(nil))) +) + +// +controllertools:marker:generateHelp:category="" + +// InputPaths represents paths and go-style path patterns to use as package roots. +// +// Multiple paths can be specified using "{path1, path2, path3}". +type InputPaths []string + +// RegisterOptionsMarkers registers "mandatory" options markers for FromOptions into the given registry. +// At this point, that's just InputPaths. +func RegisterOptionsMarkers(into *markers.Registry) error { + if err := into.Register(InputPathsMarker); err != nil { + return err + } + // NB(directxman12): we make this optional so we don't have a bootstrap problem with helpgen + if helpGiver, hasHelp := ((interface{})(InputPaths(nil))).(HasHelp); hasHelp { + into.AddHelp(InputPathsMarker, helpGiver.Help()) + } + return nil +} + +// RegistryFromOptions produces just the marker registry that would be used by FromOptions, without +// attempting to produce a full Runtime. This can be useful if you want to display help without +// trying to load roots. +func RegistryFromOptions(optionsRegistry *markers.Registry, options []string) (*markers.Registry, error) { + protoRt, err := protoFromOptions(optionsRegistry, options) + if err != nil { + return nil, err + } + reg := &markers.Registry{} + if err := protoRt.Generators.RegisterMarkers(reg); err != nil { + return nil, err + } + return reg, nil +} + +// FromOptions parses the options from markers stored in the given registry out into a runtime. +// The markers in the registry must be either +// +// a) Generators +// b) OutputRules +// c) InputPaths +// +// The paths specified in InputPaths are loaded as package roots, and the combined with +// the generators and the specified output rules to produce a runtime that can be run or +// further modified. Not default generators are used if none are specified -- you can check +// the output and rerun for that. +func FromOptions(optionsRegistry *markers.Registry, options []string) (*Runtime, error) { + return FromOptionsWithConfig(&packages.Config{}, optionsRegistry, options) +} + +func FromOptionsWithConfig(cfg *packages.Config, optionsRegistry *markers.Registry, options []string) (*Runtime, error) { + protoRt, err := protoFromOptions(optionsRegistry, options) + if err != nil { + return nil, err + } + + // make the runtime + genRuntime, err := protoRt.Generators.ForRootsWithConfig(cfg, protoRt.Paths...) + if err != nil { + return nil, err + } + + // attempt to figure out what the user wants without a lot of verbose specificity: + // if the user specifies a default rule, assume that they probably want to fall back + // to that. Otherwise, assume that they just wanted to customize one option from the + // set, and leave the rest in the standard configuration. + if protoRt.OutputRules.Default != nil { + genRuntime.OutputRules = protoRt.OutputRules + return genRuntime, nil + } + + outRules := DirectoryPerGenerator("config", protoRt.GeneratorsByName) + for gen, rule := range protoRt.OutputRules.ByGenerator { + outRules.ByGenerator[gen] = rule + } + + genRuntime.OutputRules = outRules + return genRuntime, nil +} + +// protoFromOptions returns a proto-Runtime from the given options registry and +// options set. This can then be used to construct an actual Runtime. See the +// FromOptions function for more details about how the options work. +func protoFromOptions(optionsRegistry *markers.Registry, options []string) (protoRuntime, error) { + var gens Generators + rules := OutputRules{ + ByGenerator: make(map[*Generator]OutputRule), + } + var paths []string + + // collect the generators first, so that we can key the output on the actual + // generator, which matters if there's settings in the gen object and it's not a pointer. + outputByGen := make(map[string]OutputRule) + gensByName := make(map[string]*Generator) + + for _, rawOpt := range options { + if rawOpt[0] != '+' { + rawOpt = "+" + rawOpt // add a `+` to make it acceptable for usage with the registry + } + defn := optionsRegistry.Lookup(rawOpt, markers.DescribesPackage) + if defn == nil { + return protoRuntime{}, fmt.Errorf("unknown option %q", rawOpt[1:]) + } + + val, err := defn.Parse(rawOpt) + if err != nil { + return protoRuntime{}, fmt.Errorf("unable to parse option %q: %w", rawOpt[1:], err) + } + + switch val := val.(type) { + case Generator: + gens = append(gens, &val) + if _, alreadyExists := gensByName[defn.Name]; alreadyExists { + return protoRuntime{}, fmt.Errorf("multiple instances of '%s' generator specified", defn.Name) + } + gensByName[defn.Name] = &val + case OutputRule: + _, genName := splitOutputRuleOption(defn.Name) + if genName == "" { + // it's a default rule + rules.Default = val + continue + } + + outputByGen[genName] = val + continue + case InputPaths: + paths = append(paths, val...) + default: + return protoRuntime{}, fmt.Errorf("unknown option marker %q", defn.Name) + } + } + + // actually associate the rules now that we know the generators + for genName, outputRule := range outputByGen { + gen, knownGen := gensByName[genName] + if !knownGen { + return protoRuntime{}, fmt.Errorf("non-invoked generator %q", genName) + } + + rules.ByGenerator[gen] = outputRule + } + + return protoRuntime{ + Paths: paths, + Generators: gens, + OutputRules: rules, + GeneratorsByName: gensByName, + }, nil +} + +// protoRuntime represents the raw pieces needed to compose a runtime, as +// parsed from some options. +type protoRuntime struct { + Paths []string + Generators Generators + OutputRules OutputRules + GeneratorsByName map[string]*Generator +} + +// splitOutputRuleOption splits a marker name of "output:rule:gen" or "output:rule" +// into its compontent rule and generator name. +func splitOutputRuleOption(name string) (ruleName string, genName string) { + parts := strings.SplitN(name, ":", 3) + if len(parts) == 3 { + // output:: + return parts[2], parts[1] + } + // output: + return parts[1], "" +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/output.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/output.go new file mode 100644 index 000000000..9531e82fa --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/output.go @@ -0,0 +1,165 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package genall + +import ( + "fmt" + "io" + "os" + "path/filepath" + + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// nopCloser is a WriteCloser whose Close +// is a no-op. +type nopCloser struct { + io.Writer +} + +func (n nopCloser) Close() error { + return nil +} + +// DirectoryPerGenerator produces output rules mapping output to a different subdirectory +// of the given base directory for each generator (with each subdirectory specified as +// the key in the input map). +func DirectoryPerGenerator(base string, generators map[string]*Generator) OutputRules { + rules := OutputRules{ + Default: OutputArtifacts{Config: OutputToDirectory(base)}, + ByGenerator: make(map[*Generator]OutputRule, len(generators)), + } + + for name, gen := range generators { + rules.ByGenerator[gen] = OutputArtifacts{ + Config: OutputToDirectory(filepath.Join(base, name)), + } + } + + return rules +} + +// OutputRules defines how to output artificats on a per-generator basis. +type OutputRules struct { + // Default is the output rule used when no specific per-generator overrides match. + Default OutputRule + // ByGenerator contains specific per-generator overrides. + // NB(directxman12): this is a pointer to avoid issues if a given Generator becomes unhashable + // (interface values compare by "dereferencing" their internal pointer first, whereas pointers + // compare by the actual pointer itself). + ByGenerator map[*Generator]OutputRule +} + +// ForGenerator returns the output rule that should be used +// by the given Generator. +func (o OutputRules) ForGenerator(gen *Generator) OutputRule { + if forGen, specific := o.ByGenerator[gen]; specific { + return forGen + } + return o.Default +} + +// OutputRule defines how to output artifacts from a generator. +type OutputRule interface { + // Open opens the given artifact path for writing. If a package is passed, + // the artifact is considered to be used as part of the package (e.g. + // generated code), while a nil package indicates that the artifact is + // config (or something else not involved in Go compilation). + Open(pkg *loader.Package, path string) (io.WriteCloser, error) +} + +// OutputToNothing skips outputting anything. +var OutputToNothing = outputToNothing{} + +// +controllertools:marker:generateHelp:category="" + +// outputToNothing skips outputting anything. +type outputToNothing struct{} + +func (o outputToNothing) Open(_ *loader.Package, _ string) (io.WriteCloser, error) { + return nopCloser{io.Discard}, nil +} + +// +controllertools:marker:generateHelp:category="" + +// OutputToDirectory outputs each artifact to the given directory, regardless +// of if it's package-associated or not. +type OutputToDirectory string + +func (o OutputToDirectory) Open(_ *loader.Package, itemPath string) (io.WriteCloser, error) { + // ensure the directory exists + if err := os.MkdirAll(filepath.Dir(filepath.Join(string(o), itemPath)), os.ModePerm); err != nil { + return nil, err + } + path := filepath.Join(string(o), itemPath) + return os.Create(path) +} + +// OutputToStdout outputs everything to standard-out, with no separation. +// +// Generally useful for single-artifact outputs. +var OutputToStdout = outputToStdout{} + +// +controllertools:marker:generateHelp:category="" + +// outputToStdout outputs everything to standard-out, with no separation. +// +// Generally useful for single-artifact outputs. +type outputToStdout struct{} + +func (o outputToStdout) Open(_ *loader.Package, _ string) (io.WriteCloser, error) { + return nopCloser{os.Stdout}, nil +} + +// +controllertools:marker:generateHelp:category="" + +// OutputArtifacts outputs artifacts to different locations, depending on +// whether they're package-associated or not. +// +// Non-package associated artifacts +// are output to the Config directory, while package-associated ones are output +// to their package's source files' directory, unless an alternate path is +// specified in Code. +type OutputArtifacts struct { + // Config points to the directory to which to write configuration. + Config OutputToDirectory + // Code overrides the directory in which to write new code (defaults to where the existing code lives). + Code OutputToDirectory `marker:",optional"` +} + +func (o OutputArtifacts) Open(pkg *loader.Package, itemPath string) (io.WriteCloser, error) { + if pkg == nil { + return o.Config.Open(pkg, itemPath) + } + + if o.Code != "" { + return o.Code.Open(pkg, itemPath) + } + + if len(pkg.CompiledGoFiles) == 0 { + return nil, fmt.Errorf("cannot output to a package with no path on disk") + } + outDir := filepath.Dir(pkg.CompiledGoFiles[0]) + if _, err := os.Stat(outDir); os.IsNotExist(err) { + if err := os.MkdirAll(outDir, os.ModePerm); err != nil { + return nil, err + } + } + + outPath := filepath.Join(outDir, itemPath) + return os.Create(outPath) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/zz_generated.markerhelp.go new file mode 100644 index 000000000..b33c2392e --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/zz_generated.markerhelp.go @@ -0,0 +1,89 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package genall + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (InputPaths) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "represents paths and go-style path patterns to use as package roots.", + Details: "Multiple paths can be specified using \"{path1, path2, path3}\".", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (OutputArtifacts) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "outputs artifacts to different locations, depending on", + Details: "whether they're package-associated or not.\n\nNon-package associated artifacts\nare output to the Config directory, while package-associated ones are output\nto their package's source files' directory, unless an alternate path is\nspecified in Code.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Config": { + Summary: "points to the directory to which to write configuration.", + Details: "", + }, + "Code": { + Summary: "overrides the directory in which to write new code (defaults to where the existing code lives).", + Details: "", + }, + }, + } +} + +func (OutputToDirectory) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "outputs each artifact to the given directory, regardless", + Details: "of if it's package-associated or not.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (outputToNothing) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "skips outputting anything.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + +func (outputToStdout) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "outputs everything to standard-out, with no separation.", + Details: "Generally useful for single-artifact outputs.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/doc.go new file mode 100644 index 000000000..6853c062f --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/doc.go @@ -0,0 +1,60 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package loader defines helpers for loading packages from sources. It wraps +// go/packages, allow incremental loading of source code and manual control +// over which packages get type-checked. This allows for faster loading in +// cases where you don't actually care about certain imports. +// +// Because it uses go/packages, it's modules-aware, and works in both modules- +// and non-modules environments. +// +// # Loading +// +// The main entrypoint for loading is LoadRoots, which traverse the package +// graph starting at the given patterns (file, package, path, or ...-wildcard, +// as one might pass to go list). Packages beyond the roots can be accessed +// via the Imports() method. Packages are initially loaded with export data +// paths, filenames, and imports. +// +// Packages are suitable for comparison, as each unique package only ever has +// one *Package object returned. +// +// # Syntax and TypeChecking +// +// ASTs and type-checking information can be loaded with NeedSyntax and +// NeedTypesInfo, respectively. Both are idempotent -- repeated calls will +// simply re-use the cached contents. Note that NeedTypesInfo will *only* type +// check the current package -- if you want to type-check imports as well, +// you'll need to type-check them first. +// +// # Reference Pruning and Recursive Checking +// +// In order to type-check using only the packages you care about, you can use a +// TypeChecker. TypeChecker will visit each top-level type declaration, +// collect (optionally filtered) references, and type-check references +// packages. +// +// # Errors +// +// Errors can be added to each package. Use ErrFromNode to create an error +// from an AST node. Errors can then be printed (complete with file and +// position information) using PrintErrors, optionally filtered by error type. +// It's generally a good idea to filter out TypeErrors when doing incomplete +// type-checking with TypeChecker. You can use MaybeErrList to return multiple +// errors if you need to return an error instead of adding it to a package. +// AddError will later unroll it into individual errors. +package loader diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go new file mode 100644 index 000000000..4b4062705 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go @@ -0,0 +1,69 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package loader + +import ( + "errors" + "fmt" + "go/token" +) + +// PositionedError represents some error with an associated position. +// The position is tied to some external token.FileSet. +type PositionedError struct { + Pos token.Pos + error +} + +// Node is the intersection of go/ast.Node and go/types.Var. +type Node interface { + Pos() token.Pos // position of first character belonging to the node +} + +// ErrFromNode returns the given error, with additional information +// attaching it to the given AST node. It will automatically map +// over error lists. +func ErrFromNode(err error, node Node) error { + var asList ErrList + if isList := errors.As(err, &asList); isList { + resList := make(ErrList, len(asList)) + for i, baseErr := range asList { + resList[i] = ErrFromNode(baseErr, node) + } + return resList + } + return PositionedError{ + Pos: node.Pos(), + error: err, + } +} + +// MaybeErrList constructs an ErrList if the given list of +// errors has any errors, otherwise returning nil. +func MaybeErrList(errs []error) error { + if len(errs) == 0 { + return nil + } + return ErrList(errs) +} + +// ErrList is a list of errors aggregated together into a single error. +type ErrList []error + +func (l ErrList) Error() string { + return fmt.Sprintf("%v", []error(l)) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/loader.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/loader.go new file mode 100644 index 000000000..8062b72d8 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/loader.go @@ -0,0 +1,631 @@ +/* +Copyright 2019-2022 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package loader + +import ( + "fmt" + "go/ast" + "go/parser" + "go/scanner" + "go/token" + "go/types" + "os" + "path/filepath" + "regexp" + "sync" + + "golang.org/x/tools/go/packages" + "k8s.io/apimachinery/pkg/util/sets" +) + +// Much of this is strongly inspired by the contents of go/packages, +// except that it allows for lazy loading of syntax and type-checking +// information to speed up cases where full traversal isn't needed. + +// PrintErrors print errors associated with all packages +// in the given package graph, starting at the given root +// packages and traversing through all imports. It will skip +// any errors of the kinds specified in filterKinds. It will +// return true if any errors were printed. +func PrintErrors(pkgs []*Package, filterKinds ...packages.ErrorKind) bool { + pkgsRaw := make([]*packages.Package, len(pkgs)) + for i, pkg := range pkgs { + pkgsRaw[i] = pkg.Package + } + toSkip := make(map[packages.ErrorKind]struct{}) + for _, errKind := range filterKinds { + toSkip[errKind] = struct{}{} + } + hadErrors := false + packages.Visit(pkgsRaw, nil, func(pkgRaw *packages.Package) { + for _, err := range pkgRaw.Errors { + if _, skip := toSkip[err.Kind]; skip { + continue + } + hadErrors = true + fmt.Fprintln(os.Stderr, err) + } + }) + return hadErrors +} + +// Package is a single, unique Go package that can be +// lazily parsed and type-checked. Packages should not +// be constructed directly -- instead, use LoadRoots. +// For a given call to LoadRoots, only a single instance +// of each package exists, and thus they may be used as keys +// and for comparison. +type Package struct { + *packages.Package + + imports map[string]*Package + + loader *loader + sync.Mutex +} + +// Imports returns the imports for the given package, indexed by +// package path (*not* name in any particular file). +func (p *Package) Imports() map[string]*Package { + if p.imports == nil { + p.imports = p.loader.packagesFor(p.Package.Imports) + } + + return p.imports +} + +// NeedTypesInfo indicates that type-checking information is needed for this package. +// Actual type-checking information can be accessed via the Types and TypesInfo fields. +func (p *Package) NeedTypesInfo() { + if p.TypesInfo != nil { + return + } + p.NeedSyntax() + p.loader.typeCheck(p) +} + +// NeedSyntax indicates that a parsed AST is needed for this package. +// Actual ASTs can be accessed via the Syntax field. +func (p *Package) NeedSyntax() { + if p.Syntax != nil { + return + } + out := make([]*ast.File, len(p.CompiledGoFiles)) + var wg sync.WaitGroup + wg.Add(len(p.CompiledGoFiles)) + for i, filename := range p.CompiledGoFiles { + go func(i int, filename string) { + defer wg.Done() + src, err := os.ReadFile(filename) + if err != nil { + p.AddError(err) + return + } + out[i], err = p.loader.parseFile(filename, src) + if err != nil { + p.AddError(err) + return + } + }(i, filename) + } + wg.Wait() + for _, file := range out { + if file == nil { + return + } + } + p.Syntax = out +} + +// AddError adds an error to the errors associated with the given package. +func (p *Package) AddError(err error) { + switch typedErr := err.(type) { + case *os.PathError: + // file-reading errors + p.Errors = append(p.Errors, packages.Error{ + Pos: typedErr.Path + ":1", + Msg: typedErr.Err.Error(), + Kind: packages.ParseError, + }) + case scanner.ErrorList: + // parsing/scanning errors + for _, subErr := range typedErr { + p.Errors = append(p.Errors, packages.Error{ + Pos: subErr.Pos.String(), + Msg: subErr.Msg, + Kind: packages.ParseError, + }) + } + case types.Error: + // type-checking errors + p.Errors = append(p.Errors, packages.Error{ + Pos: typedErr.Fset.Position(typedErr.Pos).String(), + Msg: typedErr.Msg, + Kind: packages.TypeError, + }) + case ErrList: + for _, subErr := range typedErr { + p.AddError(subErr) + } + case PositionedError: + p.Errors = append(p.Errors, packages.Error{ + Pos: p.loader.cfg.Fset.Position(typedErr.Pos).String(), + Msg: typedErr.Error(), + Kind: packages.UnknownError, + }) + default: + // should only happen for external errors, like ref checking + p.Errors = append(p.Errors, packages.Error{ + Pos: p.ID + ":-", + Msg: err.Error(), + Kind: packages.UnknownError, + }) + } +} + +// loader loads packages and their imports. Loaded packages will have +// type size, imports, and exports file information populated. Additional +// information, like ASTs and type-checking information, can be accessed +// via methods on individual packages. +type loader struct { + // Roots are the loaded "root" packages in the package graph loaded via + // LoadRoots. + Roots []*Package + + // cfg contains the package loading config (initialized on demand) + cfg *packages.Config + // packages contains the cache of Packages indexed by the underlying + // package.Package, so that we don't ever produce two Packages with + // the same underlying packages.Package. + packages map[*packages.Package]*Package + packagesMu sync.Mutex +} + +// packageFor returns a wrapped Package for the given packages.Package, +// ensuring that there's a one-to-one mapping between the two. +// It's *not* threadsafe -- use packagesFor for that. +func (l *loader) packageFor(pkgRaw *packages.Package) *Package { + if l.packages[pkgRaw] == nil { + l.packages[pkgRaw] = &Package{ + Package: pkgRaw, + loader: l, + } + } + return l.packages[pkgRaw] +} + +// packagesFor returns a map of Package objects for each packages.Package in the input +// map, ensuring that there's a one-to-one mapping between package.Package and Package +// (as per packageFor). +func (l *loader) packagesFor(pkgsRaw map[string]*packages.Package) map[string]*Package { + l.packagesMu.Lock() + defer l.packagesMu.Unlock() + + out := make(map[string]*Package, len(pkgsRaw)) + for name, rawPkg := range pkgsRaw { + out[name] = l.packageFor(rawPkg) + } + return out +} + +// typeCheck type-checks the given package. +func (l *loader) typeCheck(pkg *Package) { + // don't conflict with typeCheckFromExportData + + pkg.TypesInfo = &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + } + + pkg.Fset = l.cfg.Fset + pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name) + + importer := importerFunc(func(path string) (*types.Package, error) { + if path == "unsafe" { + return types.Unsafe, nil + } + + // The imports map is keyed by import path. + importedPkg := pkg.Imports()[path] + if importedPkg == nil { + return nil, fmt.Errorf("package %q possibly creates an import loop", path) + } + + // it's possible to have a call to check in parallel to a call to this + // if one package in the package graph gets its dependency filtered out, + // but another doesn't (so one wants a "placeholder" package here, and another + // wants the full check). + // + // Thus, we need to lock here (at least for the time being) to avoid + // races between the above write to `pkg.Types` and this checking of + // importedPkg.Types. + importedPkg.Lock() + defer importedPkg.Unlock() + + if importedPkg.Types != nil && importedPkg.Types.Complete() { + return importedPkg.Types, nil + } + + // if we haven't already loaded typecheck data, we don't care about this package's types + return types.NewPackage(importedPkg.PkgPath, importedPkg.Name), nil + }) + + var errs []error + + // type-check + checkConfig := &types.Config{ + Importer: importer, + + IgnoreFuncBodies: true, // we only need decl-level info + + Error: func(err error) { + errs = append(errs, err) + }, + + Sizes: pkg.TypesSizes, + } + if err := types.NewChecker(checkConfig, l.cfg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax); err != nil { + errs = append(errs, err) + } + + // make sure that if a given sub-import is ill-typed, we mark this package as ill-typed as well. + illTyped := len(errs) > 0 + if !illTyped { + for _, importedPkg := range pkg.Imports() { + if importedPkg.IllTyped { + illTyped = true + break + } + } + } + pkg.IllTyped = illTyped + + // publish errors to the package error list. + for _, err := range errs { + pkg.AddError(err) + } +} + +// parseFile parses the given file, including comments. +func (l *loader) parseFile(filename string, src []byte) (*ast.File, error) { + // skip function bodies + file, err := parser.ParseFile(l.cfg.Fset, filename, src, parser.AllErrors|parser.ParseComments) + if err != nil { + return nil, err + } + + return file, nil +} + +// LoadRoots loads the given "root" packages by path, transitively loading +// and all imports as well. +// +// Loaded packages will have type size, imports, and exports file information +// populated. Additional information, like ASTs and type-checking information, +// can be accessed via methods on individual packages. +func LoadRoots(roots ...string) ([]*Package, error) { + return LoadRootsWithConfig(&packages.Config{}, roots...) +} + +// LoadRootsWithConfig functions like LoadRoots, except that it allows passing +// a custom loading config. The config will be modified to suit the needs of +// the loader. +// +// This is generally only useful for use in testing when you need to modify +// loading settings to load from a fake location. +// +// This function will traverse Go module boundaries for roots that are file- +// system paths and end with "...". Please note this feature currently only +// supports roots that are filesystem paths. For more information, please +// refer to the high-level outline of this function's logic: +// +// 1. If no roots are provided then load the working directory and return +// early. +// +// 2. Otherwise sort the provided roots into two, distinct buckets: +// +// a. package/module names +// b. filesystem paths +// +// A filesystem path is distinguished from a Go package/module name by +// the same rules as followed by the "go" command. At a high level, a +// root is a filesystem path IFF it meets ANY of the following criteria: +// +// * is absolute +// * begins with . +// * begins with .. +// +// For more information please refer to the output of the command +// "go help packages". +// +// 3. Load the package/module roots as a single call to packages.Load. If +// there are no filesystem path roots then return early. +// +// 4. For filesystem path roots ending with "...", check to see if its +// descendants include any nested, Go modules. If so, add the directory +// that contains the nested Go module to the filesystem path roots. +// +// 5. Load the filesystem path roots and return the load packages for the +// package/module roots AND the filesystem path roots. +func LoadRootsWithConfig(cfg *packages.Config, roots ...string) ([]*Package, error) { + l := &loader{ + cfg: cfg, + packages: make(map[*packages.Package]*Package), + } + l.cfg.Mode |= packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypesSizes + if l.cfg.Fset == nil { + l.cfg.Fset = token.NewFileSet() + } + + // put our build flags first so that callers can override them. + // + // NOTE: if callers provide their own `-tags` flag, then our hardcoded `ignore_autogenerated` tag + // will be ignored. Callers that provide custom tags MUST include `ignore_autogenerated` in their + // custom tag set if they want that tag to remain active. Users can explicitly pass custom build + // flags with `-tags=""` to disable use of the default `ignore_autogenerated` tag. + l.cfg.BuildFlags = append([]string{"-tags=ignore_autogenerated"}, l.cfg.BuildFlags...) + + // Visit the import graphs of the loaded, root packages. If an imported + // package refers to another loaded, root package, then replace the + // instance of the imported package with a reference to the loaded, root + // package. This is required to make kubebuilder markers work correctly + // when multiple root paths are loaded and types from one path reference + // types from another root path. + defer func() { + for i := range l.Roots { + visitImports(l.Roots, l.Roots[i], nil) + } + }() + + // uniquePkgIDs is used to keep track of the discovered packages to be nice + // and try and prevent packages from showing up twice when nested module + // support is enabled. there is not harm that comes from this per se, but + // it makes testing easier when a known number of modules can be asserted + uniquePkgIDs := sets.Set[string]{} + + // loadPackages returns the Go packages for the provided roots + // + // if validatePkgFn is nil, a package will be returned in the slice, + // otherwise the package is only returned if the result of + // validatePkgFn(pkg.ID) is truthy + loadPackages := func(roots ...string) ([]*Package, error) { + rawPkgs, err := packages.Load(l.cfg, roots...) + if err != nil { + loadRoot := l.cfg.Dir + if l.cfg.Dir == "" { + loadRoot, _ = os.Getwd() + } + return nil, fmt.Errorf("load packages in root %q: %w", loadRoot, err) + } + var pkgs []*Package + for _, rp := range rawPkgs { + p := l.packageFor(rp) + if !uniquePkgIDs.Has(p.ID) { + pkgs = append(pkgs, p) + uniquePkgIDs.Insert(p.ID) + } + } + return pkgs, nil + } + + // if no roots were provided then load the current package and return early + if len(roots) == 0 { + pkgs, err := loadPackages() + if err != nil { + return nil, err + } + l.Roots = append(l.Roots, pkgs...) + return l.Roots, nil + } + + // pkgRoots is a slice of roots that are package/modules and fspRoots + // is a slice of roots that are local filesystem paths. + // + // please refer to this function's godoc comments for more information on + // how these two types of roots are distinguished from one another + var ( + pkgRoots []string + fspRoots []string + fspRootRx = regexp.MustCompile(`^\.{1,2}`) + ) + for _, r := range roots { + if filepath.IsAbs(r) || fspRootRx.MatchString(r) { + fspRoots = append(fspRoots, r) + } else { + pkgRoots = append(pkgRoots, r) + } + } + + // handle the package roots by sending them into the packages.Load function + // all at once. this is more efficient, but cannot be used for the file- + // system path roots due to them needing a custom, calculated value for the + // cfg.Dir field + if len(pkgRoots) > 0 { + pkgs, err := loadPackages(pkgRoots...) + if err != nil { + return nil, err + } + l.Roots = append(l.Roots, pkgs...) + } + + // if there are no filesystem path roots then go ahead and return early + if len(fspRoots) == 0 { + return l.Roots, nil + } + + // + // at this point we are handling filesystem path roots + // + + // ensure the cfg.Dir field is reset to its original value upon + // returning from this function. it should honestly be fine if it is + // not given most callers will not send in the cfg parameter directly, + // as it's largely for testing, but still, let's be good stewards. + defer func(d string) { + cfg.Dir = d + }(cfg.Dir) + + // store the value of cfg.Dir so we can use it later if it is non-empty. + // we need to store it now as the value of cfg.Dir will be updated by + // a loop below + cfgDir := cfg.Dir + + // addNestedGoModulesToRoots is given to filepath.WalkDir and adds the + // directory part of p to the list of filesystem path roots IFF p is the + // path to a file named "go.mod" + addNestedGoModulesToRoots := func( + p string, + d os.DirEntry, + e error) error { + if e != nil { + return e + } + if !d.IsDir() && filepath.Base(p) == "go.mod" { + fspRoots = append(fspRoots, filepath.Join(filepath.Dir(p), "...")) + } + return nil + } + + // in the first pass over the filesystem path roots we: + // + // 1. make the root into an absolute path + // + // 2. check to see if a root uses the nested path syntax, ex. ... + // + // 3. if so, walk the root's descendants, searching for any nested Go + // modules + // + // 4. if found then the directory containing the Go module is added to + // the list of the filesystem path roots + for i := range fspRoots { + r := fspRoots[i] + + // clean up the root + r = filepath.Clean(r) + + // get the absolute path of the root + if !filepath.IsAbs(r) { + // if the initial value of cfg.Dir was non-empty then use it when + // building the absolute path to this root. otherwise use the + // filepath.Abs function to get the absolute path of the root based + // on the working directory + if cfgDir != "" { + r = filepath.Join(cfgDir, r) + } else { + ar, err := filepath.Abs(r) + if err != nil { + return nil, err + } + r = ar + } + } + + // update the root to be an absolute path + fspRoots[i] = r + + b, d := filepath.Base(r), filepath.Dir(r) + + // if the base element is "..." then it means nested traversal is + // activated. this can be passed directly to the loader. however, if + // specified we also want to traverse the path manually to determine if + // there are any nested Go modules we want to add to the list of file- + // system path roots to process + if b == "..." { + if err := filepath.WalkDir( + d, + addNestedGoModulesToRoots); err != nil { + return nil, err + } + } + } + + // in the second pass over the filesystem path roots we: + // + // 1. determine the directory from which to execute the loader + // + // 2. update the loader config's Dir property to be the directory from + // step one + // + // 3. determine whether the root passed to the loader should be "./." + // or "./..." + // + // 4. execute the loader with the value from step three + for _, r := range fspRoots { + b, d := filepath.Base(r), filepath.Dir(r) + + // we want the base part of the path to be either "..." or ".", except + // Go's filepath utilities clean paths during manipulation, removing the + // ".". thus, if not "...", let's update the path components so that: + // + // d = r + // b = "." + if b != "..." { + d = r + b = "." + } + + // update the loader configuration's Dir field to the directory part of + // the root + l.cfg.Dir = d + + // update the root to be "./..." or "./." + // (with OS-specific filepath separator). please note filepath.Join + // would clean up the trailing "." character that we want preserved, + // hence the more manual path concatenation logic + r = fmt.Sprintf(".%s%s", string(filepath.Separator), b) + + // load the packages from the roots + pkgs, err := loadPackages(r) + if err != nil { + return nil, err + } + l.Roots = append(l.Roots, pkgs...) + } + + return l.Roots, nil +} + +// visitImports walks a dependency graph, replacing imported package +// references with those from the rootPkgs list. This ensures the +// kubebuilder marker generation is handled correctly. For more info, +// please see issue 680. +func visitImports(rootPkgs []*Package, pkg *Package, seen sets.Set[string]) { + if seen == nil { + seen = sets.Set[string]{} + } + for importedPkgID, importedPkg := range pkg.Imports() { + for i := range rootPkgs { + if importedPkgID == rootPkgs[i].ID { + pkg.imports[importedPkgID] = rootPkgs[i] + } + } + if !seen.Has(importedPkgID) { + seen.Insert(importedPkgID) + visitImports(rootPkgs, importedPkg, seen) + } + } +} + +// importFunc is an implementation of the single-method +// types.Importer interface based on a function value. +type importerFunc func(path string) (*types.Package, error) + +func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) } diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/paths.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/paths.go new file mode 100644 index 000000000..3b783e168 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/paths.go @@ -0,0 +1,32 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package loader + +import ( + "strings" +) + +// NonVendorPath returns a package path that does not include anything before the +// last vendor directory. This is useful for when using vendor directories, +// and using go/types.Package.Path(), which returns the full path including vendor. +// +// If you're using this, make sure you really need it -- it's better to index by +// the actual Package object when you can. +func NonVendorPath(rawPath string) string { + parts := strings.Split(rawPath, "/vendor/") + return parts[len(parts)-1] +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go new file mode 100644 index 000000000..f58a29f72 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go @@ -0,0 +1,272 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package loader + +import ( + "fmt" + "go/ast" + "strconv" + "sync" +) + +// NB(directxman12): most of this is done by the typechecker, +// but it's a bit slow/heavyweight for what we want -- we want +// to resolve external imports *only* if we actually need them. + +// Basically, what we do is: +// 1. Map imports to names +// 2. Find all explicit external references (`name.type`) +// 3. Find all referenced packages by merging explicit references and dot imports +// 4. Only type-check those packages +// 5. Ignore type-checking errors from the missing packages, because we won't ever +// touch unloaded types (they're probably used in ignored fields/types, variables, or functions) +// (done using PrintErrors with an ignore argument from the caller). +// 6. Notice any actual type-checking errors via invalid types + +// importsMap saves import aliases, mapping them to underlying packages. +type importsMap struct { + // dotImports maps package IDs to packages for any packages that have/ been imported as `.` + dotImports map[string]*Package + // byName maps package aliases or names to the underlying package. + byName map[string]*Package +} + +// mapImports maps imports from the names they use in the given file to the underlying package, +// using a map of package import paths to packages (generally from Package.Imports()). +func mapImports(file *ast.File, importedPkgs map[string]*Package) (*importsMap, error) { + m := &importsMap{ + dotImports: make(map[string]*Package), + byName: make(map[string]*Package), + } + for _, importSpec := range file.Imports { + path, err := strconv.Unquote(importSpec.Path.Value) + if err != nil { + return nil, ErrFromNode(err, importSpec.Path) + } + importedPkg := importedPkgs[path] + if importedPkg == nil { + return nil, ErrFromNode(fmt.Errorf("no such package located"), importSpec.Path) + } + if importSpec.Name == nil { + m.byName[importedPkg.Name] = importedPkg + continue + } + if importSpec.Name.Name == "." { + m.dotImports[importedPkg.ID] = importedPkg + continue + } + m.byName[importSpec.Name.Name] = importedPkg + } + + return m, nil +} + +// referenceSet finds references to external packages' types in the given file, +// without otherwise calling into the type-checker. When checking structs, +// it only checks fields with JSON tags. +type referenceSet struct { + file *ast.File + imports *importsMap + pkg *Package + + externalRefs map[*Package]struct{} +} + +func (r *referenceSet) init() { + if r.externalRefs == nil { + r.externalRefs = make(map[*Package]struct{}) + } +} + +// NodeFilter filters nodes, accepting them for reference collection +// when true is returned and rejecting them when false is returned. +type NodeFilter func(ast.Node) bool + +// collectReferences saves all references to external types in the given info. +func (r *referenceSet) collectReferences(rawType ast.Expr, filterNode NodeFilter) { + r.init() + col := &referenceCollector{ + refs: r, + filterNode: filterNode, + } + ast.Walk(col, rawType) +} + +// external saves an external reference to the given named package. +func (r *referenceSet) external(pkgName string) { + pkg := r.imports.byName[pkgName] + if pkg == nil { + r.pkg.AddError(fmt.Errorf("use of unimported package %q", pkgName)) + return + } + r.externalRefs[pkg] = struct{}{} +} + +// referenceCollector visits nodes in an AST, adding external references to a +// referenceSet. +type referenceCollector struct { + refs *referenceSet + filterNode NodeFilter +} + +func (c *referenceCollector) Visit(node ast.Node) ast.Visitor { + if !c.filterNode(node) { + return nil + } + switch typedNode := node.(type) { + case *ast.Ident: + // local reference or dot-import, ignore + return nil + case *ast.SelectorExpr: + switch x := typedNode.X.(type) { + case *ast.Ident: + pkgName := x.Name + c.refs.external(pkgName) + return nil + default: + return c + } + default: + return c + } +} + +// allReferencedPackages finds all directly referenced packages in the given package. +func allReferencedPackages(pkg *Package, filterNodes NodeFilter) []*Package { + pkg.NeedSyntax() + refsByFile := make(map[*ast.File]*referenceSet) + for _, file := range pkg.Syntax { + imports, err := mapImports(file, pkg.Imports()) + if err != nil { + pkg.AddError(err) + return nil + } + refs := &referenceSet{ + file: file, + imports: imports, + pkg: pkg, + } + refsByFile[file] = refs + } + + EachType(pkg, func(file *ast.File, _ *ast.GenDecl, spec *ast.TypeSpec) { + refs := refsByFile[file] + refs.collectReferences(spec.Type, filterNodes) + }) + + allPackages := make(map[*Package]struct{}) + for _, refs := range refsByFile { + for _, pkg := range refs.imports.dotImports { + allPackages[pkg] = struct{}{} + } + for ref := range refs.externalRefs { + allPackages[ref] = struct{}{} + } + } + + res := make([]*Package, 0, len(allPackages)) + for pkg := range allPackages { + res = append(res, pkg) + } + return res +} + +// TypeChecker performs type-checking on a limitted subset of packages by +// checking each package's types' externally-referenced types, and only +// type-checking those packages. +type TypeChecker struct { + // NodeFilters are used to filter the set of references that are followed + // when typechecking. If any of the filters returns true for a given node, + // its package will be added to the set of packages to check. + // + // If no filters are specified, all references are followed (this may be slow). + // + // Modifying this after the first call to check may yield strange/invalid + // results. + NodeFilters []NodeFilter + + checkedPackages map[*Package]struct{} + sync.Mutex +} + +// Check type-checks the given package and all packages referenced by types +// that pass through (have true returned by) any of the NodeFilters. +func (c *TypeChecker) Check(root *Package) { + c.init() + + // use a sub-checker with the appropriate settings + (&TypeChecker{ + NodeFilters: c.NodeFilters, + checkedPackages: c.checkedPackages, + }).check(root) +} + +func (c *TypeChecker) isNodeInteresting(node ast.Node) bool { + // no filters --> everything is important + if len(c.NodeFilters) == 0 { + return true + } + + // otherwise, passing through any one filter means this node is important + for _, filter := range c.NodeFilters { + if filter(node) { + return true + } + } + return false +} + +func (c *TypeChecker) init() { + if c.checkedPackages == nil { + c.checkedPackages = make(map[*Package]struct{}) + } +} + +// check recursively type-checks the given package, only loading packages that +// are actually referenced by our types (it's the actual implementation of Check, +// without initialization). +func (c *TypeChecker) check(root *Package) { + root.Lock() + defer root.Unlock() + + c.Lock() + _, ok := c.checkedPackages[root] + c.Unlock() + if ok { + return + } + + refedPackages := allReferencedPackages(root, c.isNodeInteresting) + + // first, resolve imports for all leaf packages... + var wg sync.WaitGroup + for _, pkg := range refedPackages { + wg.Add(1) + go func(pkg *Package) { + defer wg.Done() + c.check(pkg) + }(pkg) + } + wg.Wait() + + // ...then, we can safely type-check ourself + root.NeedTypesInfo() + + c.Lock() + defer c.Unlock() + c.checkedPackages[root] = struct{}{} +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/visit.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/visit.go new file mode 100644 index 000000000..b5646fde1 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/visit.go @@ -0,0 +1,81 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package loader + +import ( + "go/ast" + "reflect" + "strconv" +) + +// TypeCallback is a callback called for each raw AST (gendecl, typespec) combo. +type TypeCallback func(file *ast.File, decl *ast.GenDecl, spec *ast.TypeSpec) + +// EachType calls the given callback for each (gendecl, typespec) combo in the +// given package. Generally, using markers.EachType is better when working +// with marker data, and has a more convinient representation. +func EachType(pkg *Package, cb TypeCallback) { + visitor := &typeVisitor{ + callback: cb, + } + pkg.NeedSyntax() + for _, file := range pkg.Syntax { + visitor.file = file + ast.Walk(visitor, file) + } +} + +// typeVisitor visits all TypeSpecs, calling the given callback for each. +type typeVisitor struct { + callback TypeCallback + decl *ast.GenDecl + file *ast.File +} + +// Visit visits all TypeSpecs. +func (v *typeVisitor) Visit(node ast.Node) ast.Visitor { + if node == nil { + v.decl = nil + return v + } + + switch typedNode := node.(type) { + case *ast.File: + v.file = typedNode + return v + case *ast.GenDecl: + v.decl = typedNode + return v + case *ast.TypeSpec: + v.callback(v.file, v.decl, typedNode) + return nil // don't recurse + default: + return nil + } +} + +// ParseAstTag parses the given raw tag literal into a reflect.StructTag. +func ParseAstTag(tag *ast.BasicLit) reflect.StructTag { + if tag == nil { + return reflect.StructTag("") + } + tagStr, err := strconv.Unquote(tag.Value) + if err != nil { + return reflect.StructTag("") + } + return reflect.StructTag(tagStr) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/collect.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/collect.go new file mode 100644 index 000000000..23f52e3d2 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/collect.go @@ -0,0 +1,420 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "go/ast" + "go/token" + "strings" + "sync" + + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// Collector collects and parses marker comments defined in the registry +// from package source code. If no registry is provided, an empty one will +// be initialized on the first call to MarkersInPackage. +type Collector struct { + *Registry + + byPackage map[*loader.Package]map[ast.Node]MarkerValues + mu sync.Mutex +} + +// MarkerValues are all the values for some set of markers. +type MarkerValues map[string][]interface{} + +// Get fetches the first value that for the given marker, returning +// nil if no values are available. +func (v MarkerValues) Get(name string) interface{} { + vals := v[name] + if len(vals) == 0 { + return nil + } + return vals[0] +} + +func (c *Collector) init() { + if c.Registry == nil { + c.Registry = &Registry{} + } + if c.byPackage == nil { + c.byPackage = make(map[*loader.Package]map[ast.Node]MarkerValues) + } +} + +// MarkersInPackage computes the marker values by node for the given package. Results +// are cached by package ID, so this is safe to call repeatedly from different functions. +// Each file in the package is treated as a distinct node. +// +// We consider a marker to be associated with a given AST node if either of the following are true: +// +// - it's in the Godoc for that AST node +// +// - it's in the closest non-godoc comment group above that node, +// *and* that node is a type or field node, *and* [it's either +// registered as type-level *or* it's not registered as being +// package-level] +// +// - it's not in the Godoc of a node, doesn't meet the above criteria, and +// isn't in a struct definition (in which case it's package-level) +func (c *Collector) MarkersInPackage(pkg *loader.Package) (map[ast.Node]MarkerValues, error) { + c.mu.Lock() + c.init() + if markers, exist := c.byPackage[pkg]; exist { + c.mu.Unlock() + return markers, nil + } + // unlock early, it's ok if we do a bit extra work rather than locking while we're working + c.mu.Unlock() + + pkg.NeedSyntax() + nodeMarkersRaw := c.associatePkgMarkers(pkg) + markers, err := c.parseMarkersInPackage(nodeMarkersRaw) + if err != nil { + return nil, err + } + + c.mu.Lock() + defer c.mu.Unlock() + c.byPackage[pkg] = markers + return markers, nil +} + +// parseMarkersInPackage parses the given raw marker comments into output values using the registry. +func (c *Collector) parseMarkersInPackage(nodeMarkersRaw map[ast.Node][]markerComment) (map[ast.Node]MarkerValues, error) { + var errors []error + nodeMarkerValues := make(map[ast.Node]MarkerValues) + for node, markersRaw := range nodeMarkersRaw { + var target TargetType + switch node.(type) { + case *ast.File: + target = DescribesPackage + case *ast.Field: + target = DescribesField + default: + target = DescribesType + } + markerVals := make(map[string][]interface{}) + for _, markerRaw := range markersRaw { + markerText := markerRaw.Text() + def := c.Registry.Lookup(markerText, target) + if def == nil { + continue + } + val, err := def.Parse(markerText) + if err != nil { + errors = append(errors, loader.ErrFromNode(err, markerRaw)) + continue + } + markerVals[def.Name] = append(markerVals[def.Name], val) + } + nodeMarkerValues[node] = markerVals + } + + return nodeMarkerValues, loader.MaybeErrList(errors) +} + +// associatePkgMarkers associates markers with AST nodes in the given package. +func (c *Collector) associatePkgMarkers(pkg *loader.Package) map[ast.Node][]markerComment { + nodeMarkers := make(map[ast.Node][]markerComment) + for _, file := range pkg.Syntax { + fileNodeMarkers := c.associateFileMarkers(file) + for node, markers := range fileNodeMarkers { + nodeMarkers[node] = append(nodeMarkers[node], markers...) + } + } + + return nodeMarkers +} + +// associateFileMarkers associates markers with AST nodes in the given file. +func (c *Collector) associateFileMarkers(file *ast.File) map[ast.Node][]markerComment { + // grab all the raw marker comments by node + visitor := markerSubVisitor{ + collectPackageLevel: true, + markerVisitor: &markerVisitor{ + nodeMarkers: make(map[ast.Node][]markerComment), + allComments: file.Comments, + }, + } + ast.Walk(visitor, file) + + // grab the last package-level comments at the end of the file (if any) + lastFileMarkers := visitor.markersBetween(false, visitor.commentInd, len(visitor.allComments)) + visitor.pkgMarkers = append(visitor.pkgMarkers, lastFileMarkers...) + + // figure out if any type-level markers are actually package-level markers + for node, markers := range visitor.nodeMarkers { + _, isType := node.(*ast.TypeSpec) + if !isType { + continue + } + endOfMarkers := 0 + for _, marker := range markers { + if marker.fromGodoc { + // markers from godoc are never package level + markers[endOfMarkers] = marker + endOfMarkers++ + continue + } + markerText := marker.Text() + typeDef := c.Registry.Lookup(markerText, DescribesType) + if typeDef != nil { + // prefer assuming type-level markers + markers[endOfMarkers] = marker + endOfMarkers++ + continue + } + def := c.Registry.Lookup(markerText, DescribesPackage) + if def == nil { + // assume type-level unless proven otherwise + markers[endOfMarkers] = marker + endOfMarkers++ + continue + } + // it's package-level, since a package-level definition exists + visitor.pkgMarkers = append(visitor.pkgMarkers, marker) + } + visitor.nodeMarkers[node] = markers[:endOfMarkers] // re-set after trimming the package markers + } + visitor.nodeMarkers[file] = visitor.pkgMarkers + + return visitor.nodeMarkers +} + +// markerComment is an AST comment that contains a marker. +// It may or may not be from a Godoc comment, which affects +// marker re-associated (from type-level to package-level) +type markerComment struct { + *ast.Comment + fromGodoc bool +} + +// Text returns the text of the marker, stripped of the comment +// marker and leading spaces, as should be passed to Registry.Lookup +// and Registry.Parse. +func (c markerComment) Text() string { + return strings.TrimSpace(c.Comment.Text[2:]) +} + +// markerVisistor visits AST nodes, recording markers associated with each node. +type markerVisitor struct { + allComments []*ast.CommentGroup + commentInd int + + declComments []markerComment + lastLineCommentGroup *ast.CommentGroup + + pkgMarkers []markerComment + nodeMarkers map[ast.Node][]markerComment +} + +// isMarkerComment checks that the given comment is a single-line (`//`) +// comment and it's first non-space content is `+`. +func isMarkerComment(comment string) bool { + if comment[0:2] != "//" { + return false + } + stripped := strings.TrimSpace(comment[2:]) + if len(stripped) < 1 || stripped[0] != '+' { + return false + } + return true +} + +// markersBetween grabs the markers between the given indicies in the list of all comments. +func (v *markerVisitor) markersBetween(fromGodoc bool, start, end int) []markerComment { + if start < 0 || end < 0 { + return nil + } + var res []markerComment + for i := start; i < end; i++ { + commentGroup := v.allComments[i] + for _, comment := range commentGroup.List { + if !isMarkerComment(comment.Text) { + continue + } + res = append(res, markerComment{Comment: comment, fromGodoc: fromGodoc}) + } + } + return res +} + +type markerSubVisitor struct { + *markerVisitor + node ast.Node + collectPackageLevel bool +} + +// Visit collects markers for each node in the AST, optionally +// collecting unassociated markers as package-level. +func (v markerSubVisitor) Visit(node ast.Node) ast.Visitor { + if node == nil { + // end of the node, so we might need to advance comments beyond the end + // of the block if we don't want to collect package-level markers in + // this block. + + if !v.collectPackageLevel { + if v.commentInd < len(v.allComments) { + lastCommentInd := v.commentInd + nextGroup := v.allComments[lastCommentInd] + for nextGroup.Pos() < v.node.End() { + lastCommentInd++ + if lastCommentInd >= len(v.allComments) { + // after the increment so our decrement below still makes sense + break + } + nextGroup = v.allComments[lastCommentInd] + } + v.commentInd = lastCommentInd + } + } + + return nil + } + + // skip comments on the same line as the previous node + // making sure to double-check for the case where we've gone past the end of the comments + // but still have to finish up typespec-gendecl association (see below). + if v.lastLineCommentGroup != nil && v.commentInd < len(v.allComments) && v.lastLineCommentGroup.Pos() == v.allComments[v.commentInd].Pos() { + v.commentInd++ + } + + // stop visiting if there are no more comments in the file + // NB(directxman12): we can't just stop immediately, because we + // still need to check if there are typespecs associated with gendecls. + var markerCommentBlock []markerComment + var docCommentBlock []markerComment + lastCommentInd := v.commentInd + if v.commentInd < len(v.allComments) { + // figure out the first comment after the node in question... + nextGroup := v.allComments[lastCommentInd] + for nextGroup.Pos() < node.Pos() { + lastCommentInd++ + if lastCommentInd >= len(v.allComments) { + // after the increment so our decrement below still makes sense + break + } + nextGroup = v.allComments[lastCommentInd] + } + lastCommentInd-- // ...then decrement to get the last comment before the node in question + + // figure out the godoc comment so we can deal with it separately + var docGroup *ast.CommentGroup + docGroup, v.lastLineCommentGroup = associatedCommentsFor(node) + + // find the last comment group that's not godoc + markerCommentInd := lastCommentInd + if docGroup != nil && v.allComments[markerCommentInd].Pos() == docGroup.Pos() { + markerCommentInd-- + } + + // check if we have freestanding package markers, + // and find the markers in our "closest non-godoc" comment block, + // plus our godoc comment block + if markerCommentInd >= v.commentInd { + if v.collectPackageLevel { + // assume anything between the comment ind and the marker ind (not including it) + // are package-level + v.pkgMarkers = append(v.pkgMarkers, v.markersBetween(false, v.commentInd, markerCommentInd)...) + } + markerCommentBlock = v.markersBetween(false, markerCommentInd, markerCommentInd+1) + docCommentBlock = v.markersBetween(true, markerCommentInd+1, lastCommentInd+1) + } else { + docCommentBlock = v.markersBetween(true, markerCommentInd+1, lastCommentInd+1) + } + } + + resVisitor := markerSubVisitor{ + collectPackageLevel: false, // don't collect package level by default + markerVisitor: v.markerVisitor, + node: node, + } + + // associate those markers with a node + switch typedNode := node.(type) { + case *ast.GenDecl: + // save the comments associated with the gen-decl if it's a single-line type decl + if typedNode.Lparen != token.NoPos || typedNode.Tok != token.TYPE { + // not a single-line type spec, treat them as free comments + v.pkgMarkers = append(v.pkgMarkers, markerCommentBlock...) + break + } + // save these, we'll need them when we encounter the actual type spec + v.declComments = append(v.declComments, markerCommentBlock...) + v.declComments = append(v.declComments, docCommentBlock...) + case *ast.TypeSpec: + // add in comments attributed to the gen-decl, if any, + // as well as comments associated with the actual type + v.nodeMarkers[node] = append(v.nodeMarkers[node], v.declComments...) + v.nodeMarkers[node] = append(v.nodeMarkers[node], markerCommentBlock...) + v.nodeMarkers[node] = append(v.nodeMarkers[node], docCommentBlock...) + + v.declComments = nil + v.collectPackageLevel = false // don't collect package-level inside type structs + case *ast.Field: + v.nodeMarkers[node] = append(v.nodeMarkers[node], markerCommentBlock...) + v.nodeMarkers[node] = append(v.nodeMarkers[node], docCommentBlock...) + case *ast.File: + v.pkgMarkers = append(v.pkgMarkers, markerCommentBlock...) + v.pkgMarkers = append(v.pkgMarkers, docCommentBlock...) + + // collect markers in root file scope + resVisitor.collectPackageLevel = true + default: + // assume markers before anything else are package-level markers, + // *but* don't include any markers in godoc + if v.collectPackageLevel { + v.pkgMarkers = append(v.pkgMarkers, markerCommentBlock...) + } + } + + // increment the comment ind so that we start at the right place for the next node + v.commentInd = lastCommentInd + 1 + + return resVisitor +} + +// associatedCommentsFor returns the doc comment group (if relevant and present) and end-of-line comment +// (again if relevant and present) for the given AST node. +func associatedCommentsFor(node ast.Node) (docGroup *ast.CommentGroup, lastLineCommentGroup *ast.CommentGroup) { + switch typedNode := node.(type) { + case *ast.Field: + docGroup = typedNode.Doc + lastLineCommentGroup = typedNode.Comment + case *ast.File: + docGroup = typedNode.Doc + case *ast.FuncDecl: + docGroup = typedNode.Doc + case *ast.GenDecl: + docGroup = typedNode.Doc + case *ast.ImportSpec: + docGroup = typedNode.Doc + lastLineCommentGroup = typedNode.Comment + case *ast.TypeSpec: + docGroup = typedNode.Doc + lastLineCommentGroup = typedNode.Comment + case *ast.ValueSpec: + docGroup = typedNode.Doc + lastLineCommentGroup = typedNode.Comment + default: + lastLineCommentGroup = nil + } + + return docGroup, lastLineCommentGroup +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/doc.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/doc.go new file mode 100644 index 000000000..ab6947cca --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/doc.go @@ -0,0 +1,113 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package markers contains utilities for defining and parsing "marker +// comments", also occasionally called tag comments (we use the term marker to +// avoid confusing with struct tags). Parsed result (output) values take the +// form of Go values, much like the "encoding/json" package. +// +// # Definitions and Parsing +// +// Markers are defined as structured Definitions which can be used to +// consistently parse marker comments. A Definition contains an concrete +// output type for the marker, which can be a simple type (like string), a +// struct, or a wrapper type (useful for defining additional methods on marker +// types). +// +// Markers take the general form +// +// +path:to:marker=val +// +// +path:to:marker:arg1=val,arg2=val2 +// +// +path:to:marker +// +// Arguments may be ints, bools, strings, and slices. Ints and bool take their +// standard form from Go. Strings may take any of their standard forms, or any +// sequence of unquoted characters up until a `,` or `;` is encountered. Lists +// take either of the following forms: +// +// val;val;val +// +// {val, val, val} +// +// Note that the first form will not properly parse nested slices, but is +// generally convenient and is the form used in many existing markers. +// +// Each of those argument types maps to the corresponding go type. Pointers +// mark optional fields (a struct tag, below, may also be used). The empty +// interface will match any type. +// +// Struct fields may optionally be annotated with the `marker` struct tag. The +// first argument is a name override. If it's left blank (or the tag isn't +// present), the camelCase version of the name will be used. The only +// additional argument defined is `optional`, which marks a field as optional +// without using a pointer. +// +// All parsed values are unmarshalled into the output type. If any +// non-optional fields aren't mentioned, an error will be raised unless +// `Strict` is set to false. +// +// # Registries and Lookup +// +// Definitions can be added to registries to facilitate lookups. Each +// definition is marked as either describing a type, struct field, or package +// (unassociated). The same marker name may be registered multiple times, as +// long as each describes a different construct (type, field, or package). +// Definitions can then be looked up by passing unparsed markers. +// +// # Collection and Extraction +// +// Markers can be collected from a loader.Package using a Collector. The +// Collector will read from a given Registry, collecting comments that look +// like markers and parsing them if they match some definition on the registry. +// +// Markers are considered associated with a particular field or type if they +// exist in the Godoc, or the closest non-godoc comment. Any other markers not +// inside a some other block (e.g. a struct definition, interface definition, +// etc) are considered package level. Markers in a "closest non-Go comment +// block" may also be considered package level if registered as such and no +// identical type-level definition exists. +// +// Like loader.Package, Collector's methods are idempotent and will not +// reperform work. +// +// # Traversal +// +// EachType function iterates over each type in a Package, providing +// conveniently structured type and field information with marker values +// associated. +// +// PackageMarkers can be used to fetch just package-level markers. +// +// # Help +// +// Help can be defined for each marker using the DefinitionHelp struct. It's +// mostly intended to be generated off of godocs using cmd/helpgen, which takes +// the first line as summary (removing the type/field name), and considers the +// rest as details. It looks for the +// +// +controllertools:generateHelp[:category=] +// +// marker to start generation. +// +// If you can't use godoc-based generation for whatever reasons (e.g. +// primitive-typed markers), you can use the SimpleHelp and DeprecatedHelp +// helper functions to generate help structs. +// +// Help is then registered into a registry as associated with the actual +// definition, and can then be later retrieved from the registry. +package markers diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/help.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/help.go new file mode 100644 index 000000000..26ca059bc --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/help.go @@ -0,0 +1,81 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +// You *probably* don't want to write these structs by hand +// -- use cmd/helpgen if you can write Godoc, and {Simple,Deprecated}Help +// otherwise. + +// DetailedHelp contains brief help, as well as more details. +// For the "full" help, join the two together. +type DetailedHelp struct { + Summary string + Details string +} + +// DefinitionHelp contains overall help for a marker Definition, +// as well as per-field help. +type DefinitionHelp struct { + // DetailedHelp contains the overall help for the marker. + DetailedHelp + // Category describes what kind of marker this is. + Category string + // DeprecatedInFavorOf marks the marker as deprecated. + // If non-nil & empty, it's assumed to just mean deprecated permanently. + // If non-empty, it's assumed to be a marker name. + DeprecatedInFavorOf *string + + // NB(directxman12): we make FieldHelp be in terms of the Go struct field + // names so that we don't have to know the conversion or processing rules + // for struct fields at compile-time for help generation. + + // FieldHelp defines the per-field help for this marker, *in terms of the + // go struct field names. Use the FieldsHelp method to map this to + // marker argument names. + FieldHelp map[string]DetailedHelp +} + +// FieldsHelp maps per-field help to the actual marker argument names from the +// given definition. +func (d *DefinitionHelp) FieldsHelp(def *Definition) map[string]DetailedHelp { + fieldsHelp := make(map[string]DetailedHelp, len(def.FieldNames)) + for fieldName, argName := range def.FieldNames { + fieldsHelp[fieldName] = d.FieldHelp[argName] + } + return fieldsHelp +} + +// SimpleHelp returns help that just has marker-level summary information +// (e.g. for use with empty or primitive-typed markers, where Godoc-based +// generation isn't possible). +func SimpleHelp(category, summary string) *DefinitionHelp { + return &DefinitionHelp{ + Category: category, + DetailedHelp: DetailedHelp{Summary: summary}, + } +} + +// DeprecatedHelp returns simple help (a la SimpleHelp), except marked as +// deprecated in favor of the given marker (or an empty string for just +// deprecated). +func DeprecatedHelp(inFavorOf, category, summary string) *DefinitionHelp { + return &DefinitionHelp{ + Category: category, + DetailedHelp: DetailedHelp{Summary: summary}, + DeprecatedInFavorOf: &inFavorOf, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go new file mode 100644 index 000000000..f42dec0cf --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go @@ -0,0 +1,990 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" + sc "text/scanner" + "unicode" + + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// expect checks that the next token of the scanner is the given token, adding an error +// to the scanner if not. It returns whether the token was as expected. +func expect(scanner *sc.Scanner, expected rune, errDesc string) bool { + tok := scanner.Scan() + if tok != expected { + scanner.Error(scanner, fmt.Sprintf("expected %s, got %q", errDesc, scanner.TokenText())) + return false + } + return true +} + +// peekNoSpace is equivalent to scanner.Peek, except that it will consume intervening whitespace. +func peekNoSpace(scanner *sc.Scanner) rune { + hint := scanner.Peek() + for ; hint <= rune(' ') && ((1<") + case IntType: + out.WriteString("int") + case NumberType: + out.WriteString("float64") + case StringType: + out.WriteString("string") + case BoolType: + out.WriteString("bool") + case AnyType: + out.WriteString("") + case SliceType: + out.WriteString("[]") + // arguments can't be non-pointer optional, so just call into typeString again. + a.ItemType.typeString(out) + case MapType: + out.WriteString("map[string]") + a.ItemType.typeString(out) + case RawType: + out.WriteString("") + } +} + +// TypeString returns a string roughly equivalent +// (but not identical) to the underlying Go type that +// this argument would parse to. It's mainly useful +// for user-friendly formatting of this argument (e.g. +// help strings). +func (a Argument) TypeString() string { + out := &strings.Builder{} + a.typeString(out) + return out.String() +} + +func (a Argument) String() string { + if a.Optional { + return fmt.Sprintf("", a.TypeString()) + } + return fmt.Sprintf("", a.TypeString()) +} + +// castAndSet casts val to out's type if needed, +// then sets out to val. +func castAndSet(out, val reflect.Value) { + outType := out.Type() + if outType != val.Type() { + val = val.Convert(outType) + } + out.Set(val) +} + +// makeSliceType makes a reflect.Type for a slice of the given type. +// Useful for constructing the out value for when AnyType's guess returns a slice. +func makeSliceType(itemType Argument) (reflect.Type, error) { + var itemReflectedType reflect.Type + switch itemType.Type { + case IntType: + itemReflectedType = reflect.TypeOf(int(0)) + case NumberType: + itemReflectedType = reflect.TypeOf(float64(0)) + case StringType: + itemReflectedType = reflect.TypeOf("") + case BoolType: + itemReflectedType = reflect.TypeOf(false) + case SliceType: + subItemType, err := makeSliceType(*itemType.ItemType) + if err != nil { + return nil, err + } + itemReflectedType = subItemType + case MapType: + subItemType, err := makeMapType(*itemType.ItemType) + if err != nil { + return nil, err + } + itemReflectedType = subItemType + // TODO(directxman12): support non-uniform slices? (probably not) + default: + return nil, fmt.Errorf("invalid type when constructing guessed slice out: %v", itemType.Type) + } + + if itemType.Pointer { + itemReflectedType = reflect.PointerTo(itemReflectedType) + } + + return reflect.SliceOf(itemReflectedType), nil +} + +// makeMapType makes a reflect.Type for a map of the given item type. +// Useful for constructing the out value for when AnyType's guess returns a map. +func makeMapType(itemType Argument) (reflect.Type, error) { + var itemReflectedType reflect.Type + switch itemType.Type { + case IntType: + itemReflectedType = reflect.TypeOf(int(0)) + case NumberType: + itemReflectedType = reflect.TypeOf(float64(0)) + case StringType: + itemReflectedType = reflect.TypeOf("") + case BoolType: + itemReflectedType = reflect.TypeOf(false) + case SliceType: + subItemType, err := makeSliceType(*itemType.ItemType) + if err != nil { + return nil, err + } + itemReflectedType = subItemType + // TODO(directxman12): support non-uniform slices? (probably not) + case MapType: + subItemType, err := makeMapType(*itemType.ItemType) + if err != nil { + return nil, err + } + itemReflectedType = subItemType + case AnyType: + // NB(directxman12): maps explicitly allow non-uniform item types, unlike slices at the moment + itemReflectedType = interfaceType + default: + return nil, fmt.Errorf("invalid type when constructing guessed slice out: %v", itemType.Type) + } + + if itemType.Pointer { + itemReflectedType = reflect.PointerTo(itemReflectedType) + } + + return reflect.MapOf(reflect.TypeOf(""), itemReflectedType), nil +} + +// guessType takes an educated guess about the type of the next field. If allowSlice +// is false, it will not guess slices. It's less efficient than parsing with actual +// type information, since we need to allocate to peek ahead full tokens, and the scanner +// only allows peeking ahead one character. +// Maps are *always* non-uniform (i.e. type the AnyType item type), since they're frequently +// used to represent things like defaults for an object in JSON. +func guessType(scanner *sc.Scanner, raw string, allowSlice bool) *Argument { + if allowSlice { + maybeItem := guessType(scanner, raw, false) + + subRaw := raw[scanner.Pos().Offset:] + subScanner := parserScanner(subRaw, scanner.Error) + + var tok rune + for { + tok = subScanner.Scan() + if tok == ',' || tok == sc.EOF || tok == ';' { + break + } + // wait till we get something interesting + } + + // semicolon means it's a legacy slice + if tok == ';' { + return &Argument{ + Type: SliceType, + ItemType: maybeItem, + } + } + + return maybeItem + } + + // everything else needs a duplicate scanner to scan properly + // (so we don't consume our scanner tokens until we actually + // go to use this -- Go doesn't like scanners that can be rewound). + subRaw := raw[scanner.Pos().Offset:] + subScanner := parserScanner(subRaw, scanner.Error) + + // skip whitespace + hint := peekNoSpace(subScanner) + + // first, try the easy case -- quoted strings strings + switch hint { + case '"', '\'', '`': + return &Argument{Type: StringType} + } + + // next, check for slices or maps + if hint == '{' { + subScanner.Scan() + + // TODO(directxman12): this can't guess at empty objects, but that's generally ok. + // We'll cross that bridge when we get there. + + // look ahead till we can figure out if this is a map or a slice + hint = peekNoSpace(subScanner) + firstElemType := guessType(subScanner, subRaw, false) + if firstElemType.Type == StringType { + // might be a map or slice, parse the string and check for colon + // (blech, basically arbitrary look-ahead due to raw strings). + var keyVal string // just ignore this + (&Argument{Type: StringType}).parseString(subScanner, raw, reflect.Indirect(reflect.ValueOf(&keyVal))) + + if token := subScanner.Scan(); token == ':' || hint == '}' { + // it's got a string followed by a colon -- it's a map + // or an empty map in case of {} + return &Argument{ + Type: MapType, + ItemType: &Argument{Type: AnyType}, + } + } + } + + // definitely a slice -- maps have to have string keys and have a value followed by a colon + return &Argument{ + Type: SliceType, + ItemType: firstElemType, + } + } + + // then, bools... + probablyString := false + if hint == 't' || hint == 'f' { + // maybe a bool + if nextTok := subScanner.Scan(); nextTok == sc.Ident { + switch subScanner.TokenText() { + case "true", "false": + // definitely a bool + return &Argument{Type: BoolType} + } + // probably a string + probablyString = true + } else { + // we shouldn't ever get here + scanner.Error(scanner, fmt.Sprintf("got a token (%q) that looked like an ident, but was not", scanner.TokenText())) + return &Argument{Type: InvalidType} + } + } + + // then, integers... + if !probablyString { + nextTok := subScanner.Scan() + if nextTok == '-' { + nextTok = subScanner.Scan() + } + + if nextTok == sc.Int { + return &Argument{Type: IntType} + } + if nextTok == sc.Float { + return &Argument{Type: NumberType} + } + } + + // otherwise assume bare strings + return &Argument{Type: StringType} +} + +// parseString parses either of the two accepted string forms (quoted, or bare tokens). +func (a *Argument) parseString(scanner *sc.Scanner, raw string, out reflect.Value) { + // we need to temporarily disable the scanner's int/float parsing, since we want to + // prevent number parsing errors. + oldMode := scanner.Mode + scanner.Mode = oldMode &^ sc.ScanInts &^ sc.ScanFloats + defer func() { + scanner.Mode = oldMode + }() + + // strings are a bit weird -- the "easy" case is quoted strings (tokenized as strings), + // the "hard" case (present for backwards compat) is a bare sequence of tokens that aren't + // a comma. + tok := scanner.Scan() + if tok == sc.String || tok == sc.RawString { + // the easy case + val, err := strconv.Unquote(scanner.TokenText()) + if err != nil { + scanner.Error(scanner, fmt.Sprintf("unable to parse string: %v", err)) + return + } + castAndSet(out, reflect.ValueOf(val)) + return + } + + // the "hard" case -- bare tokens not including ',' (the argument + // separator), ';' (the slice separator), ':' (the map separator), or '}' + // (delimitted slice ender) + startPos := scanner.Position.Offset + for hint := peekNoSpace(scanner); hint != ',' && hint != ';' && hint != ':' && hint != '}' && hint != sc.EOF; hint = peekNoSpace(scanner) { + // skip this token + scanner.Scan() + } + endPos := scanner.Position.Offset + len(scanner.TokenText()) + castAndSet(out, reflect.ValueOf(raw[startPos:endPos])) +} + +// parseSlice parses either of the two slice forms (curly-brace-delimitted and semicolon-separated). +func (a *Argument) parseSlice(scanner *sc.Scanner, raw string, out reflect.Value) { + // slices have two supported formats, like string: + // - `{val, val, val}` (preferred) + // - `val;val;val` (legacy) + resSlice := reflect.Zero(out.Type()) + elem := reflect.Indirect(reflect.New(out.Type().Elem())) + + // preferred case + if peekNoSpace(scanner) == '{' { + // NB(directxman12): supporting delimitted slices in bare slices + // would require an extra look-ahead here :-/ + + scanner.Scan() // skip '{' + for hint := peekNoSpace(scanner); hint != '}' && hint != sc.EOF; hint = peekNoSpace(scanner) { + a.ItemType.parse(scanner, raw, elem, true /* parsing a slice */) + resSlice = reflect.Append(resSlice, elem) + tok := peekNoSpace(scanner) + if tok == '}' { + break + } + if !expect(scanner, ',', "comma") { + return + } + } + if !expect(scanner, '}', "close curly brace") { + return + } + castAndSet(out, resSlice) + return + } + + // legacy case + for hint := peekNoSpace(scanner); hint != ',' && hint != '}' && hint != sc.EOF; hint = peekNoSpace(scanner) { + a.ItemType.parse(scanner, raw, elem, true /* parsing a slice */) + resSlice = reflect.Append(resSlice, elem) + tok := peekNoSpace(scanner) + if tok == ',' || tok == '}' || tok == sc.EOF { + break + } + scanner.Scan() + if tok != ';' { + scanner.Error(scanner, fmt.Sprintf("expected comma, got %q", scanner.TokenText())) + return + } + } + castAndSet(out, resSlice) +} + +// parseMap parses a map of the form {string: val, string: val, string: val} +func (a *Argument) parseMap(scanner *sc.Scanner, raw string, out reflect.Value) { + resMap := reflect.MakeMap(out.Type()) + elem := reflect.Indirect(reflect.New(out.Type().Elem())) + key := reflect.Indirect(reflect.New(out.Type().Key())) + + if !expect(scanner, '{', "open curly brace") { + return + } + + for hint := peekNoSpace(scanner); hint != '}' && hint != sc.EOF; hint = peekNoSpace(scanner) { + a.parseString(scanner, raw, key) + if !expect(scanner, ':', "colon") { + return + } + a.ItemType.parse(scanner, raw, elem, false /* not in a slice */) + resMap.SetMapIndex(key, elem) + + if peekNoSpace(scanner) == '}' { + break + } + if !expect(scanner, ',', "comma") { + return + } + } + + if !expect(scanner, '}', "close curly brace") { + return + } + + castAndSet(out, resMap) +} + +// parse functions like Parse, except that it allows passing down whether or not we're +// already in a slice, to avoid duplicate legacy slice detection for AnyType +func (a *Argument) parse(scanner *sc.Scanner, raw string, out reflect.Value, inSlice bool) { + if a.Type == InvalidType { + scanner.Error(scanner, "cannot parse invalid type") + return + } + if a.Pointer { + out.Set(reflect.New(out.Type().Elem())) + out = reflect.Indirect(out) + } + switch a.Type { + case RawType: + // raw consumes everything else + castAndSet(out, reflect.ValueOf(raw[scanner.Pos().Offset:])) + // consume everything else + var tok rune + for { + tok = scanner.Scan() + if tok == sc.EOF { + break + } + } + case NumberType: + nextChar := scanner.Peek() + isNegative := false + if nextChar == '-' { + isNegative = true + scanner.Scan() // eat the '-' + } + + tok := scanner.Scan() + if tok != sc.Float && tok != sc.Int { + scanner.Error(scanner, fmt.Sprintf("expected integer or float, got %q", scanner.TokenText())) + return + } + + text := scanner.TokenText() + if isNegative { + text = "-" + text + } + + val, err := strconv.ParseFloat(text, 64) + if err != nil { + scanner.Error(scanner, fmt.Sprintf("unable to parse number: %v", err)) + return + } + + castAndSet(out, reflect.ValueOf(val)) + case IntType: + nextChar := scanner.Peek() + isNegative := false + if nextChar == '-' { + isNegative = true + scanner.Scan() // eat the '-' + } + if !expect(scanner, sc.Int, "integer") { + return + } + // TODO(directxman12): respect the size when parsing + text := scanner.TokenText() + if isNegative { + text = "-" + text + } + val, err := strconv.Atoi(text) + if err != nil { + scanner.Error(scanner, fmt.Sprintf("unable to parse integer: %v", err)) + return + } + castAndSet(out, reflect.ValueOf(val)) + case StringType: + // strings are a bit weird -- the "easy" case is quoted strings (tokenized as strings), + // the "hard" case (present for backwards compat) is a bare sequence of tokens that aren't + // a comma. + a.parseString(scanner, raw, out) + case BoolType: + if !expect(scanner, sc.Ident, "true or false") { + return + } + switch scanner.TokenText() { + case "true": + castAndSet(out, reflect.ValueOf(true)) + case "false": + castAndSet(out, reflect.ValueOf(false)) + default: + scanner.Error(scanner, fmt.Sprintf("expected true or false, got %q", scanner.TokenText())) + return + } + case AnyType: + guessedType := guessType(scanner, raw, !inSlice) + newOut := out + + // we need to be able to construct the right element types, below + // in parse, so construct a concretely-typed value to use as "out" + switch guessedType.Type { + case SliceType: + newType, err := makeSliceType(*guessedType.ItemType) + if err != nil { + scanner.Error(scanner, err.Error()) + return + } + newOut = reflect.Indirect(reflect.New(newType)) + case MapType: + newType, err := makeMapType(*guessedType.ItemType) + if err != nil { + scanner.Error(scanner, err.Error()) + return + } + newOut = reflect.Indirect(reflect.New(newType)) + } + if !newOut.CanSet() { + panic("at the disco") // TODO(directxman12): this is left over from debugging -- it might need to be an error + } + guessedType.Parse(scanner, raw, newOut) + castAndSet(out, newOut) + case SliceType: + // slices have two supported formats, like string: + // - `{val, val, val}` (preferred) + // - `val;val;val` (legacy) + a.parseSlice(scanner, raw, out) + case MapType: + // maps are {string: val, string: val, string: val} + a.parseMap(scanner, raw, out) + } +} + +// Parse attempts to consume the argument from the given scanner (based on the given +// raw input as well for collecting ranges of content), and places the output value +// in the given reflect.Value. Errors are reported via the given scanner. +func (a *Argument) Parse(scanner *sc.Scanner, raw string, out reflect.Value) { + a.parse(scanner, raw, out, false) +} + +// ArgumentFromType constructs an Argument by examining the given +// raw reflect.Type. It can construct arguments from the Go types +// corresponding to any of the types listed in ArgumentType. +func ArgumentFromType(rawType reflect.Type) (Argument, error) { + if rawType == rawArgsType { + return Argument{ + Type: RawType, + }, nil + } + + if rawType == interfaceType { + return Argument{ + Type: AnyType, + }, nil + } + + arg := Argument{} + if rawType.Kind() == reflect.Ptr { + rawType = rawType.Elem() + arg.Pointer = true + arg.Optional = true + } + + switch rawType.Kind() { + case reflect.String: + arg.Type = StringType + case reflect.Int, reflect.Int32: // NB(directxman12): all ints in kubernetes are int32, so explicitly support that + arg.Type = IntType + case reflect.Float64: + arg.Type = NumberType + case reflect.Bool: + arg.Type = BoolType + case reflect.Slice: + arg.Type = SliceType + itemType, err := ArgumentFromType(rawType.Elem()) + if err != nil { + return Argument{}, fmt.Errorf("bad slice item type: %w", err) + } + arg.ItemType = &itemType + case reflect.Map: + arg.Type = MapType + if rawType.Key().Kind() != reflect.String { + return Argument{}, fmt.Errorf("bad map key type: map keys must be strings") + } + itemType, err := ArgumentFromType(rawType.Elem()) + if err != nil { + return Argument{}, fmt.Errorf("bad slice item type: %w", err) + } + arg.ItemType = &itemType + default: + return Argument{}, fmt.Errorf("type has unsupported kind %s", rawType.Kind()) + } + + return arg, nil +} + +// TargetType describes which kind of node a given marker is associated with. +type TargetType int + +const ( + // DescribesPackage indicates that a marker is associated with a package. + DescribesPackage TargetType = iota + // DescribesType indicates that a marker is associated with a type declaration. + DescribesType + // DescribesField indicates that a marker is associated with a struct field. + DescribesField +) + +func (t TargetType) String() string { + switch t { + case DescribesPackage: + return "package" + case DescribesType: + return "type" + case DescribesField: + return "field" + default: + return "(unknown)" + } +} + +// Definition is a parsed definition of a marker. +type Definition struct { + // Output is the deserialized Go type of the marker. + Output reflect.Type + // Name is the marker's name. + Name string + // Target indicates which kind of node this marker can be associated with. + Target TargetType + // Fields lists out the types of each field that this marker has, by + // argument name as used in the marker (if the output type isn't a struct, + // it'll have a single, blank field name). This only lists exported fields, + // (as per reflection rules). + Fields map[string]Argument + // FieldNames maps argument names (as used in the marker) to struct field name + // in the output type. + FieldNames map[string]string + // Strict indicates that this definition should error out when parsing if + // not all non-optional fields were seen. + Strict bool +} + +// AnonymousField indicates that the definition has one field, +// (actually the original object), and thus the field +// doesn't get named as part of the name. +func (d *Definition) AnonymousField() bool { + if len(d.Fields) != 1 { + return false + } + _, hasAnonField := d.Fields[""] + return hasAnonField +} + +// Empty indicates that this definition has no fields. +func (d *Definition) Empty() bool { + return len(d.Fields) == 0 +} + +// argumentInfo returns information about an argument field as the marker parser's field loader +// would see it. This can be useful if you have to interact with marker definition structs +// externally (e.g. at compile time). +func argumentInfo(fieldName string, tag reflect.StructTag) (argName string, optionalOpt bool) { + argName = lowerCamelCase(fieldName) + markerTag, tagSpecified := tag.Lookup("marker") + markerTagParts := strings.Split(markerTag, ",") + if tagSpecified && markerTagParts[0] != "" { + // allow overriding to support legacy cases where we don't follow camelCase conventions + argName = markerTagParts[0] + } + optionalOpt = false + for _, tagOption := range markerTagParts[1:] { + if tagOption == "optional" { + optionalOpt = true + } + } + + return argName, optionalOpt +} + +// loadFields uses reflection to populate argument information from the Output type. +func (d *Definition) loadFields() error { + if d.Fields == nil { + d.Fields = make(map[string]Argument) + d.FieldNames = make(map[string]string) + } + if d.Output.Kind() != reflect.Struct { + // anonymous field type + argType, err := ArgumentFromType(d.Output) + if err != nil { + return err + } + d.Fields[""] = argType + d.FieldNames[""] = "" + return nil + } + + for i := 0; i < d.Output.NumField(); i++ { + field := d.Output.Field(i) + if field.PkgPath != "" { + // as per the reflect package docs, pkgpath is empty for exported fields, + // so non-empty package path means a private field, which we should skip + continue + } + argName, optionalOpt := argumentInfo(field.Name, field.Tag) + + argType, err := ArgumentFromType(field.Type) + if err != nil { + return fmt.Errorf("unable to extract type information for field %q: %w", field.Name, err) + } + + if argType.Type == RawType { + return fmt.Errorf("RawArguments must be the direct type of a marker, and not a field") + } + + argType.Optional = optionalOpt || argType.Optional + + d.Fields[argName] = argType + d.FieldNames[argName] = field.Name + } + + return nil +} + +// parserScanner makes a new scanner appropriate for use in parsing definitions and arguments. +func parserScanner(raw string, err func(*sc.Scanner, string)) *sc.Scanner { + scanner := &sc.Scanner{} + scanner.Init(bytes.NewBufferString(raw)) + scanner.Mode = sc.ScanIdents | sc.ScanInts | sc.ScanFloats | sc.ScanStrings | sc.ScanRawStrings | sc.SkipComments + scanner.Error = err + + return scanner +} + +type markerParser interface { + ParseMarker(name string, anonymousName string, restFields string) error +} + +// Parse uses the type information in this Definition to parse the given +// raw marker in the form `+a:b:c=arg,d=arg` into an output object of the +// type specified in the definition. +func (d *Definition) Parse(rawMarker string) (interface{}, error) { + name, anonName, fields := splitMarker(rawMarker) + + outPointer := reflect.New(d.Output) + out := reflect.Indirect(outPointer) + + if parser, ok := outPointer.Interface().(markerParser); ok { + err := parser.ParseMarker(name, anonName, fields) + return out.Interface(), err + } + + // if we're a not a struct or have no arguments, treat the full `a:b:c` as the name, + // otherwise, treat `c` as a field name, and `a:b` as the marker name. + if !d.AnonymousField() && !d.Empty() && len(anonName) >= len(name)+1 { + fields = anonName[len(name)+1:] + "=" + fields + } + + var errs []error + scanner := parserScanner(fields, func(scanner *sc.Scanner, msg string) { + errs = append(errs, &ScannerError{Msg: msg, Pos: scanner.Position}) + }) + + // TODO(directxman12): strict parsing where we error out if certain fields aren't optional + seen := make(map[string]struct{}, len(d.Fields)) + if d.AnonymousField() && scanner.Peek() != sc.EOF { + // might still be a struct that something fiddled with, so double check + structFieldName := d.FieldNames[""] + outTarget := out + if structFieldName != "" { + // it's a struct field mapped to an anonymous marker + outTarget = out.FieldByName(structFieldName) + if !outTarget.CanSet() { + scanner.Error(scanner, fmt.Sprintf("cannot set field %q (might not exist)", structFieldName)) + return out.Interface(), loader.MaybeErrList(errs) + } + } + + // no need for trying to parse field names if we're not a struct + field := d.Fields[""] + field.Parse(scanner, fields, outTarget) + seen[""] = struct{}{} // mark as seen for strict definitions + } else if !d.Empty() && scanner.Peek() != sc.EOF { + // if we expect *and* actually have arguments passed + for { + // parse the argument name + if !expect(scanner, sc.Ident, "argument name") { + break + } + argName := scanner.TokenText() + if !expect(scanner, '=', "equals") { + break + } + + // make sure we know the field + fieldName, known := d.FieldNames[argName] + if !known { + scanner.Error(scanner, fmt.Sprintf("unknown argument %q", argName)) + break + } + fieldType, known := d.Fields[argName] + if !known { + scanner.Error(scanner, fmt.Sprintf("unknown argument %q", argName)) + break + } + seen[argName] = struct{}{} // mark as seen for strict definitions + + // parse the field value + fieldVal := out.FieldByName(fieldName) + if !fieldVal.CanSet() { + scanner.Error(scanner, fmt.Sprintf("cannot set field %q (might not exist)", fieldName)) + break + } + fieldType.Parse(scanner, fields, fieldVal) + + if len(errs) > 0 { + break + } + + if scanner.Peek() == sc.EOF { + break + } + if !expect(scanner, ',', "comma") { + break + } + } + } + + if tok := scanner.Scan(); tok != sc.EOF { + scanner.Error(scanner, fmt.Sprintf("extra arguments provided: %q", fields[scanner.Position.Offset:])) + } + + if d.Strict { + for argName, arg := range d.Fields { + if _, wasSeen := seen[argName]; !wasSeen && !arg.Optional { + scanner.Error(scanner, fmt.Sprintf("missing argument %q", argName)) + } + } + } + + return out.Interface(), loader.MaybeErrList(errs) +} + +// MakeDefinition constructs a definition from a name, type, and the output type. +// All such definitions are strict by default. If a struct is passed as the output +// type, its public fields will automatically be populated into Fields (and similar +// fields in Definition). Other values will have a single, empty-string-named Fields +// entry. +func MakeDefinition(name string, target TargetType, output interface{}) (*Definition, error) { + def := &Definition{ + Name: name, + Target: target, + Output: reflect.TypeOf(output), + Strict: true, + } + + if err := def.loadFields(); err != nil { + return nil, err + } + + return def, nil +} + +// MakeAnyTypeDefinition constructs a definition for an output struct with a +// field named `Value` of type `interface{}`. The argument to the marker will +// be parsed as AnyType and assigned to the field named `Value`. +func MakeAnyTypeDefinition(name string, target TargetType, output interface{}) (*Definition, error) { + defn, err := MakeDefinition(name, target, output) + if err != nil { + return nil, err + } + defn.FieldNames = map[string]string{"": "Value"} + defn.Fields = map[string]Argument{"": defn.Fields["value"]} + return defn, nil +} + +// splitMarker takes a marker in the form of `+a:b:c=arg,d=arg` and splits it +// into the name (`a:b`), the name if it's not a struct (`a:b:c`), and the parts +// that are definitely fields (`arg,d=arg`). +func splitMarker(raw string) (name string, anonymousName string, restFields string) { + raw = raw[1:] // get rid of the leading '+' + nameFieldParts := strings.SplitN(raw, "=", 2) + if len(nameFieldParts) == 1 { + return nameFieldParts[0], nameFieldParts[0], "" + } + anonymousName = nameFieldParts[0] + name = anonymousName + restFields = nameFieldParts[1] + + nameParts := strings.Split(name, ":") + if len(nameParts) > 1 { + name = strings.Join(nameParts[:len(nameParts)-1], ":") + } + return name, anonymousName, restFields +} + +type ScannerError struct { + Msg string + Pos sc.Position +} + +func (e *ScannerError) Error() string { + return fmt.Sprintf("%s (at %s)", e.Msg, e.Pos) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/reg.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/reg.go new file mode 100644 index 000000000..7dcd45899 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/reg.go @@ -0,0 +1,154 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "fmt" + "sync" +) + +// Registry keeps track of registered definitions, and allows for easy lookup. +// It's thread-safe, and the zero-value can be safely used. +type Registry struct { + forPkg map[string]*Definition + forType map[string]*Definition + forField map[string]*Definition + helpFor map[*Definition]*DefinitionHelp + + mu sync.RWMutex + initOnce sync.Once +} + +func (r *Registry) init() { + r.initOnce.Do(func() { + if r.forPkg == nil { + r.forPkg = make(map[string]*Definition) + } + if r.forType == nil { + r.forType = make(map[string]*Definition) + } + if r.forField == nil { + r.forField = make(map[string]*Definition) + } + if r.helpFor == nil { + r.helpFor = make(map[*Definition]*DefinitionHelp) + } + }) +} + +// Define defines a new marker with the given name, target, and output type. +// It's a shortcut around +// +// r.Register(MakeDefinition(name, target, obj)) +func (r *Registry) Define(name string, target TargetType, obj interface{}) error { + def, err := MakeDefinition(name, target, obj) + if err != nil { + return err + } + return r.Register(def) +} + +// Register registers the given marker definition with this registry for later lookup. +func (r *Registry) Register(def *Definition) error { + r.init() + + r.mu.Lock() + defer r.mu.Unlock() + + switch def.Target { + case DescribesPackage: + r.forPkg[def.Name] = def + case DescribesType: + r.forType[def.Name] = def + case DescribesField: + r.forField[def.Name] = def + default: + return fmt.Errorf("unknown target type %v", def.Target) + } + return nil +} + +// AddHelp stores the given help in the registry, marking it as associated with +// the given definition. +func (r *Registry) AddHelp(def *Definition, help *DefinitionHelp) { + r.init() + + r.mu.Lock() + defer r.mu.Unlock() + + r.helpFor[def] = help +} + +// Lookup fetches the definition corresponding to the given name and target type. +func (r *Registry) Lookup(name string, target TargetType) *Definition { + r.init() + + r.mu.RLock() + defer r.mu.RUnlock() + + switch target { + case DescribesPackage: + return tryAnonLookup(name, r.forPkg) + case DescribesType: + return tryAnonLookup(name, r.forType) + case DescribesField: + return tryAnonLookup(name, r.forField) + default: + return nil + } +} + +// HelpFor fetches the help for a given definition, if present. +func (r *Registry) HelpFor(def *Definition) *DefinitionHelp { + r.init() + + r.mu.RLock() + defer r.mu.RUnlock() + + return r.helpFor[def] +} + +// AllDefinitions returns all marker definitions known to this registry. +func (r *Registry) AllDefinitions() []*Definition { + res := make([]*Definition, 0, len(r.forPkg)+len(r.forType)+len(r.forField)) + for _, def := range r.forPkg { + res = append(res, def) + } + for _, def := range r.forType { + res = append(res, def) + } + for _, def := range r.forField { + res = append(res, def) + } + return res +} + +// tryAnonLookup tries looking up the given marker as both an struct-based +// marker and an anonymous marker, returning whichever format matches first, +// preferring the longer (anonymous) name in case of conflicts. +func tryAnonLookup(name string, defs map[string]*Definition) *Definition { + // NB(directxman12): we look up anonymous names first to work with + // legacy style marker definitions that have a namespaced approach + // (e.g. deepcopy-gen, which uses `+k8s:deepcopy-gen=foo,bar` *and* + // `+k8s.io:deepcopy-gen:interfaces=foo`). + name, anonName, _ := splitMarker(name) + if def, exists := defs[anonName]; exists { + return def + } + + return defs[name] +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/regutil.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/regutil.go new file mode 100644 index 000000000..a9160c3c2 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/regutil.go @@ -0,0 +1,36 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +// Must panics on errors creating definitions. +func Must(def *Definition, err error) *Definition { + if err != nil { + panic(err) + } + return def +} + +// RegisterAll attempts to register all definitions against the given registry, +// stopping and returning if an error occurs. +func RegisterAll(reg *Registry, defs ...*Definition) error { + for _, def := range defs { + if err := reg.Register(def); err != nil { + return err + } + } + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/zip.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/zip.go new file mode 100644 index 000000000..0ad44e610 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/zip.go @@ -0,0 +1,234 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package markers + +import ( + "go/ast" + "go/token" + "reflect" + "strings" + + "sigs.k8s.io/controller-tools/pkg/loader" +) + +// extractDoc extracts documentation from the given node, skipping markers +// in the godoc and falling back to the decl if necessary (for single-line decls). +func extractDoc(node ast.Node, decl *ast.GenDecl) string { + var docs *ast.CommentGroup + switch docced := node.(type) { + case *ast.Field: + docs = docced.Doc + case *ast.File: + docs = docced.Doc + case *ast.GenDecl: + docs = docced.Doc + case *ast.TypeSpec: + docs = docced.Doc + // type Ident expr expressions get docs attached to the decl, + // so check for that case (missing Lparen == single line type decl) + if docs == nil && decl.Lparen == token.NoPos { + docs = decl.Doc + } + } + + if docs == nil { + return "" + } + + // filter out markers + var outGroup ast.CommentGroup + outGroup.List = make([]*ast.Comment, 0, len(docs.List)) + for _, comment := range docs.List { + if isMarkerComment(comment.Text) { + continue + } + outGroup.List = append(outGroup.List, comment) + } + isAsteriskComment := false + for _, l := range outGroup.List { + if strings.HasPrefix(l.Text, "/*") { + isAsteriskComment = true + break + } + } + + // split lines, and re-join together as a single + // paragraph, respecting double-newlines as + // paragraph markers. + lines := strings.Split(outGroup.Text(), "\n") + if lines[len(lines)-1] == "" { + // chop off the extraneous last part + lines = lines[:len(lines)-1] + } + + outLines := make([]string, 0, len(lines)) + var insideCodeBlock bool + for i, line := range lines { + if isAsteriskComment { + // Trim any extranous whitespace, + // for handling /*…*/-style comments, + // which have whitespace preserved in go/ast: + line = strings.TrimSpace(line) + } + + // Respect that double-newline means + // actual newline: + if line == "" { + lines[i] = "\n" + } else { + lines[i] = line + } + + // Recognize markdown code blocks (``` or ~~~) + // https://spec.commonmark.org/0.27/#fenced-code-blocks + if strings.HasPrefix(line, "```") || strings.HasPrefix(line, "~~~") { + insideCodeBlock = !insideCodeBlock + } + + if !insideCodeBlock { + // If we are not inside markdown code block, follow the Kubernetes formatting conventions: + // - Lines after --- are comments and should be ignored. + // - Lines starting with TODO are comments and should be ignored. + // See function fmtRawDoc() in https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/swagger_doc_generator.go + + if strings.HasPrefix(line, "TODO") { + continue + } + + if strings.HasPrefix(line, "---") { + break + } + } + + outLines = append(outLines, line) + } + return strings.Join(outLines, "\n") +} + +// PackageMarkers collects all the package-level marker values for the given package. +func PackageMarkers(col *Collector, pkg *loader.Package) (MarkerValues, error) { + markers, err := col.MarkersInPackage(pkg) + if err != nil { + return nil, err + } + res := make(MarkerValues) + for _, file := range pkg.Syntax { + fileMarkers := markers[file] + for name, vals := range fileMarkers { + res[name] = append(res[name], vals...) + } + } + + return res, nil +} + +// FieldInfo contains marker values and commonly used information for a struct field. +type FieldInfo struct { + // Name is the name of the field (or "" for embedded fields) + Name string + // Doc is the Godoc of the field, pre-processed to remove markers and joine + // single newlines together. + Doc string + // Tag struct tag associated with this field (or "" if non existed). + Tag reflect.StructTag + + // Markers are all registered markers associated with this field. + Markers MarkerValues + + // RawField is the raw, underlying field AST object that this field represents. + RawField *ast.Field +} + +// TypeInfo contains marker values and commonly used information for a type declaration. +type TypeInfo struct { + // Name is the name of the type. + Name string + // Doc is the Godoc of the type, pre-processed to remove markers and joine + // single newlines together. + Doc string + + // Markers are all registered markers associated with the type. + Markers MarkerValues + + // Fields are all the fields associated with the type, if it's a struct. + // (if not, Fields will be nil). + Fields []FieldInfo + + // RawDecl contains the raw GenDecl that the type was declared as part of. + RawDecl *ast.GenDecl + // RawSpec contains the raw Spec that declared this type. + RawSpec *ast.TypeSpec + // RawFile contains the file in which this type was declared. + RawFile *ast.File +} + +// TypeCallback is a callback called for each type declaration in a package. +type TypeCallback func(info *TypeInfo) + +// EachType collects all markers, then calls the given callback for each type declaration in a package. +// Each individual spec is considered separate, so +// +// type ( +// Foo string +// Bar int +// Baz struct{} +// ) +// +// yields three calls to the callback. +func EachType(col *Collector, pkg *loader.Package, cb TypeCallback) error { + markers, err := col.MarkersInPackage(pkg) + if err != nil { + return err + } + + loader.EachType(pkg, func(file *ast.File, decl *ast.GenDecl, spec *ast.TypeSpec) { + var fields []FieldInfo + if structSpec, isStruct := spec.Type.(*ast.StructType); isStruct { + for _, field := range structSpec.Fields.List { + for _, name := range field.Names { + fields = append(fields, FieldInfo{ + Name: name.Name, + Doc: extractDoc(field, nil), + Tag: loader.ParseAstTag(field.Tag), + Markers: markers[field], + RawField: field, + }) + } + if field.Names == nil { + fields = append(fields, FieldInfo{ + Doc: extractDoc(field, nil), + Tag: loader.ParseAstTag(field.Tag), + Markers: markers[field], + RawField: field, + }) + } + } + } + + cb(&TypeInfo{ + Name: spec.Name.Name, + Markers: markers[spec], + Doc: extractDoc(spec, decl), + Fields: fields, + RawDecl: decl, + RawSpec: spec, + RawFile: file, + }) + }) + + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/rbac/parser.go b/vendor/sigs.k8s.io/controller-tools/pkg/rbac/parser.go new file mode 100644 index 000000000..6521d2658 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/rbac/parser.go @@ -0,0 +1,395 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package rbac contain libraries for generating RBAC manifests from RBAC +// markers in Go source files. +// +// The markers take the form: +// +// +kubebuilder:rbac:groups=,resources=,resourceNames=,verbs=,urls= +package rbac + +import ( + "fmt" + "sort" + "strings" + + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +var ( + // RuleDefinition is a marker for defining RBAC rules. + // Call ToRule on the value to get a Kubernetes RBAC policy rule. + RuleDefinition = markers.Must(markers.MakeDefinition("kubebuilder:rbac", markers.DescribesPackage, Rule{})) +) + +// +controllertools:marker:generateHelp:category=RBAC + +// Rule specifies an RBAC rule to all access to some resources or non-resource URLs. +type Rule struct { + // Groups specifies the API groups that this rule encompasses. + Groups []string `marker:",optional"` + // Resources specifies the API resources that this rule encompasses. + Resources []string `marker:",optional"` + // ResourceNames specifies the names of the API resources that this rule encompasses. + // + // Create requests cannot be restricted by resourcename, as the object's name + // is not known at authorization time. + ResourceNames []string `marker:",optional"` + // Verbs specifies the (lowercase) kubernetes API verbs that this rule encompasses. + Verbs []string + // URL specifies the non-resource URLs that this rule encompasses. + URLs []string `marker:"urls,optional"` + // Namespace specifies the scope of the Rule. + // If not set, the Rule belongs to the generated ClusterRole. + // If set, the Rule belongs to a Role, whose namespace is specified by this field. + Namespace string `marker:",optional"` +} + +// ruleKey represents the resources and non-resources a Rule applies. +type ruleKey struct { + Groups string + Resources string + ResourceNames string + URLs string +} + +func (key ruleKey) String() string { + return fmt.Sprintf("%s + %s + %s + %s", key.Groups, key.Resources, key.ResourceNames, key.URLs) +} + +// ruleKeys implements sort.Interface +type ruleKeys []ruleKey + +func (keys ruleKeys) Len() int { return len(keys) } +func (keys ruleKeys) Swap(i, j int) { keys[i], keys[j] = keys[j], keys[i] } +func (keys ruleKeys) Less(i, j int) bool { return keys[i].String() < keys[j].String() } + +// key normalizes the Rule and returns a ruleKey object. +func (r *Rule) key() ruleKey { + r.normalize() + return ruleKey{ + Groups: strings.Join(r.Groups, "&"), + Resources: strings.Join(r.Resources, "&"), + ResourceNames: strings.Join(r.ResourceNames, "&"), + URLs: strings.Join(r.URLs, "&"), + } +} + +func (r *Rule) keyWithGroupResourceNamesURLsVerbs() string { + key := r.key() + verbs := strings.Join(r.Verbs, "&") + return fmt.Sprintf("%s + %s + %s + %s", key.Groups, key.ResourceNames, key.URLs, verbs) +} + +func (r *Rule) keyWithResourcesResourceNamesURLsVerbs() string { + key := r.key() + verbs := strings.Join(r.Verbs, "&") + return fmt.Sprintf("%s + %s + %s + %s", key.Resources, key.ResourceNames, key.URLs, verbs) +} + +func (r *Rule) keyWitGroupResourcesResourceNamesVerbs() string { + key := r.key() + verbs := strings.Join(r.Verbs, "&") + return fmt.Sprintf("%s + %s + %s + %s", key.Groups, key.Resources, key.ResourceNames, verbs) +} + +// addVerbs adds new verbs into a Rule. +// The duplicates in `r.Verbs` will be removed, and then `r.Verbs` will be sorted. +func (r *Rule) addVerbs(verbs []string) { + r.Verbs = removeDupAndSort(append(r.Verbs, verbs...)) +} + +// normalize removes duplicates from each field of a Rule, and sorts each field. +func (r *Rule) normalize() { + r.Groups = removeDupAndSort(r.Groups) + r.Resources = removeDupAndSort(r.Resources) + r.ResourceNames = removeDupAndSort(r.ResourceNames) + r.Verbs = removeDupAndSort(r.Verbs) + r.URLs = removeDupAndSort(r.URLs) +} + +// removeDupAndSort removes duplicates in strs, sorts the items, and returns a +// new slice of strings. +func removeDupAndSort(strs []string) []string { + set := make(map[string]bool) + for _, str := range strs { + if _, ok := set[str]; !ok { + set[str] = true + } + } + + var result []string + for str := range set { + result = append(result, str) + } + sort.Strings(result) + return result +} + +// ToRule converts this rule to its Kubernetes API form. +func (r *Rule) ToRule() rbacv1.PolicyRule { + return rbacv1.PolicyRule{ + APIGroups: r.Groups, + Verbs: r.Verbs, + Resources: r.Resources, + ResourceNames: r.ResourceNames, + NonResourceURLs: r.URLs, + } +} + +// +controllertools:marker:generateHelp + +// Generator generates ClusterRole objects. +type Generator struct { + // RoleName sets the name of the generated ClusterRole. + RoleName string + + // FileName sets the file name for the generated manifest(s). If not set, defaults to "role.yaml". + FileName string `marker:",optional"` + + // HeaderFile specifies the header text (e.g. license) to prepend to generated files. + HeaderFile string `marker:",optional"` + + // Year specifies the year to substitute for " YEAR" in the header file. + Year string `marker:",optional"` +} + +func (Generator) RegisterMarkers(into *markers.Registry) error { + if err := into.Register(RuleDefinition); err != nil { + return err + } + into.AddHelp(RuleDefinition, Rule{}.Help()) + return nil +} + +// GenerateRoles generate a slice of objs representing either a ClusterRole or a Role object +// The order of the objs in the returned slice is stable and determined by their namespaces. +func GenerateRoles(ctx *genall.GenerationContext, roleName string) ([]interface{}, error) { + rulesByNSResource := make(map[string][]*Rule) + for _, root := range ctx.Roots { + markerSet, err := markers.PackageMarkers(ctx.Collector, root) + if err != nil { + root.AddError(err) + } + + // group RBAC markers by namespace and separate by resource + for _, markerValue := range markerSet[RuleDefinition.Name] { + rule := markerValue.(Rule) + if len(rule.Resources) == 0 { + // Add a rule without any resource if Resources is empty. + r := Rule{ + Groups: rule.Groups, + Resources: []string{}, + ResourceNames: rule.ResourceNames, + URLs: rule.URLs, + Namespace: rule.Namespace, + Verbs: rule.Verbs, + } + namespace := r.Namespace + rulesByNSResource[namespace] = append(rulesByNSResource[namespace], &r) + continue + } + for _, resource := range rule.Resources { + r := Rule{ + Groups: rule.Groups, + Resources: []string{resource}, + ResourceNames: rule.ResourceNames, + URLs: rule.URLs, + Namespace: rule.Namespace, + Verbs: rule.Verbs, + } + namespace := r.Namespace + rulesByNSResource[namespace] = append(rulesByNSResource[namespace], &r) + } + } + } + + // NormalizeRules merge Rule with the same ruleKey and sort the Rules + NormalizeRules := func(rules []*Rule) []rbacv1.PolicyRule { + ruleMap := make(map[ruleKey]*Rule) + // all the Rules having the same ruleKey will be merged into the first Rule + for _, rule := range rules { + // fix the group name first, since letting people type "core" is nice + for i, name := range rule.Groups { + if name == "core" { + rule.Groups[i] = "" + } + } + + key := rule.key() + if _, ok := ruleMap[key]; !ok { + ruleMap[key] = rule + continue + } + ruleMap[key].addVerbs(rule.Verbs) + } + + // deduplicate resources + // 1. create map based on key without resources + ruleMapWithoutResources := make(map[string][]*Rule) + for _, rule := range ruleMap { + // get key without Resources + key := rule.keyWithGroupResourceNamesURLsVerbs() + ruleMapWithoutResources[key] = append(ruleMapWithoutResources[key], rule) + } + // 2. merge to ruleMap + ruleMap = make(map[ruleKey]*Rule) + for _, rules := range ruleMapWithoutResources { + rule := rules[0] + for _, mergeRule := range rules[1:] { + rule.Resources = append(rule.Resources, mergeRule.Resources...) + } + + key := rule.key() + ruleMap[key] = rule + } + + // deduplicate groups + // 1. create map based on key without group + ruleMapWithoutGroup := make(map[string][]*Rule) + for _, rule := range ruleMap { + // get key without Group + key := rule.keyWithResourcesResourceNamesURLsVerbs() + ruleMapWithoutGroup[key] = append(ruleMapWithoutGroup[key], rule) + } + // 2. merge to ruleMap + ruleMap = make(map[ruleKey]*Rule) + for _, rules := range ruleMapWithoutGroup { + rule := rules[0] + for _, mergeRule := range rules[1:] { + rule.Groups = append(rule.Groups, mergeRule.Groups...) + } + key := rule.key() + ruleMap[key] = rule + } + + // deduplicate URLs + // 1. create map based on key without URLs + ruleMapWithoutURLs := make(map[string][]*Rule) + for _, rule := range ruleMap { + // get key without Group + key := rule.keyWitGroupResourcesResourceNamesVerbs() + ruleMapWithoutURLs[key] = append(ruleMapWithoutURLs[key], rule) + } + // 2. merge to ruleMap + ruleMap = make(map[ruleKey]*Rule) + for _, rules := range ruleMapWithoutURLs { + rule := rules[0] + for _, mergeRule := range rules[1:] { + rule.URLs = append(rule.URLs, mergeRule.URLs...) + } + key := rule.key() + ruleMap[key] = rule + } + + // sort the Rules in rules according to their ruleKeys + keys := make([]ruleKey, 0, len(ruleMap)) + for key := range ruleMap { + keys = append(keys, key) + } + sort.Sort(ruleKeys(keys)) + + // Normalize rule verbs to "*" if any verb in the rule is an asterisk + for _, rule := range ruleMap { + for _, verb := range rule.Verbs { + if verb == "*" { + rule.Verbs = []string{"*"} + break + } + } + } + var policyRules []rbacv1.PolicyRule + for _, key := range keys { + policyRules = append(policyRules, ruleMap[key].ToRule()) + } + return policyRules + } + + // collect all the namespaces and sort them + var namespaces []string + for ns := range rulesByNSResource { + namespaces = append(namespaces, ns) + } + sort.Strings(namespaces) + + // process the items in rulesByNS by the order specified in `namespaces` to make sure that the Role order is stable + var objs []interface{} + for _, ns := range namespaces { + rules := rulesByNSResource[ns] + policyRules := NormalizeRules(rules) + if len(policyRules) == 0 { + continue + } + if ns == "" { + objs = append(objs, rbacv1.ClusterRole{ + TypeMeta: metav1.TypeMeta{ + Kind: "ClusterRole", + APIVersion: rbacv1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: roleName, + }, + Rules: policyRules, + }) + } else { + objs = append(objs, rbacv1.Role{ + TypeMeta: metav1.TypeMeta{ + Kind: "Role", + APIVersion: rbacv1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: roleName, + Namespace: ns, + }, + Rules: policyRules, + }) + } + } + + return objs, nil +} + +func (g Generator) Generate(ctx *genall.GenerationContext) error { + objs, err := GenerateRoles(ctx, g.RoleName) + if err != nil { + return err + } + + if len(objs) == 0 { + return nil + } + + var headerText string + if g.HeaderFile != "" { + headerBytes, err := ctx.ReadFile(g.HeaderFile) + if err != nil { + return err + } + headerText = string(headerBytes) + } + headerText = strings.ReplaceAll(headerText, " YEAR", " "+g.Year) + + fileName := "role.yaml" + if g.FileName != "" { + fileName = g.FileName + } + + return ctx.WriteYAML(fileName, headerText, objs, genall.WithTransform(genall.TransformRemoveCreationTimestamp)) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/rbac/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/rbac/zz_generated.markerhelp.go new file mode 100644 index 000000000..085898ab5 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/rbac/zz_generated.markerhelp.go @@ -0,0 +1,89 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package rbac + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "generates ClusterRole objects.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "RoleName": { + Summary: "sets the name of the generated ClusterRole.", + Details: "", + }, + "FileName": { + Summary: "sets the file name for the generated manifest(s). If not set, defaults to \"role.yaml\".", + Details: "", + }, + "HeaderFile": { + Summary: "specifies the header text (e.g. license) to prepend to generated files.", + Details: "", + }, + "Year": { + Summary: "specifies the year to substitute for \" YEAR\" in the header file.", + Details: "", + }, + }, + } +} + +func (Rule) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "RBAC", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies an RBAC rule to all access to some resources or non-resource URLs.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Groups": { + Summary: "specifies the API groups that this rule encompasses.", + Details: "", + }, + "Resources": { + Summary: "specifies the API resources that this rule encompasses.", + Details: "", + }, + "ResourceNames": { + Summary: "specifies the names of the API resources that this rule encompasses.", + Details: "Create requests cannot be restricted by resourcename, as the object's name\nis not known at authorization time.", + }, + "Verbs": { + Summary: "specifies the (lowercase) kubernetes API verbs that this rule encompasses.", + Details: "", + }, + "URLs": { + Summary: "URL specifies the non-resource URLs that this rule encompasses.", + Details: "", + }, + "Namespace": { + Summary: "specifies the scope of the Rule.", + Details: "If not set, the Rule belongs to the generated ClusterRole.\nIf set, the Rule belongs to a Role, whose namespace is specified by this field.", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go new file mode 100644 index 000000000..063a7cfa2 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go @@ -0,0 +1,432 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package schemapatcher + +import ( + "fmt" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + crdgen "sigs.k8s.io/controller-tools/pkg/crd" + crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/loader" + "sigs.k8s.io/controller-tools/pkg/markers" + yamlop "sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml" + kyaml "sigs.k8s.io/yaml" +) + +// NB(directxman12): this code is quite fragile, but there are a sufficient +// number of corner cases that it's hard to decompose into separate tools. +// When in doubt, ping @sttts. +// +// Namely: +// - It needs to only update existing versions +// - It needs to make "stable" changes that don't mess with map key ordering +// (in order to facilitate validating that no change has occurred) +// - It needs to collapse identical schema versions into a top-level schema, +// if all versions are identical (this is a common requirement to all CRDs, +// but in this case it means simple jsonpatch wouldn't suffice) + +// TODO(directxman12): When CRD v1 rolls around, consider splitting this into a +// tool that generates a patch, and a separate tool for applying stable YAML +// patches. + +var ( + currentAPIExtVersion = apiext.SchemeGroupVersion.String() +) + +// +controllertools:marker:generateHelp + +// Generator patches existing CRDs with new schemata. +// +// It will generate output for each "CRD Version" (API version of the CRD type +// itself) , e.g. apiextensions/v1) available. +type Generator struct { + // ManifestsPath contains the CustomResourceDefinition YAML files. + ManifestsPath string `marker:"manifests"` + + // MaxDescLen specifies the maximum description length for fields in CRD's OpenAPI schema. + // + // 0 indicates drop the description for all fields completely. + // n indicates limit the description to at most n characters and truncate the description to + // closest sentence boundary if it exceeds n characters. + MaxDescLen *int `marker:",optional"` + + // GenerateEmbeddedObjectMeta specifies if any embedded ObjectMeta in the CRD should be generated + GenerateEmbeddedObjectMeta *bool `marker:",optional"` +} + +var _ genall.Generator = &Generator{} + +func (Generator) CheckFilter() loader.NodeFilter { + return crdgen.Generator{}.CheckFilter() +} + +func (Generator) RegisterMarkers(into *markers.Registry) error { + return crdmarkers.Register(into) +} + +func (g Generator) Generate(ctx *genall.GenerationContext) (result error) { + parser := &crdgen.Parser{ + Collector: ctx.Collector, + Checker: ctx.Checker, + // Indicates the parser on whether to register the ObjectMeta type or not + GenerateEmbeddedObjectMeta: g.GenerateEmbeddedObjectMeta != nil && *g.GenerateEmbeddedObjectMeta, + } + + crdgen.AddKnownTypes(parser) + for _, root := range ctx.Roots { + parser.NeedPackage(root) + } + + metav1Pkg := crdgen.FindMetav1(ctx.Roots) + if metav1Pkg == nil { + // no objects in the roots, since nothing imported metav1 + return nil + } + + // load existing CRD manifests with group-kind and versions + partialCRDSets, err := crdsFromDirectory(ctx, g.ManifestsPath) + if err != nil { + return err + } + + // generate schemata for the types we care about, and save them to be written later. + for _, groupKind := range crdgen.FindKubeKinds(parser, metav1Pkg) { + existingSet, wanted := partialCRDSets[groupKind] + if !wanted { + continue + } + + for pkg, gv := range parser.GroupVersions { + if gv.Group != groupKind.Group { + continue + } + if _, wantedVersion := existingSet.Versions[gv.Version]; !wantedVersion { + continue + } + + typeIdent := crdgen.TypeIdent{Package: pkg, Name: groupKind.Kind} + parser.NeedFlattenedSchemaFor(typeIdent) + + fullSchema := parser.FlattenedSchemata[typeIdent] + if g.MaxDescLen != nil { + fullSchema = *fullSchema.DeepCopy() + crdgen.TruncateDescription(&fullSchema, *g.MaxDescLen) + } + + // Fix top level ObjectMeta regardless of the settings. + if _, ok := fullSchema.Properties["metadata"]; ok { + fullSchema.Properties["metadata"] = apiext.JSONSchemaProps{Type: "object"} + } + + existingSet.NewSchemata[gv.Version] = fullSchema + } + } + + // patch existing CRDs with new schemata + for _, existingSet := range partialCRDSets { + // first, figure out if we need to merge schemata together if they're *all* + // identical (meaning we also don't have any "unset" versions) + + if len(existingSet.NewSchemata) == 0 { + continue + } + + // copy over the new versions that we have, keeping old versions so + // that we can tell if a schema would be nil + var someVer string + for ver := range existingSet.NewSchemata { + someVer = ver + existingSet.Versions[ver] = struct{}{} + } + + allSame := true + firstSchema := existingSet.NewSchemata[someVer] + for ver := range existingSet.Versions { + otherSchema, hasSchema := existingSet.NewSchemata[ver] + if !hasSchema || !equality.Semantic.DeepEqual(firstSchema, otherSchema) { + allSame = false + break + } + } + + if allSame { + if err := existingSet.setGlobalSchema(); err != nil { + return fmt.Errorf("failed to set global firstSchema for %s: %w", existingSet.GroupKind, err) + } + } else { + if err := existingSet.setVersionedSchemata(); err != nil { + return fmt.Errorf("failed to set versioned schemas for %s: %w", existingSet.GroupKind, err) + } + } + } + + // write the final result out to the new location + for _, set := range partialCRDSets { + // We assume all CRD versions came from different files, since this + // is how controller-gen works. If they came from the same file, + // it'd be non-sensical, since you couldn't reasonably use kubectl + // with them against older servers. + for _, crd := range set.CRDVersions { + if err := func() error { + outWriter, err := ctx.OutputRule.Open(nil, crd.FileName) + if err != nil { + return err + } + defer outWriter.Close() + + enc := yaml.NewEncoder(outWriter) + // yaml.v2 defaults to indent=2, yaml.v3 defaults to indent=4, + // so be compatible with everything else in k8s and choose 2. + enc.SetIndent(2) + + return enc.Encode(crd.Yaml) + }(); err != nil { + return err + } + } + } + + return nil +} + +// partialCRDSet represents a set of CRDs of different apiext versions +// (v1beta1.CRD vs v1.CRD) that represent the same GroupKind. +// +// It tracks modifications to the schemata of those CRDs from this source file, +// plus some useful structured content, and keeps track of the raw YAML representation +// of the different apiext versions. +type partialCRDSet struct { + // GroupKind is the GroupKind represented by this CRD. + GroupKind schema.GroupKind + // NewSchemata are the new schemata generated from Go IDL by controller-gen. + NewSchemata map[string]apiext.JSONSchemaProps + // CRDVersions are the forms of this CRD across different apiextensions + // versions + CRDVersions []*partialCRD + // Versions are the versions of the given GroupKind in this set of CRDs. + Versions map[string]struct{} +} + +// partialCRD represents the raw YAML encoding of a given CRD instance, plus +// the versions contained therein for easy lookup. +type partialCRD struct { + // Yaml is the raw YAML structure of the CRD. + Yaml *yaml.Node + // FileName is the source name of the file that this was read from. + // + // This isn't on partialCRDSet because we could have different CRD versions + // stored in the same file (like controller-tools does by default) or in + // different files. + FileName string + + // CRDVersion is the version of the CRD object itself, from + // apiextensions (currently apiextensions/v1 or apiextensions/v1beta1). + CRDVersion string +} + +// setGlobalSchema sets the versioned schemas (as per setVersionedSchemata). +func (e *partialCRDSet) setGlobalSchema() error { + for _, crdInfo := range e.CRDVersions { + if err := crdInfo.setVersionedSchemata(e.NewSchemata); err != nil { + return err + } + } + return nil +} + +// getVersionsNode gets the YAML node of .spec.versions YAML mapping, +// if returning the node, and whether or not it was present. +func (e *partialCRD) getVersionsNode() (*yaml.Node, bool, error) { + versions, found, err := yamlop.GetNode(e.Yaml, "spec", "versions") + if err != nil { + return nil, false, err + } + if !found { + return nil, false, nil + } + if versions.Kind != yaml.SequenceNode { + return nil, true, fmt.Errorf("unexpected non-sequence versions") + } + return versions, found, nil +} + +// setVersionedSchemata sets the versioned schemata on each encoding in this set as per +// setVersionedSchemata on partialCRD. +func (e *partialCRDSet) setVersionedSchemata() error { + for _, crdInfo := range e.CRDVersions { + if err := crdInfo.setVersionedSchemata(e.NewSchemata); err != nil { + return err + } + } + return nil +} + +// setVersionedSchemata populates all existing versions with new schemata, +// wiping the schema of any version that doesn't have a listed schema. +// Any "unknown" versions are ignored. +func (e *partialCRD) setVersionedSchemata(newSchemata map[string]apiext.JSONSchemaProps) error { + var err error + if err := yamlop.DeleteNode(e.Yaml, "spec", "validation"); err != nil { + return err + } + + versions, found, err := e.getVersionsNode() + if err != nil { + return err + } + if !found { + return fmt.Errorf("unexpected missing versions") + } + + for i, verNode := range versions.Content { + nameNode, _, _ := yamlop.GetNode(verNode, "name") + if nameNode.Kind != yaml.ScalarNode || nameNode.ShortTag() != "!!str" { + return fmt.Errorf("version name was not a string at spec.versions[%d]", i) + } + name := nameNode.Value + if name == "" { + return fmt.Errorf("unexpected empty name at spec.versions[%d]", i) + } + newSchema, found := newSchemata[name] + if !found { + if err := yamlop.DeleteNode(verNode, "schema"); err != nil { + return fmt.Errorf("spec.versions[%d]: %w", i, err) + } + } else { + schemaNodeTree, err := yamlop.ToYAML(newSchema) + if err != nil { + return fmt.Errorf("failed to convert schema to YAML: %w", err) + } + schemaNodeTree = schemaNodeTree.Content[0] // get rid of the document node + yamlop.SetStyle(schemaNodeTree, 0) // clear the style so it defaults to an auto-chosen one + if err := yamlop.SetNode(verNode, *schemaNodeTree, "schema", "openAPIV3Schema"); err != nil { + return fmt.Errorf("spec.versions[%d]: %w", i, err) + } + } + } + return nil +} + +// crdsFromDirectory returns loads all CRDs from the given directory in a +// manner that preserves ordering, comments, etc in order to make patching +// minimally invasive. Returned CRDs are mapped by group-kind. +func crdsFromDirectory(ctx *genall.GenerationContext, dir string) (map[schema.GroupKind]*partialCRDSet, error) { + res := map[schema.GroupKind]*partialCRDSet{} + dirEntries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + for _, fileInfo := range dirEntries { + // find all files that are YAML + if fileInfo.IsDir() || filepath.Ext(fileInfo.Name()) != ".yaml" { + continue + } + + rawContent, err := ctx.ReadFile(filepath.Join(dir, fileInfo.Name())) + if err != nil { + return nil, err + } + + // NB(directxman12): we could use the universal deserializer for this, but it's + // really pretty clunky, and the alternative is actually kinda easier to understand + + // ensure that this is a CRD + var typeMeta metav1.TypeMeta + if err := kyaml.Unmarshal(rawContent, &typeMeta); err != nil { + continue + } + + if typeMeta.APIVersion == "" || typeMeta.Kind != "CustomResourceDefinition" { + // If there's no API version this file probably isn't a CRD. + // Likewise we don't need to care if the Kind isn't CustomResourceDefinition. + continue + } + + if !isSupportedAPIExtGroupVer(typeMeta.APIVersion) { + return nil, fmt.Errorf("load %q: apiVersion %q not supported", filepath.Join(dir, fileInfo.Name()), typeMeta.APIVersion) + } + + // collect the group-kind and versions from the actual structured form + var actualCRD crdIsh + if err := kyaml.Unmarshal(rawContent, &actualCRD); err != nil { + continue + } + groupKind := schema.GroupKind{Group: actualCRD.Spec.Group, Kind: actualCRD.Spec.Names.Kind} + versions := make(map[string]struct{}, len(actualCRD.Spec.Versions)) + for _, ver := range actualCRD.Spec.Versions { + versions[ver.Name] = struct{}{} + } + + // then actually unmarshal in a manner that preserves ordering, etc + var yamlNodeTree yaml.Node + if err := yaml.Unmarshal(rawContent, &yamlNodeTree); err != nil { + continue + } + + // then store this CRDVersion of the CRD in a set, populating the set if necessary + if res[groupKind] == nil { + res[groupKind] = &partialCRDSet{ + GroupKind: groupKind, + NewSchemata: make(map[string]apiext.JSONSchemaProps), + Versions: make(map[string]struct{}), + } + } + for ver := range versions { + res[groupKind].Versions[ver] = struct{}{} + } + res[groupKind].CRDVersions = append(res[groupKind].CRDVersions, &partialCRD{ + Yaml: &yamlNodeTree, + FileName: fileInfo.Name(), + CRDVersion: typeMeta.APIVersion, + }) + } + return res, nil +} + +// isSupportedAPIExtGroupVer checks if the given string-form group-version +// is one of the known apiextensions versions (v1). +func isSupportedAPIExtGroupVer(groupVer string) bool { + return groupVer == currentAPIExtVersion +} + +// crdIsh is a merged blob of CRD fields that looks enough like all versions of +// CRD to extract the relevant information for partialCRDSet and partialCRD. +// +// We keep this separate so it's clear what info we need, and so we don't break +// when we switch canonical internal versions and lose old fields while gaining +// new ones (like in v1beta1 --> v1). +// +// Its use is tied directly to crdsFromDirectory, and is mostly an implementation detail of that. +type crdIsh struct { + Spec struct { + Group string `json:"group"` + Names struct { + Kind string `json:"kind"` + } `json:"names"` + Versions []struct { + Name string `json:"name"` + } `json:"versions"` + } `json:"spec"` +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/convert.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/convert.go new file mode 100644 index 000000000..b0ac00158 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/convert.go @@ -0,0 +1,61 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package yaml + +import ( + "encoding/json" + "fmt" + + "gopkg.in/yaml.v3" +) + +// ToYAML converts some object that serializes to JSON into a YAML node tree. +// It's useful since it pays attention to JSON tags, unlike yaml.Unmarshal or +// yaml.Node.Decode. +func ToYAML(rawObj interface{}) (*yaml.Node, error) { + if rawObj == nil { + return &yaml.Node{Kind: yaml.ScalarNode, Value: "null", Tag: "!!null"}, nil + } + + rawJSON, err := json.Marshal(rawObj) + if err != nil { + return nil, fmt.Errorf("failed to marshal object: %w", err) + } + + var out yaml.Node + if err := yaml.Unmarshal(rawJSON, &out); err != nil { + return nil, fmt.Errorf("unable to unmarshal marshalled object: %w", err) + } + return &out, nil +} + +// changeAll calls the given callback for all nodes in +// the given YAML node tree. +func changeAll(root *yaml.Node, cb func(*yaml.Node)) { + cb(root) + for _, child := range root.Content { + changeAll(child, cb) + } +} + +// SetStyle sets the style for all nodes in the given +// node tree to the given style. +func SetStyle(root *yaml.Node, style yaml.Style) { + changeAll(root, func(node *yaml.Node) { + node.Style = style + }) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/nested.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/nested.go new file mode 100644 index 000000000..70d43dbeb --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/nested.go @@ -0,0 +1,87 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package yaml + +import ( + "fmt" + + "gopkg.in/yaml.v3" +) + +// ValueInMapping finds the value node with the corresponding string key +// in the given mapping node. If the given node is not a mapping, an +// error will be returned. +func ValueInMapping(root *yaml.Node, key string) (*yaml.Node, error) { + if root.Kind != yaml.MappingNode { + return nil, fmt.Errorf("unexpected non-mapping node") + } + + for i := 0; i < len(root.Content)/2; i++ { + keyNode := root.Content[i*2] + if keyNode.Value == key { + return root.Content[i*2+1], nil + } + } + return nil, nil +} + +// asCloseAsPossible goes as deep on the given path as possible, returning the +// last node that existed from the given path in the given tree of mapping +// nodes, as well as the rest of the path that could not be fetched, if any. +func asCloseAsPossible(root *yaml.Node, path ...string) (*yaml.Node, []string, error) { + if root == nil { + return nil, path, nil + } + if root.Kind == yaml.DocumentNode && len(root.Content) > 0 { + root = root.Content[0] + } + + currNode := root + for ; len(path) > 0; path = path[1:] { + if currNode.Kind != yaml.MappingNode { + return nil, nil, fmt.Errorf("unexpected non-mapping (%v) before path %v", currNode.Kind, path) + } + + nextNode, err := ValueInMapping(currNode, path[0]) + if err != nil { + return nil, nil, fmt.Errorf("unable to get next node in path %v: %w", path, err) + } + + if nextNode == nil { + // we're as close as possible + break + } + + currNode = nextNode + } + + return currNode, path, nil +} + +// GetNode gets the node at the given path in the given sequence of mapping +// nodes, or, if it doesn't exist, returning false. +func GetNode(root *yaml.Node, path ...string) (*yaml.Node, bool, error) { + resNode, restPath, err := asCloseAsPossible(root, path...) + if err != nil { + return nil, false, err + } + // more path means the node didn't exist + if len(restPath) != 0 { + return nil, false, nil + } + return resNode, true, nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/set.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/set.go new file mode 100644 index 000000000..ede417f1c --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml/set.go @@ -0,0 +1,80 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package yaml + +import ( + "fmt" + + "gopkg.in/yaml.v3" +) + +// SetNode sets the given path to the given yaml Node, creating mapping nodes along the way. +func SetNode(root *yaml.Node, val yaml.Node, path ...string) error { + currNode, path, err := asCloseAsPossible(root, path...) + if err != nil { + return err + } + + if len(path) > 0 { + if currNode.Kind != yaml.MappingNode { + return fmt.Errorf("unexpected non-mapping before path %v", path) + } + + for ; len(path) > 0; path = path[1:] { + keyNode := yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Style: yaml.DoubleQuotedStyle, Value: path[0]} + nextNode := &yaml.Node{Kind: yaml.MappingNode} + currNode.Content = append(currNode.Content, &keyNode, nextNode) + + currNode = nextNode + } + } + + *currNode = val + return nil +} + +// DeleteNode deletes the node at the given path in the given tree of mapping nodes. +// It's a noop if the path doesn't exist. +func DeleteNode(root *yaml.Node, path ...string) error { + if len(path) == 0 { + return fmt.Errorf("must specify a path to delete") + } + pathToParent, keyToDelete := path[:len(path)-1], path[len(path)-1] + parentNode, path, err := asCloseAsPossible(root, pathToParent...) + if err != nil { + return err + } + if len(path) > 0 { + // no-op, parent node doesn't exist + return nil + } + + if parentNode.Kind != yaml.MappingNode { + return fmt.Errorf("unexpected non-mapping node") + } + + for i := 0; i < len(parentNode.Content)/2; i++ { + keyNode := parentNode.Content[i*2] + if keyNode.Value == keyToDelete { + parentNode.Content = append(parentNode.Content[:i*2], parentNode.Content[i*2+2:]...) + return nil + } + } + + // no-op, key not found in parent node + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/zz_generated.markerhelp.go new file mode 100644 index 000000000..db4cdb074 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/zz_generated.markerhelp.go @@ -0,0 +1,49 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package schemapatcher + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "patches existing CRDs with new schemata.", + Details: "It will generate output for each \"CRD Version\" (API version of the CRD type\nitself) , e.g. apiextensions/v1) available.", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "ManifestsPath": { + Summary: "contains the CustomResourceDefinition YAML files.", + Details: "", + }, + "MaxDescLen": { + Summary: "specifies the maximum description length for fields in CRD's OpenAPI schema.", + Details: "0 indicates drop the description for all fields completely.\nn indicates limit the description to at most n characters and truncate the description to\nclosest sentence boundary if it exceeds n characters.", + }, + "GenerateEmbeddedObjectMeta": { + Summary: "specifies if any embedded ObjectMeta in the CRD should be generated", + Details: "", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/version/version.go b/vendor/sigs.k8s.io/controller-tools/pkg/version/version.go new file mode 100644 index 000000000..8d55cb597 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/version/version.go @@ -0,0 +1,59 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package version provides the version of the main module. +package version + +import ( + "fmt" + "runtime/debug" +) + +// version to be set using ldflags: +// -ldflags "-X sigs.k8s.io/controller-tools/pkg/version.version=v1.0.0" +// falls back to module information is unset +var version = "" + +// Version returns the version of the main module +func Version() string { + if version != "" { + return version + } + info, ok := debug.ReadBuildInfo() + if !ok || info == nil || info.Main.Version == "" { + // binary has not been built with module support or doesn't contain a version. + return "(unknown)" + } + return info.Main.Version +} + +// Print prints the main module version on stdout. +// +// Print will display either: +// +// - "Version: v0.2.1" when the program has been compiled with: +// +// $ go get github.com/controller-tools/cmd/controller-gen@v0.2.1 +// +// Note: go modules requires the usage of semver compatible tags starting with +// 'v' to have nice human-readable versions. +// +// - "Version: (devel)" when the program is compiled from a local git checkout. +// +// - "Version: (unknown)" when not using go modules. +func Print() { + fmt.Printf("Version: %s\n", Version()) +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go new file mode 100644 index 000000000..832edebb0 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go @@ -0,0 +1,633 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package webhook contains libraries for generating webhookconfig manifests +// from markers in Go source files. +// +// The markers take the form: +// +// +kubebuilder:webhook:webhookVersions=<[]string>,failurePolicy=,matchPolicy=,groups=<[]string>,resources=<[]string>,verbs=<[]string>,versions=<[]string>,name=,path=,mutating=,sideEffects=,timeoutSeconds=,admissionReviewVersions=<[]string>,reinvocationPolicy= +package webhook + +import ( + "fmt" + "sort" + "strings" + + admissionregv1 "k8s.io/api/admissionregistration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/sets" + "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/markers" +) + +// The default {Mutating,Validating}WebhookConfiguration version to generate. +const ( + v1 = "v1" + defaultWebhookVersion = v1 + defaultServiceName = "webhook-service" + defaultServiceNamespace = "system" +) + +var ( + // ConfigDefinition is a marker for defining Webhook manifests. + // Call ToWebhook on the value to get a Kubernetes Webhook. + ConfigDefinition = markers.Must(markers.MakeDefinition("kubebuilder:webhook", markers.DescribesPackage, Config{})) + // WebhookConfigDefinition is a marker for defining MutatingWebhookConfiguration or ValidatingWebhookConfiguration manifests. + WebhookConfigDefinition = markers.Must(markers.MakeDefinition("kubebuilder:webhookconfiguration", markers.DescribesPackage, WebhookConfig{})) +) + +// supportedWebhookVersions returns currently supported API version of {Mutating,Validating}WebhookConfiguration. +func supportedWebhookVersions() []string { + return []string{defaultWebhookVersion} +} + +// +controllertools:marker:generateHelp + +type WebhookConfig struct { + // Mutating marks this as a mutating webhook (it's validating only if false) + // + // Mutating webhooks are allowed to change the object in their response, + // and are called *before* all validating webhooks. Mutating webhooks may + // choose to reject an object, similarly to a validating webhook. + Mutating bool + // Name indicates the name of the K8s MutatingWebhookConfiguration or ValidatingWebhookConfiguration object. + Name string `marker:"name,optional"` +} + +// +controllertools:marker:generateHelp:category=Webhook + +// Config specifies how a webhook should be served. +// +// It specifies only the details that are intrinsic to the application serving +// it (e.g. the resources it can handle, or the path it serves on). +type Config struct { + // Mutating marks this as a mutating webhook (it's validating only if false) + // + // Mutating webhooks are allowed to change the object in their response, + // and are called *before* all validating webhooks. Mutating webhooks may + // choose to reject an object, similarly to a validating webhook. + Mutating bool + // FailurePolicy specifies what should happen if the API server cannot reach the webhook. + // + // It may be either "ignore" (to skip the webhook and continue on) or "fail" (to reject + // the object in question). + FailurePolicy string + // MatchPolicy defines how the "rules" list is used to match incoming requests. + // Allowed values are "Exact" (match only if it exactly matches the specified rule) + // or "Equivalent" (match a request if it modifies a resource listed in rules, even via another API group or version). + MatchPolicy string `marker:",optional"` + // SideEffects specify whether calling the webhook will have side effects. + // This has an impact on dry runs and `kubectl diff`: if the sideEffect is "Unknown" (the default) or "Some", then + // the API server will not call the webhook on a dry-run request and fails instead. + // If the value is "None", then the webhook has no side effects and the API server will call it on dry-run. + // If the value is "NoneOnDryRun", then the webhook is responsible for inspecting the "dryRun" property of the + // AdmissionReview sent in the request, and avoiding side effects if that value is "true." + SideEffects string `marker:",optional"` + // TimeoutSeconds allows configuring how long the API server should wait for a webhook to respond before treating the call as a failure. + // If the timeout expires before the webhook responds, the webhook call will be ignored or the API call will be rejected based on the failure policy. + // The timeout value must be between 1 and 30 seconds. + // The timeout for an admission webhook defaults to 10 seconds. + TimeoutSeconds int `marker:",optional"` + + // Groups specifies the API groups that this webhook receives requests for. + Groups []string + // Resources specifies the API resources that this webhook receives requests for. + Resources []string + // Verbs specifies the Kubernetes API verbs that this webhook receives requests for. + // + // Only modification-like verbs may be specified. + // May be "create", "update", "delete", "connect", or "*" (for all). + Verbs []string + // Versions specifies the API versions that this webhook receives requests for. + Versions []string + + // Name indicates the name of this webhook configuration. Should be a domain with at least three segments separated by dots + Name string + + // ServiceName indicates the name of the K8s Service the webhook uses. + ServiceName string `marker:"serviceName,optional"` + + // ServiceNamespace indicates the namespace of the K8s Service the webhook uses. + ServiceNamespace string `marker:"serviceNamespace,optional"` + + // Path specifies that path that the API server should connect to this webhook on. Must be + // prefixed with a '/validate-' or '/mutate-' depending on the type, and followed by + // $GROUP-$VERSION-$KIND where all values are lower-cased and the periods in the group + // are substituted for hyphens. For example, a validating webhook path for type + // batch.tutorial.kubebuilder.io/v1,Kind=CronJob would be + // /validate-batch-tutorial-kubebuilder-io-v1-cronjob + Path string `marker:"path,optional"` + + // ServicePort indicates the port of the K8s Service the webhook uses + ServicePort *int32 `marker:"servicePort,optional"` + + // WebhookVersions specifies the target API versions of the {Mutating,Validating}WebhookConfiguration objects + // itself to generate. The only supported value is v1. Defaults to v1. + WebhookVersions []string `marker:"webhookVersions,optional"` + + // AdmissionReviewVersions is an ordered list of preferred `AdmissionReview` + // versions the Webhook expects. + AdmissionReviewVersions []string `marker:"admissionReviewVersions"` + + // ReinvocationPolicy allows mutating webhooks to request reinvocation after other mutations + // + // To allow mutating admission plugins to observe changes made by other plugins, + // built-in mutating admission plugins are re-run if a mutating webhook modifies + // an object, and mutating webhooks can specify a reinvocationPolicy to control + // whether they are reinvoked as well. + ReinvocationPolicy string `marker:"reinvocationPolicy,optional"` + + // URL allows mutating webhooks configuration to specify an external URL when generating + // the manifests, instead of using the internal service communication. Should be in format of + // https://address:port/path + // When this option is specified, the serviceConfig.Service is removed from webhook the manifest. + // The URL configuration should be between quotes. + // `url` cannot be specified when `path` is specified. + URL string `marker:"url,optional"` +} + +// verbToAPIVariant converts a marker's verb to the proper value for the API. +// Unrecognized verbs are passed through. +func verbToAPIVariant(verbRaw string) admissionregv1.OperationType { + switch strings.ToLower(verbRaw) { + case strings.ToLower(string(admissionregv1.Create)): + return admissionregv1.Create + case strings.ToLower(string(admissionregv1.Update)): + return admissionregv1.Update + case strings.ToLower(string(admissionregv1.Delete)): + return admissionregv1.Delete + case strings.ToLower(string(admissionregv1.Connect)): + return admissionregv1.Connect + case strings.ToLower(string(admissionregv1.OperationAll)): + return admissionregv1.OperationAll + default: + return admissionregv1.OperationType(verbRaw) + } +} + +// ToMutatingWebhookConfiguration converts this WebhookConfig to its Kubernetes API form. +func (c WebhookConfig) ToMutatingWebhookConfiguration() (admissionregv1.MutatingWebhookConfiguration, error) { + if !c.Mutating { + return admissionregv1.MutatingWebhookConfiguration{}, fmt.Errorf("%s is a validating webhook", c.Name) + } + + return admissionregv1.MutatingWebhookConfiguration{ + ObjectMeta: metav1.ObjectMeta{ + Name: c.Name, + }, + }, nil +} + +// ToValidatingWebhookConfiguration converts this WebhookConfig to its Kubernetes API form. +func (c WebhookConfig) ToValidatingWebhookConfiguration() (admissionregv1.ValidatingWebhookConfiguration, error) { + if c.Mutating { + return admissionregv1.ValidatingWebhookConfiguration{}, fmt.Errorf("%s is a mutating webhook", c.Name) + } + + return admissionregv1.ValidatingWebhookConfiguration{ + ObjectMeta: metav1.ObjectMeta{ + Name: c.Name, + }, + }, nil +} + +// ToMutatingWebhook converts this rule to its Kubernetes API form. +func (c Config) ToMutatingWebhook() (admissionregv1.MutatingWebhook, error) { + if !c.Mutating { + return admissionregv1.MutatingWebhook{}, fmt.Errorf("%s is a validating webhook", c.Name) + } + + matchPolicy, err := c.matchPolicy() + if err != nil { + return admissionregv1.MutatingWebhook{}, err + } + + clientConfig, err := c.clientConfig() + if err != nil { + return admissionregv1.MutatingWebhook{}, err + } + + return admissionregv1.MutatingWebhook{ + Name: c.Name, + Rules: c.rules(), + FailurePolicy: c.failurePolicy(), + MatchPolicy: matchPolicy, + ClientConfig: clientConfig, + SideEffects: c.sideEffects(), + TimeoutSeconds: c.timeoutSeconds(), + AdmissionReviewVersions: c.AdmissionReviewVersions, + ReinvocationPolicy: c.reinvocationPolicy(), + }, nil +} + +// ToValidatingWebhook converts this rule to its Kubernetes API form. +func (c Config) ToValidatingWebhook() (admissionregv1.ValidatingWebhook, error) { + if c.Mutating { + return admissionregv1.ValidatingWebhook{}, fmt.Errorf("%s is a mutating webhook", c.Name) + } + + matchPolicy, err := c.matchPolicy() + if err != nil { + return admissionregv1.ValidatingWebhook{}, err + } + + clientConfig, err := c.clientConfig() + if err != nil { + return admissionregv1.ValidatingWebhook{}, err + } + + return admissionregv1.ValidatingWebhook{ + Name: c.Name, + Rules: c.rules(), + FailurePolicy: c.failurePolicy(), + MatchPolicy: matchPolicy, + ClientConfig: clientConfig, + SideEffects: c.sideEffects(), + TimeoutSeconds: c.timeoutSeconds(), + AdmissionReviewVersions: c.AdmissionReviewVersions, + }, nil +} + +// rules returns the configuration of what operations on what +// resources/subresources a webhook should care about. +func (c Config) rules() []admissionregv1.RuleWithOperations { + whConfig := admissionregv1.RuleWithOperations{ + Rule: admissionregv1.Rule{ + APIGroups: c.Groups, + APIVersions: c.Versions, + Resources: c.Resources, + }, + Operations: make([]admissionregv1.OperationType, len(c.Verbs)), + } + + for i, verbRaw := range c.Verbs { + whConfig.Operations[i] = verbToAPIVariant(verbRaw) + } + + // fix the group names, since letting people type "core" is nice + for i, group := range whConfig.APIGroups { + if group == "core" { + whConfig.APIGroups[i] = "" + } + } + + return []admissionregv1.RuleWithOperations{whConfig} +} + +// failurePolicy converts the string value to the proper value for the API. +// Unrecognized values are passed through. +func (c Config) failurePolicy() *admissionregv1.FailurePolicyType { + var failurePolicy admissionregv1.FailurePolicyType + switch strings.ToLower(c.FailurePolicy) { + case strings.ToLower(string(admissionregv1.Ignore)): + failurePolicy = admissionregv1.Ignore + case strings.ToLower(string(admissionregv1.Fail)): + failurePolicy = admissionregv1.Fail + default: + failurePolicy = admissionregv1.FailurePolicyType(c.FailurePolicy) + } + return &failurePolicy +} + +// matchPolicy converts the string value to the proper value for the API. +func (c Config) matchPolicy() (*admissionregv1.MatchPolicyType, error) { + var matchPolicy admissionregv1.MatchPolicyType + switch strings.ToLower(c.MatchPolicy) { + case strings.ToLower(string(admissionregv1.Exact)): + matchPolicy = admissionregv1.Exact + case strings.ToLower(string(admissionregv1.Equivalent)): + matchPolicy = admissionregv1.Equivalent + case "": + return nil, nil + default: + return nil, fmt.Errorf("unknown value %q for matchPolicy", c.MatchPolicy) + } + return &matchPolicy, nil +} + +// clientConfig returns the client config for a webhook. +func (c Config) clientConfig() (admissionregv1.WebhookClientConfig, error) { + if (c.Path != "" && c.URL != "") || (c.Path == "" && c.URL == "") { + return admissionregv1.WebhookClientConfig{}, fmt.Errorf("`url` or `path` markers are required and mutually exclusive") + } + + path := c.Path + if path != "" { + var name, namespace string + var port *int32 + + if c.ServiceName != "" { + name = c.ServiceName + } else { + name = defaultServiceName + } + if c.ServiceNamespace != "" { + namespace = c.ServiceNamespace + } else { + namespace = defaultServiceNamespace + } + if c.ServicePort != nil { + port = c.ServicePort + } + + return admissionregv1.WebhookClientConfig{ + Service: &admissionregv1.ServiceReference{ + Name: name, + Namespace: namespace, + Path: &path, + Port: port, + }, + }, nil + } + + url := c.URL + return admissionregv1.WebhookClientConfig{ + URL: &url, + }, nil +} + +// sideEffects returns the sideEffects config for a webhook. +func (c Config) sideEffects() *admissionregv1.SideEffectClass { + var sideEffects admissionregv1.SideEffectClass + switch strings.ToLower(c.SideEffects) { + case strings.ToLower(string(admissionregv1.SideEffectClassNone)): + sideEffects = admissionregv1.SideEffectClassNone + case strings.ToLower(string(admissionregv1.SideEffectClassNoneOnDryRun)): + sideEffects = admissionregv1.SideEffectClassNoneOnDryRun + case strings.ToLower(string(admissionregv1.SideEffectClassSome)): + sideEffects = admissionregv1.SideEffectClassSome + case "": + return nil + default: + return nil + } + return &sideEffects +} + +// timeoutSeconds returns the timeoutSeconds config for a webhook. +func (c Config) timeoutSeconds() *int32 { + if c.TimeoutSeconds != 0 { + timeoutSeconds := int32(c.TimeoutSeconds) + return &timeoutSeconds + } + return nil +} + +// reinvocationPolicy returns the reinvocationPolicy config for a mutating webhook. +func (c Config) reinvocationPolicy() *admissionregv1.ReinvocationPolicyType { + var reinvocationPolicy admissionregv1.ReinvocationPolicyType + switch strings.ToLower(c.ReinvocationPolicy) { + case strings.ToLower(string(admissionregv1.NeverReinvocationPolicy)): + reinvocationPolicy = admissionregv1.NeverReinvocationPolicy + case strings.ToLower(string(admissionregv1.IfNeededReinvocationPolicy)): + reinvocationPolicy = admissionregv1.IfNeededReinvocationPolicy + default: + return nil + } + return &reinvocationPolicy +} + +// webhookVersions returns the target API versions of the {Mutating,Validating}WebhookConfiguration objects for a webhook. +func (c Config) webhookVersions() ([]string, error) { + // If WebhookVersions is not specified, we default it to `v1`. + if len(c.WebhookVersions) == 0 { + return []string{defaultWebhookVersion}, nil + } + supportedWebhookVersions := sets.NewString(supportedWebhookVersions()...) + for _, version := range c.WebhookVersions { + if !supportedWebhookVersions.Has(version) { + return nil, fmt.Errorf("unsupported webhook version: %s", version) + } + } + return sets.NewString(c.WebhookVersions...).UnsortedList(), nil +} + +// +controllertools:marker:generateHelp + +// Generator generates (partial) {Mutating,Validating}WebhookConfiguration objects. +type Generator struct { + // HeaderFile specifies the header text (e.g. license) to prepend to generated files. + HeaderFile string `marker:",optional"` + + // Year specifies the year to substitute for " YEAR" in the header file. + Year string `marker:",optional"` +} + +func (Generator) RegisterMarkers(into *markers.Registry) error { + if err := into.Register(ConfigDefinition); err != nil { + return err + } + if err := into.Register(WebhookConfigDefinition); err != nil { + return err + } + into.AddHelp(ConfigDefinition, Config{}.Help()) + into.AddHelp(WebhookConfigDefinition, Config{}.Help()) + return nil +} + +//gocyclo:ignore +func (g Generator) Generate(ctx *genall.GenerationContext) error { + supportedWebhookVersions := supportedWebhookVersions() + mutatingCfgs := make(map[string][]admissionregv1.MutatingWebhook, len(supportedWebhookVersions)) + validatingCfgs := make(map[string][]admissionregv1.ValidatingWebhook, len(supportedWebhookVersions)) + var mutatingWebhookCfgs admissionregv1.MutatingWebhookConfiguration + var validatingWebhookCfgs admissionregv1.ValidatingWebhookConfiguration + + for _, root := range ctx.Roots { + markerSet, err := markers.PackageMarkers(ctx.Collector, root) + if err != nil { + root.AddError(err) + } + + webhookCfgs := markerSet[WebhookConfigDefinition.Name] + hasValidatingWebhookConfig, hasMutatingWebhookConfig := false, false + for _, webhookCfg := range webhookCfgs { + webhookCfg := webhookCfg.(WebhookConfig) + + if webhookCfg.Mutating { + if hasMutatingWebhookConfig { + return fmt.Errorf("duplicate mutating %s with name %s", WebhookConfigDefinition.Name, webhookCfg.Name) + } + + if mutatingWebhookCfgs, err = webhookCfg.ToMutatingWebhookConfiguration(); err != nil { + return err + } + + hasMutatingWebhookConfig = true + } else { + if hasValidatingWebhookConfig { + return fmt.Errorf("duplicate validating %s with name %s", WebhookConfigDefinition.Name, webhookCfg.Name) + } + + if validatingWebhookCfgs, err = webhookCfg.ToValidatingWebhookConfiguration(); err != nil { + return err + } + + hasValidatingWebhookConfig = true + } + } + + cfgs := markerSet[ConfigDefinition.Name] + sort.SliceStable(cfgs, func(i, j int) bool { + return cfgs[i].(Config).Name < cfgs[j].(Config).Name + }) + + for _, cfg := range cfgs { + cfg := cfg.(Config) + webhookVersions, err := cfg.webhookVersions() + if err != nil { + return err + } + if cfg.Mutating { + w, err := cfg.ToMutatingWebhook() + if err != nil { + return err + } + for _, webhookVersion := range webhookVersions { + mutatingCfgs[webhookVersion] = append(mutatingCfgs[webhookVersion], w) + } + } else { + w, err := cfg.ToValidatingWebhook() + if err != nil { + return err + } + for _, webhookVersion := range webhookVersions { + validatingCfgs[webhookVersion] = append(validatingCfgs[webhookVersion], w) + } + } + } + } + + versionedWebhooks := make(map[string][]interface{}, len(supportedWebhookVersions)) + for _, version := range supportedWebhookVersions { + if cfgs, ok := mutatingCfgs[version]; ok { + var objRaw *admissionregv1.MutatingWebhookConfiguration + if mutatingWebhookCfgs.Name != "" { + objRaw = &mutatingWebhookCfgs + } else { + // The only possible version in supportedWebhookVersions is v1, + // so use it for all versioned types in this context. + objRaw = &admissionregv1.MutatingWebhookConfiguration{} + objRaw.SetName("mutating-webhook-configuration") + } + objRaw.SetGroupVersionKind(schema.GroupVersionKind{ + Group: admissionregv1.SchemeGroupVersion.Group, + Version: version, + Kind: "MutatingWebhookConfiguration", + }) + objRaw.Webhooks = cfgs + + for i := range objRaw.Webhooks { + // SideEffects is required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, + // return an error + if err := checkSideEffectsForV1(objRaw.Webhooks[i].SideEffects); err != nil { + return err + } + // TimeoutSeconds must be nil or between 1 and 30 seconds, otherwise, + // return an error + if err := checkTimeoutSeconds(objRaw.Webhooks[i].TimeoutSeconds); err != nil { + return err + } + // AdmissionReviewVersions is required in admissionregistration/v1, if this is not set, + // return an error + if len(objRaw.Webhooks[i].AdmissionReviewVersions) == 0 { + return fmt.Errorf("AdmissionReviewVersions is mandatory for v1 {Mutating,Validating}WebhookConfiguration") + } + } + versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) + } + + if cfgs, ok := validatingCfgs[version]; ok { + var objRaw *admissionregv1.ValidatingWebhookConfiguration + if validatingWebhookCfgs.Name != "" { + objRaw = &validatingWebhookCfgs + } else { + // The only possible version in supportedWebhookVersions is v1, + // so use it for all versioned types in this context. + objRaw = &admissionregv1.ValidatingWebhookConfiguration{} + objRaw.SetName("validating-webhook-configuration") + } + objRaw.SetGroupVersionKind(schema.GroupVersionKind{ + Group: admissionregv1.SchemeGroupVersion.Group, + Version: version, + Kind: "ValidatingWebhookConfiguration", + }) + objRaw.Webhooks = cfgs + + for i := range objRaw.Webhooks { + // SideEffects is required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, + // return an error + if err := checkSideEffectsForV1(objRaw.Webhooks[i].SideEffects); err != nil { + return err + } + // TimeoutSeconds must be nil or between 1 and 30 seconds, otherwise, + // return an error + if err := checkTimeoutSeconds(objRaw.Webhooks[i].TimeoutSeconds); err != nil { + return err + } + // AdmissionReviewVersions is required in admissionregistration/v1, if this is not set, + // return an error + if len(objRaw.Webhooks[i].AdmissionReviewVersions) == 0 { + return fmt.Errorf("AdmissionReviewVersions is mandatory for v1 {Mutating,Validating}WebhookConfiguration") + } + } + versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) + } + } + + var headerText string + if g.HeaderFile != "" { + headerBytes, err := ctx.ReadFile(g.HeaderFile) + if err != nil { + return err + } + headerText = string(headerBytes) + } + headerText = strings.ReplaceAll(headerText, " YEAR", " "+g.Year) + + for k, v := range versionedWebhooks { + var fileName string + if k == defaultWebhookVersion { + fileName = "manifests.yaml" + } else { + fileName = fmt.Sprintf("manifests.%s.yaml", k) + } + if err := ctx.WriteYAML(fileName, headerText, v, genall.WithTransform(genall.TransformRemoveCreationTimestamp)); err != nil { + return err + } + } + return nil +} + +func checkSideEffectsForV1(sideEffects *admissionregv1.SideEffectClass) error { + if sideEffects == nil { + return fmt.Errorf("SideEffects is required for creating v1 {Mutating,Validating}WebhookConfiguration") + } + if *sideEffects == admissionregv1.SideEffectClassUnknown || + *sideEffects == admissionregv1.SideEffectClassSome { + return fmt.Errorf("SideEffects should not be set to `Some` or `Unknown` for v1 {Mutating,Validating}WebhookConfiguration") + } + return nil +} + +func checkTimeoutSeconds(timeoutSeconds *int32) error { + if timeoutSeconds != nil && (*timeoutSeconds < 1 || *timeoutSeconds > 30) { + return fmt.Errorf("TimeoutSeconds must be between 1 and 30 seconds") + } + return nil +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go new file mode 100644 index 000000000..53ce42f59 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go @@ -0,0 +1,149 @@ +//go:build !ignore_autogenerated + +/* +Copyright2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by helpgen. DO NOT EDIT. + +package webhook + +import ( + "sigs.k8s.io/controller-tools/pkg/markers" +) + +func (Config) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "Webhook", + DetailedHelp: markers.DetailedHelp{ + Summary: "specifies how a webhook should be served.", + Details: "It specifies only the details that are intrinsic to the application serving\nit (e.g. the resources it can handle, or the path it serves on).", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Mutating": { + Summary: "marks this as a mutating webhook (it's validating only if false)", + Details: "Mutating webhooks are allowed to change the object in their response,\nand are called *before* all validating webhooks. Mutating webhooks may\nchoose to reject an object, similarly to a validating webhook.", + }, + "FailurePolicy": { + Summary: "specifies what should happen if the API server cannot reach the webhook.", + Details: "It may be either \"ignore\" (to skip the webhook and continue on) or \"fail\" (to reject\nthe object in question).", + }, + "MatchPolicy": { + Summary: "defines how the \"rules\" list is used to match incoming requests.", + Details: "Allowed values are \"Exact\" (match only if it exactly matches the specified rule)\nor \"Equivalent\" (match a request if it modifies a resource listed in rules, even via another API group or version).", + }, + "SideEffects": { + Summary: "specify whether calling the webhook will have side effects.", + Details: "This has an impact on dry runs and `kubectl diff`: if the sideEffect is \"Unknown\" (the default) or \"Some\", then\nthe API server will not call the webhook on a dry-run request and fails instead.\nIf the value is \"None\", then the webhook has no side effects and the API server will call it on dry-run.\nIf the value is \"NoneOnDryRun\", then the webhook is responsible for inspecting the \"dryRun\" property of the\nAdmissionReview sent in the request, and avoiding side effects if that value is \"true.\"", + }, + "TimeoutSeconds": { + Summary: "allows configuring how long the API server should wait for a webhook to respond before treating the call as a failure.", + Details: "If the timeout expires before the webhook responds, the webhook call will be ignored or the API call will be rejected based on the failure policy.\nThe timeout value must be between 1 and 30 seconds.\nThe timeout for an admission webhook defaults to 10 seconds.", + }, + "Groups": { + Summary: "specifies the API groups that this webhook receives requests for.", + Details: "", + }, + "Resources": { + Summary: "specifies the API resources that this webhook receives requests for.", + Details: "", + }, + "Verbs": { + Summary: "specifies the Kubernetes API verbs that this webhook receives requests for.", + Details: "Only modification-like verbs may be specified.\nMay be \"create\", \"update\", \"delete\", \"connect\", or \"*\" (for all).", + }, + "Versions": { + Summary: "specifies the API versions that this webhook receives requests for.", + Details: "", + }, + "Name": { + Summary: "indicates the name of this webhook configuration. Should be a domain with at least three segments separated by dots", + Details: "", + }, + "ServiceName": { + Summary: "indicates the name of the K8s Service the webhook uses.", + Details: "", + }, + "ServiceNamespace": { + Summary: "indicates the namespace of the K8s Service the webhook uses.", + Details: "", + }, + "Path": { + Summary: "specifies that path that the API server should connect to this webhook on. Must be", + Details: "prefixed with a '/validate-' or '/mutate-' depending on the type, and followed by\n$GROUP-$VERSION-$KIND where all values are lower-cased and the periods in the group\nare substituted for hyphens. For example, a validating webhook path for type\nbatch.tutorial.kubebuilder.io/v1,Kind=CronJob would be\n/validate-batch-tutorial-kubebuilder-io-v1-cronjob", + }, + "ServicePort": { + Summary: "indicates the port of the K8s Service the webhook uses", + Details: "", + }, + "WebhookVersions": { + Summary: "specifies the target API versions of the {Mutating,Validating}WebhookConfiguration objects", + Details: "itself to generate. The only supported value is v1. Defaults to v1.", + }, + "AdmissionReviewVersions": { + Summary: "is an ordered list of preferred `AdmissionReview`", + Details: "versions the Webhook expects.", + }, + "ReinvocationPolicy": { + Summary: "allows mutating webhooks to request reinvocation after other mutations", + Details: "To allow mutating admission plugins to observe changes made by other plugins,\nbuilt-in mutating admission plugins are re-run if a mutating webhook modifies\nan object, and mutating webhooks can specify a reinvocationPolicy to control\nwhether they are reinvoked as well.", + }, + "URL": { + Summary: "allows mutating webhooks configuration to specify an external URL when generating", + Details: "the manifests, instead of using the internal service communication. Should be in format of\nhttps://address:port/path\nWhen this option is specified, the serviceConfig.Service is removed from webhook the manifest.\nThe URL configuration should be between quotes.\n`url` cannot be specified when `path` is specified.", + }, + }, + } +} + +func (Generator) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "generates (partial) {Mutating,Validating}WebhookConfiguration objects.", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "HeaderFile": { + Summary: "specifies the header text (e.g. license) to prepend to generated files.", + Details: "", + }, + "Year": { + Summary: "specifies the year to substitute for \" YEAR\" in the header file.", + Details: "", + }, + }, + } +} + +func (WebhookConfig) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "", + DetailedHelp: markers.DetailedHelp{ + Summary: "", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{ + "Mutating": { + Summary: "marks this as a mutating webhook (it's validating only if false)", + Details: "Mutating webhooks are allowed to change the object in their response,\nand are called *before* all validating webhooks. Mutating webhooks may\nchoose to reject an object, similarly to a validating webhook.", + }, + "Name": { + Summary: "indicates the name of the K8s MutatingWebhookConfiguration or ValidatingWebhookConfiguration object.", + Details: "", + }, + }, + } +} diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/LICENSE b/vendor/sigs.k8s.io/structured-merge-diff/v6/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/doc.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/doc.go new file mode 100644 index 000000000..9081ccbc7 --- /dev/null +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/doc.go @@ -0,0 +1,28 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package schema defines a targeted schema language which allows one to +// represent all the schema information necessary to perform "structured" +// merges and diffs. +// +// Due to the targeted nature of the data model, the schema language can fit in +// just a few hundred lines of go code, making it much more understandable and +// concise than e.g. OpenAPI. +// +// This schema was derived by observing the API objects used by Kubernetes, and +// formalizing a model which allows certain operations ("apply") to be more +// well defined. It is currently missing one feature: one-of ("unions"). +package schema diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go new file mode 100644 index 000000000..5d3707a5b --- /dev/null +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go @@ -0,0 +1,375 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package schema + +import ( + "sync" +) + +// Schema is a list of named types. +// +// Schema types are indexed in a map before the first search so this type +// should be considered immutable. +type Schema struct { + Types []TypeDef `yaml:"types,omitempty"` + + once sync.Once + m map[string]TypeDef + + lock sync.Mutex + // Cached results of resolving type references to atoms. Only stores + // type references which require fields of Atom to be overriden. + resolvedTypes map[TypeRef]Atom +} + +// A TypeSpecifier references a particular type in a schema. +type TypeSpecifier struct { + Type TypeRef `yaml:"type,omitempty"` + Schema Schema `yaml:"schema,omitempty"` +} + +// TypeDef represents a named type in a schema. +type TypeDef struct { + // Top level types should be named. Every type must have a unique name. + Name string `yaml:"name,omitempty"` + + Atom `yaml:"atom,omitempty,inline"` +} + +// TypeRef either refers to a named type or declares an inlined type. +type TypeRef struct { + // Either the name or one member of Atom should be set. + NamedType *string `yaml:"namedType,omitempty"` + Inlined Atom `yaml:",inline,omitempty"` + + // If this reference refers to a map-type or list-type, this field overrides + // the `ElementRelationship` of the referred type when resolved. + // If this field is nil, then it has no effect. + // See `Map` and `List` for more information about `ElementRelationship` + ElementRelationship *ElementRelationship `yaml:"elementRelationship,omitempty"` +} + +// Atom represents the smallest possible pieces of the type system. +// Each set field in the Atom represents a possible type for the object. +// If none of the fields are set, any object will fail validation against the atom. +type Atom struct { + *Scalar `yaml:"scalar,omitempty"` + *List `yaml:"list,omitempty"` + *Map `yaml:"map,omitempty"` +} + +// Scalar (AKA "primitive") represents a type which has a single value which is +// either numeric, string, or boolean, or untyped for any of them. +// +// TODO: split numeric into float/int? Something even more fine-grained? +type Scalar string + +const ( + Numeric = Scalar("numeric") + String = Scalar("string") + Boolean = Scalar("boolean") + Untyped = Scalar("untyped") +) + +// ElementRelationship is an enum of the different possible relationships +// between the elements of container types (maps, lists). +type ElementRelationship string + +const ( + // Associative only applies to lists (see the documentation there). + Associative = ElementRelationship("associative") + // Atomic makes container types (lists, maps) behave + // as scalars / leaf fields + Atomic = ElementRelationship("atomic") + // Separable means the items of the container type have no particular + // relationship (default behavior for maps). + Separable = ElementRelationship("separable") +) + +// Map is a key-value pair. Its default semantics are the same as an +// associative list, but: +// - It is serialized differently: +// map: {"k": {"value": "v"}} +// list: [{"key": "k", "value": "v"}] +// - Keys must be string typed. +// - Keys can't have multiple components. +// +// Optionally, maps may be atomic (for example, imagine representing an RGB +// color value--it doesn't make sense to have different actors own the R and G +// values). +// +// Maps may also represent a type which is composed of a number of different fields. +// Each field has a name and a type. +// +// Fields are indexed in a map before the first search so this type +// should be considered immutable. +type Map struct { + // Each struct field appears exactly once in this list. The order in + // this list defines the canonical field ordering. + Fields []StructField `yaml:"fields,omitempty"` + + // A Union is a grouping of fields with special rules. It may refer to + // one or more fields in the above list. A given field from the above + // list may be referenced in exactly 0 or 1 places in the below list. + // One can have multiple unions in the same struct, but the fields can't + // overlap between unions. + Unions []Union `yaml:"unions,omitempty"` + + // ElementType is the type of the structs's unknown fields. + ElementType TypeRef `yaml:"elementType,omitempty"` + + // ElementRelationship states the relationship between the map's items. + // * `separable` (or unset) implies that each element is 100% independent. + // * `atomic` implies that all elements depend on each other, and this + // is effectively a scalar / leaf field; it doesn't make sense for + // separate actors to set the elements. Example: an RGB color struct; + // it would never make sense to "own" only one component of the + // color. + // The default behavior for maps is `separable`; it's permitted to + // leave this unset to get the default behavior. + ElementRelationship ElementRelationship `yaml:"elementRelationship,omitempty"` + + once sync.Once + m map[string]StructField +} + +// FindField is a convenience function that returns the referenced StructField, +// if it exists, or (nil, false) if it doesn't. +func (m *Map) FindField(name string) (StructField, bool) { + m.once.Do(func() { + m.m = make(map[string]StructField, len(m.Fields)) + for _, field := range m.Fields { + m.m[field.Name] = field + } + }) + sf, ok := m.m[name] + return sf, ok +} + +// CopyInto this instance of Map into the other +// If other is nil this method does nothing. +// If other is already initialized, overwrites it with this instance +// Warning: Not thread safe +func (m *Map) CopyInto(dst *Map) { + if dst == nil { + return + } + + // Map type is considered immutable so sharing references + dst.Fields = m.Fields + dst.ElementType = m.ElementType + dst.Unions = m.Unions + dst.ElementRelationship = m.ElementRelationship + + if m.m != nil { + // If cache is non-nil then the once token had been consumed. + // Must reset token and use it again to ensure same semantics. + dst.once = sync.Once{} + dst.once.Do(func() { + dst.m = m.m + }) + } +} + +// UnionFields are mapping between the fields that are part of the union and +// their discriminated value. The discriminated value has to be set, and +// should not conflict with other discriminated value in the list. +type UnionField struct { + // FieldName is the name of the field that is part of the union. This + // is the serialized form of the field. + FieldName string `yaml:"fieldName"` + // Discriminatorvalue is the value of the discriminator to + // select that field. If the union doesn't have a discriminator, + // this field is ignored. + DiscriminatorValue string `yaml:"discriminatorValue"` +} + +// Union, or oneof, means that only one of multiple fields of a structure can be +// set at a time. Setting the discriminator helps clearing oher fields: +// - If discriminator changed to non-nil, and a new field has been added +// that doesn't match, an error is returned, +// - If discriminator hasn't changed and two fields or more are set, an +// error is returned, +// - If discriminator changed to non-nil, all other fields but the +// discriminated one will be cleared, +// - Otherwise, If only one field is left, update discriminator to that value. +type Union struct { + // Discriminator, if present, is the name of the field that + // discriminates fields in the union. The mapping between the value of + // the discriminator and the field is done by using the Fields list + // below. + Discriminator *string `yaml:"discriminator,omitempty"` + + // DeduceInvalidDiscriminator indicates if the discriminator + // should be updated automatically based on the fields set. This + // typically defaults to false since we don't want to deduce by + // default (the behavior exists to maintain compatibility on + // existing types and shouldn't be used for new types). + DeduceInvalidDiscriminator bool `yaml:"deduceInvalidDiscriminator,omitempty"` + + // This is the list of fields that belong to this union. All the + // fields present in here have to be part of the parent + // structure. Discriminator (if oneOf has one), is NOT included in + // this list. The value for field is how we map the name of the field + // to actual value for discriminator. + Fields []UnionField `yaml:"fields,omitempty"` +} + +// StructField pairs a field name with a field type. +type StructField struct { + // Name is the field name. + Name string `yaml:"name,omitempty"` + // Type is the field type. + Type TypeRef `yaml:"type,omitempty"` + // Default value for the field, nil if not present. + Default interface{} `yaml:"default,omitempty"` +} + +// List represents a type which contains a zero or more elements, all of the +// same subtype. Lists may be either associative: each element is more or less +// independent and could be managed by separate entities in the system; or +// atomic, where the elements are heavily dependent on each other: it is not +// sensible to change one element without considering the ramifications on all +// the other elements. +type List struct { + // ElementType is the type of the list's elements. + ElementType TypeRef `yaml:"elementType,omitempty"` + + // ElementRelationship states the relationship between the list's elements + // and must have one of these values: + // * `atomic`: the list is treated as a single entity, like a scalar. + // * `associative`: + // - If the list element is a scalar, the list is treated as a set. + // - If the list element is a map, the list is treated as a map. + // There is no default for this value for lists; all schemas must + // explicitly state the element relationship for all lists. + ElementRelationship ElementRelationship `yaml:"elementRelationship,omitempty"` + + // Iff ElementRelationship is `associative`, and the element type is + // map, then Keys must have non-zero length, and it lists the fields + // of the element's map type which are to be used as the keys of the + // list. + // + // TODO: change this to "non-atomic struct" above and make the code reflect this. + // + // Each key must refer to a single field name (no nesting, not JSONPath). + Keys []string `yaml:"keys,omitempty"` +} + +// FindNamedType is a convenience function that returns the referenced TypeDef, +// if it exists, or (nil, false) if it doesn't. +func (s *Schema) FindNamedType(name string) (TypeDef, bool) { + s.once.Do(func() { + s.m = make(map[string]TypeDef, len(s.Types)) + for _, t := range s.Types { + s.m[t.Name] = t + } + }) + t, ok := s.m[name] + return t, ok +} + +func (s *Schema) resolveNoOverrides(tr TypeRef) (Atom, bool) { + result := Atom{} + + if tr.NamedType != nil { + t, ok := s.FindNamedType(*tr.NamedType) + if !ok { + return Atom{}, false + } + + result = t.Atom + } else { + result = tr.Inlined + } + + return result, true +} + +// Resolve is a convenience function which returns the atom referenced, whether +// it is inline or named. Returns (Atom{}, false) if the type can't be resolved. +// +// This allows callers to not care about the difference between a (possibly +// inlined) reference and a definition. +func (s *Schema) Resolve(tr TypeRef) (Atom, bool) { + // If this is a plain reference with no overrides, just return the type + if tr.ElementRelationship == nil { + return s.resolveNoOverrides(tr) + } + + s.lock.Lock() + defer s.lock.Unlock() + + if s.resolvedTypes == nil { + s.resolvedTypes = make(map[TypeRef]Atom) + } + + var result Atom + var exists bool + + // Return cached result if available + // If not, calculate result and cache it + if result, exists = s.resolvedTypes[tr]; !exists { + if result, exists = s.resolveNoOverrides(tr); exists { + // Allow field-level electives to override the referred type's modifiers + switch { + case result.Map != nil: + mapCopy := Map{} + result.Map.CopyInto(&mapCopy) + mapCopy.ElementRelationship = *tr.ElementRelationship + result.Map = &mapCopy + case result.List != nil: + listCopy := *result.List + listCopy.ElementRelationship = *tr.ElementRelationship + result.List = &listCopy + case result.Scalar != nil: + return Atom{}, false + default: + return Atom{}, false + } + } else { + return Atom{}, false + } + + // Save result. If it is nil, that is also recorded as not existing. + s.resolvedTypes[tr] = result + } + + return result, true +} + +// Clones this instance of Schema into the other +// If other is nil this method does nothing. +// If other is already initialized, overwrites it with this instance +// Warning: Not thread safe +func (s *Schema) CopyInto(dst *Schema) { + if dst == nil { + return + } + + // Schema type is considered immutable so sharing references + dst.Types = s.Types + + if s.m != nil { + // If cache is non-nil then the once token had been consumed. + // Must reset token and use it again to ensure same semantics. + dst.once = sync.Once{} + dst.once.Do(func() { + dst.m = s.m + }) + } +} diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go new file mode 100644 index 000000000..b668eff83 --- /dev/null +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go @@ -0,0 +1,202 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package schema + +import "reflect" + +// Equals returns true iff the two Schemas are equal. +func (a *Schema) Equals(b *Schema) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + + if len(a.Types) != len(b.Types) { + return false + } + for i := range a.Types { + if !a.Types[i].Equals(&b.Types[i]) { + return false + } + } + return true +} + +// Equals returns true iff the two TypeRefs are equal. +// +// Note that two typerefs that have an equivalent type but where one is +// inlined and the other is named, are not considered equal. +func (a *TypeRef) Equals(b *TypeRef) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if (a.NamedType == nil) != (b.NamedType == nil) { + return false + } + if a.NamedType != nil { + if *a.NamedType != *b.NamedType { + return false + } + //return true + } + if a.ElementRelationship != b.ElementRelationship { + return false + } + return a.Inlined.Equals(&b.Inlined) +} + +// Equals returns true iff the two TypeDefs are equal. +func (a *TypeDef) Equals(b *TypeDef) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if a.Name != b.Name { + return false + } + return a.Atom.Equals(&b.Atom) +} + +// Equals returns true iff the two Atoms are equal. +func (a *Atom) Equals(b *Atom) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if (a.Scalar == nil) != (b.Scalar == nil) { + return false + } + if (a.List == nil) != (b.List == nil) { + return false + } + if (a.Map == nil) != (b.Map == nil) { + return false + } + switch { + case a.Scalar != nil: + return *a.Scalar == *b.Scalar + case a.List != nil: + return a.List.Equals(b.List) + case a.Map != nil: + return a.Map.Equals(b.Map) + } + return true +} + +// Equals returns true iff the two Maps are equal. +func (a *Map) Equals(b *Map) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if !a.ElementType.Equals(&b.ElementType) { + return false + } + if a.ElementRelationship != b.ElementRelationship { + return false + } + if len(a.Fields) != len(b.Fields) { + return false + } + for i := range a.Fields { + if !a.Fields[i].Equals(&b.Fields[i]) { + return false + } + } + if len(a.Unions) != len(b.Unions) { + return false + } + for i := range a.Unions { + if !a.Unions[i].Equals(&b.Unions[i]) { + return false + } + } + return true +} + +// Equals returns true iff the two Unions are equal. +func (a *Union) Equals(b *Union) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if (a.Discriminator == nil) != (b.Discriminator == nil) { + return false + } + if a.Discriminator != nil { + if *a.Discriminator != *b.Discriminator { + return false + } + } + if a.DeduceInvalidDiscriminator != b.DeduceInvalidDiscriminator { + return false + } + if len(a.Fields) != len(b.Fields) { + return false + } + for i := range a.Fields { + if !a.Fields[i].Equals(&b.Fields[i]) { + return false + } + } + return true +} + +// Equals returns true iff the two UnionFields are equal. +func (a *UnionField) Equals(b *UnionField) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if a.FieldName != b.FieldName { + return false + } + if a.DiscriminatorValue != b.DiscriminatorValue { + return false + } + return true +} + +// Equals returns true iff the two StructFields are equal. +func (a *StructField) Equals(b *StructField) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if a.Name != b.Name { + return false + } + if !reflect.DeepEqual(a.Default, b.Default) { + return false + } + return a.Type.Equals(&b.Type) +} + +// Equals returns true iff the two Lists are equal. +func (a *List) Equals(b *List) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if !a.ElementType.Equals(&b.ElementType) { + return false + } + if a.ElementRelationship != b.ElementRelationship { + return false + } + if len(a.Keys) != len(b.Keys) { + return false + } + for i := range a.Keys { + if a.Keys[i] != b.Keys[i] { + return false + } + } + return true +} diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go new file mode 100644 index 000000000..6eb6c36df --- /dev/null +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go @@ -0,0 +1,165 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package schema + +// SchemaSchemaYAML is a schema against which you can validate other schemas. +// It will validate itself. It can be unmarshalled into a Schema type. +var SchemaSchemaYAML = `types: +- name: schema + map: + fields: + - name: types + type: + list: + elementRelationship: associative + elementType: + namedType: typeDef + keys: + - name +- name: typeDef + map: + fields: + - name: name + type: + scalar: string + - name: scalar + type: + scalar: string + - name: map + type: + namedType: map + - name: list + type: + namedType: list + - name: untyped + type: + namedType: untyped +- name: typeRef + map: + fields: + - name: namedType + type: + scalar: string + - name: scalar + type: + scalar: string + - name: map + type: + namedType: map + - name: list + type: + namedType: list + - name: untyped + type: + namedType: untyped + - name: elementRelationship + type: + scalar: string +- name: scalar + scalar: string +- name: map + map: + fields: + - name: fields + type: + list: + elementType: + namedType: structField + elementRelationship: associative + keys: [ "name" ] + - name: unions + type: + list: + elementType: + namedType: union + elementRelationship: atomic + - name: elementType + type: + namedType: typeRef + - name: elementRelationship + type: + scalar: string +- name: unionField + map: + fields: + - name: fieldName + type: + scalar: string + - name: discriminatorValue + type: + scalar: string +- name: union + map: + fields: + - name: discriminator + type: + scalar: string + - name: deduceInvalidDiscriminator + type: + scalar: boolean + - name: fields + type: + list: + elementRelationship: associative + elementType: + namedType: unionField + keys: + - fieldName +- name: structField + map: + fields: + - name: name + type: + scalar: string + - name: type + type: + namedType: typeRef + - name: default + type: + namedType: __untyped_atomic_ +- name: list + map: + fields: + - name: elementType + type: + namedType: typeRef + - name: elementRelationship + type: + scalar: string + - name: keys + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: untyped + map: + fields: + - name: elementRelationship + type: + scalar: string +- name: __untyped_atomic_ + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic +`