From b55f0818cc7ccbbd2eb99bee5bbf7a2427498c56 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Dec 2024 23:56:23 +0000 Subject: [PATCH] Bump github.com/mittwald/go-helm-client from 0.12.14 to 0.12.16 Bumps [github.com/mittwald/go-helm-client](https://github.com/mittwald/go-helm-client) from 0.12.14 to 0.12.16. - [Release notes](https://github.com/mittwald/go-helm-client/releases) - [Commits](https://github.com/mittwald/go-helm-client/compare/v0.12.14...v0.12.16) --- updated-dependencies: - dependency-name: github.com/mittwald/go-helm-client dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- go.mod | 33 +- go.sum | 72 +- vendor/github.com/Microsoft/hcsshim/LICENSE | 21 - .../hcsshim/osversion/osversion_windows.go | 59 - .../osversion/platform_compat_windows.go | 35 - .../hcsshim/osversion/windowsbuilds.go | 84 - .../archive/compression/compression.go | 2 +- .../containerd/containerd/content/content.go | 6 + .../containerd/containerd/content/helpers.go | 15 +- .../containerd/content/local/store.go | 5 +- .../containerd/content/local/writer.go | 5 +- .../containerd/containerd/errdefs/errors.go | 94 +- .../containerd/containerd/filters/filter.go | 2 +- .../containerd/containerd/images/diffid.go | 2 +- .../containerd/containerd/images/handlers.go | 7 +- .../containerd/containerd/images/image.go | 12 +- .../containerd/images/mediatypes.go | 2 +- .../containerd/reference/docker/helpers.go | 58 - .../containerd/reference/docker/normalize.go | 196 -- .../containerd/reference/docker/reference.go | 453 --- .../containerd/reference/docker/regexp.go | 191 -- .../containerd/reference/docker/sort.go | 73 - .../containerd/reference/reference.go | 39 +- .../containerd/remotes/docker/auth/fetch.go | 2 +- .../containerd/remotes/docker/authorizer.go | 21 +- .../containerd/remotes/docker/converter.go | 2 +- .../remotes/docker/converter_fuzz.go | 2 +- .../containerd/remotes/docker/fetcher.go | 7 +- .../containerd/remotes/docker/fetcher_fuzz.go | 7 - .../containerd/remotes/docker/handler.go | 2 +- .../remotes/docker/httpreadseeker.go | 3 +- .../containerd/remotes/docker/pusher.go | 116 +- .../containerd/remotes/docker/resolver.go | 77 +- .../remotes/docker/schema1/converter.go | 11 +- .../containerd/containerd/remotes/handlers.go | 9 +- .../containerd/containerd/version/version.go | 2 +- .../containerd/errdefs}/LICENSE | 18 +- .../github.com/containerd/errdefs/README.md | 13 + .../github.com/containerd/errdefs/errors.go | 443 +++ .../github.com/containerd/errdefs/resolve.go | 147 + .../containerd/platforms/.gitattributes | 1 + .../containerd/platforms/.golangci.yml | 30 + .../github.com/containerd/platforms/LICENSE | 191 ++ .../github.com/containerd/platforms/README.md | 32 + .../{containerd => }/platforms/compare.go | 0 .../{containerd => }/platforms/cpuinfo.go | 2 +- .../platforms/cpuinfo_linux.go | 13 +- .../platforms/cpuinfo_other.go | 6 +- .../{containerd => }/platforms/database.go | 0 .../{containerd => }/platforms/defaults.go | 6 +- .../platforms/defaults_darwin.go | 0 .../platforms/defaults_freebsd.go | 0 .../platforms/defaults_unix.go | 0 .../platforms/defaults_windows.go | 15 +- .../github.com/containerd/platforms/errors.go | 30 + .../platforms/platform_compat_windows.go | 78 + .../{containerd => }/platforms/platforms.go | 96 +- .../platforms/platforms_other.go | 4 - .../platforms/platforms_windows.go | 8 - .../cyphar/filepath-securejoin/CHANGELOG.md | 42 +- .../cyphar/filepath-securejoin/README.md | 3 +- .../cyphar/filepath-securejoin/VERSION | 2 +- .../cyphar/filepath-securejoin/doc.go | 39 + .../cyphar/filepath-securejoin/join.go | 21 +- .../cyphar/filepath-securejoin/mkdir_linux.go | 102 +- .../cyphar/filepath-securejoin/open_linux.go | 14 +- .../filepath-securejoin/openat2_linux.go | 33 +- .../filepath-securejoin/procfs_linux.go | 150 +- .../testing_mocks_linux.go | 68 - .../cyphar/filepath-securejoin/vfs.go | 24 +- .../distribution/reference/README.md | 2 +- .../distribution/reference/normalize.go | 59 +- .../distribution/reference/reference.go | 44 +- .../mittwald/go-helm-client/client.go | 8 +- vendor/go.starlark.net/LICENSE | 29 - .../internal/compile/compile.go | 1927 ------------ .../internal/compile/serial.go | 399 --- .../go.starlark.net/internal/spell/spell.go | 115 - vendor/go.starlark.net/resolve/binding.go | 74 - vendor/go.starlark.net/resolve/resolve.go | 981 ------ vendor/go.starlark.net/starlark/debug.go | 42 - vendor/go.starlark.net/starlark/empty.s | 3 - vendor/go.starlark.net/starlark/eval.go | 1672 ---------- vendor/go.starlark.net/starlark/hashtable.go | 442 --- vendor/go.starlark.net/starlark/int.go | 459 --- .../go.starlark.net/starlark/int_generic.go | 33 - .../go.starlark.net/starlark/int_posix64.go | 89 - vendor/go.starlark.net/starlark/interp.go | 704 ----- vendor/go.starlark.net/starlark/library.go | 2455 --------------- vendor/go.starlark.net/starlark/profile.go | 449 --- vendor/go.starlark.net/starlark/unpack.go | 355 --- vendor/go.starlark.net/starlark/value.go | 1613 ---------- .../go.starlark.net/starlarkstruct/module.go | 43 - .../go.starlark.net/starlarkstruct/struct.go | 282 -- vendor/go.starlark.net/syntax/grammar.txt | 129 - vendor/go.starlark.net/syntax/options.go | 63 - vendor/go.starlark.net/syntax/parse.go | 1057 ------- vendor/go.starlark.net/syntax/quote.go | 309 -- vendor/go.starlark.net/syntax/scan.go | 1124 ------- vendor/go.starlark.net/syntax/syntax.go | 529 ---- vendor/go.starlark.net/syntax/walk.go | 161 - vendor/golang.org/x/sys/unix/ioctl_linux.go | 96 + vendor/golang.org/x/sys/unix/mkerrors.sh | 12 + vendor/golang.org/x/sys/unix/syscall_linux.go | 1 + .../x/sys/unix/syscall_zos_s390x.go | 104 +- vendor/golang.org/x/sys/unix/zerrors_linux.go | 31 + .../x/sys/unix/zerrors_linux_386.go | 20 + .../x/sys/unix/zerrors_linux_amd64.go | 20 + .../x/sys/unix/zerrors_linux_arm.go | 20 + .../x/sys/unix/zerrors_linux_arm64.go | 21 + .../x/sys/unix/zerrors_linux_loong64.go | 20 + .../x/sys/unix/zerrors_linux_mips.go | 20 + .../x/sys/unix/zerrors_linux_mips64.go | 20 + .../x/sys/unix/zerrors_linux_mips64le.go | 20 + .../x/sys/unix/zerrors_linux_mipsle.go | 20 + .../x/sys/unix/zerrors_linux_ppc.go | 20 + .../x/sys/unix/zerrors_linux_ppc64.go | 20 + .../x/sys/unix/zerrors_linux_ppc64le.go | 20 + .../x/sys/unix/zerrors_linux_riscv64.go | 20 + .../x/sys/unix/zerrors_linux_s390x.go | 20 + .../x/sys/unix/zerrors_linux_sparc64.go | 20 + .../golang.org/x/sys/unix/zsyscall_linux.go | 10 + .../x/sys/unix/ztypes_darwin_amd64.go | 60 + .../x/sys/unix/ztypes_darwin_arm64.go | 60 + vendor/golang.org/x/sys/unix/ztypes_linux.go | 138 +- .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 6 + .../x/sys/windows/syscall_windows.go | 36 +- .../golang.org/x/sys/windows/types_windows.go | 127 + .../x/sys/windows/zsyscall_windows.go | 71 + vendor/golang.org/x/term/README.md | 11 +- vendor/gopkg.in/yaml.v2/.travis.yml | 17 - vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - vendor/gopkg.in/yaml.v2/NOTICE | 13 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/apic.go | 744 ----- vendor/gopkg.in/yaml.v2/decode.go | 815 ----- vendor/gopkg.in/yaml.v2/emitterc.go | 1685 ---------- vendor/gopkg.in/yaml.v2/encode.go | 390 --- vendor/gopkg.in/yaml.v2/parserc.go | 1095 ------- vendor/gopkg.in/yaml.v2/readerc.go | 412 --- vendor/gopkg.in/yaml.v2/resolve.go | 258 -- vendor/gopkg.in/yaml.v2/scannerc.go | 2711 ----------------- vendor/gopkg.in/yaml.v2/sorter.go | 113 - vendor/gopkg.in/yaml.v2/writerc.go | 26 - vendor/gopkg.in/yaml.v2/yaml.go | 478 --- vendor/gopkg.in/yaml.v2/yamlh.go | 739 ----- vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 -- .../helm/v3/internal/resolver/resolver.go | 2 +- .../helm/v3/internal/third_party/dep/fs/fs.go | 2 +- .../helm.sh/helm/v3/internal/tlsutil/tls.go | 2 +- vendor/helm.sh/helm/v3/pkg/action/hooks.go | 3 +- vendor/helm.sh/helm/v3/pkg/action/install.go | 8 +- vendor/helm.sh/helm/v3/pkg/action/upgrade.go | 2 +- .../helm/v3/pkg/chart/loader/archive.go | 2 +- .../helm/v3/pkg/chartutil/dependencies.go | 2 +- .../helm.sh/helm/v3/pkg/downloader/manager.go | 2 +- vendor/helm.sh/helm/v3/pkg/engine/engine.go | 2 +- .../helm.sh/helm/v3/pkg/engine/lookup_func.go | 2 +- .../helm.sh/helm/v3/pkg/helmpath/lazypath.go | 2 +- vendor/helm.sh/helm/v3/pkg/ignore/doc.go | 2 +- vendor/helm.sh/helm/v3/pkg/kube/client.go | 4 +- vendor/helm.sh/helm/v3/pkg/kube/ready.go | 2 +- vendor/helm.sh/helm/v3/pkg/registry/util.go | 3 +- vendor/helm.sh/helm/v3/pkg/release/status.go | 4 +- vendor/helm.sh/helm/v3/pkg/repo/index.go | 6 +- .../helm.sh/helm/v3/pkg/storage/driver/sql.go | 12 +- vendor/helm.sh/helm/v3/pkg/strvals/parser.go | 2 +- vendor/helm.sh/helm/v3/pkg/time/time.go | 2 +- .../k8s.io/cli-runtime/pkg/printers/json.go | 5 +- .../cli-runtime/pkg/printers/jsonpath.go | 3 +- .../k8s.io/cli-runtime/pkg/printers/name.go | 3 +- .../cli-runtime/pkg/printers/template.go | 3 +- .../k8s.io/cli-runtime/pkg/printers/yaml.go | 5 +- .../cli-runtime/pkg/resource/builder.go | 4 +- .../pkg/resource/query_param_verifier.go | 2 +- vendor/modules.txt | 66 +- .../builtins/HelmChartInflationGenerator.go | 10 +- .../internal/builtins/SortOrderTransformer.go | 3 + .../builtinpluginconsts/namereference.go | 7 + .../api/internal/plugins/fnplugin/fnplugin.go | 1 - .../api/internal/target/kusttarget.go | 5 +- .../kustomize/api/resource/factory.go | 5 +- .../kustomize/api/types/helmchartargs.go | 6 + .../kustomize/api/types/kustomization.go | 2 + .../kustomize/api/types/pluginconfig.go | 2 +- .../kustomize/api/types/pluginrestrictions.go | 2 - .../kyaml/fn/runtime/container/container.go | 2 +- .../fn/runtime/runtimeutil/functiontypes.go | 14 - .../kyaml/fn/runtime/starlark/context.go | 79 - .../kyaml/fn/runtime/starlark/doc.go | 36 - .../kyaml/fn/runtime/starlark/starlark.go | 180 -- .../github.com/qri-io/starlib/util/LICENSE | 21 - .../github.com/qri-io/starlib/util/doc.go | 25 - .../github.com/qri-io/starlib/util/util.go | 275 -- .../kustomize/kyaml/kio/filters/filters.go | 210 -- .../kustomize/kyaml/kio/filters/fmtr.go | 314 -- .../kustomize/kyaml/kio/filters/grep.go | 117 - .../kustomize/kyaml/kio/filters/local.go | 38 - .../kustomize/kyaml/kio/filters/merge.go | 86 - .../kustomize/kyaml/kio/filters/merge3.go | 317 -- .../kustomize/kyaml/kio/filters/modify.go | 4 - .../kyaml/kio/filters/stripcomments.go | 32 - .../kustomize/kyaml/kio/ignorefilesmatcher.go | 2 +- .../kyaml/openapi/kustomizationapi/swagger.go | 2 +- .../kustomize/kyaml/openapi/openapi.go | 2 +- .../kustomize/kyaml/runfn/runfn.go | 41 - .../sigs.k8s.io/kustomize/kyaml/yaml/alias.go | 2 +- .../kustomize/kyaml/yaml/merge3/merge3.go | 45 - .../kustomize/kyaml/yaml/merge3/visitor.go | 172 -- 209 files changed, 2803 insertions(+), 29321 deletions(-) delete mode 100644 vendor/github.com/Microsoft/hcsshim/LICENSE delete mode 100644 vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go delete mode 100644 vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go delete mode 100644 vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go delete mode 100644 vendor/github.com/containerd/containerd/reference/docker/helpers.go delete mode 100644 vendor/github.com/containerd/containerd/reference/docker/normalize.go delete mode 100644 vendor/github.com/containerd/containerd/reference/docker/reference.go delete mode 100644 vendor/github.com/containerd/containerd/reference/docker/regexp.go delete mode 100644 vendor/github.com/containerd/containerd/reference/docker/sort.go rename vendor/{gopkg.in/yaml.v2 => github.com/containerd/errdefs}/LICENSE (93%) create mode 100644 vendor/github.com/containerd/errdefs/README.md create mode 100644 vendor/github.com/containerd/errdefs/errors.go create mode 100644 vendor/github.com/containerd/errdefs/resolve.go create mode 100644 vendor/github.com/containerd/platforms/.gitattributes create mode 100644 vendor/github.com/containerd/platforms/.golangci.yml create mode 100644 vendor/github.com/containerd/platforms/LICENSE create mode 100644 vendor/github.com/containerd/platforms/README.md rename vendor/github.com/containerd/{containerd => }/platforms/compare.go (100%) rename vendor/github.com/containerd/{containerd => }/platforms/cpuinfo.go (96%) rename vendor/github.com/containerd/{containerd => }/platforms/cpuinfo_linux.go (94%) rename vendor/github.com/containerd/{containerd => }/platforms/cpuinfo_other.go (94%) rename vendor/github.com/containerd/{containerd => }/platforms/database.go (100%) rename vendor/github.com/containerd/{containerd => }/platforms/defaults.go (81%) rename vendor/github.com/containerd/{containerd => }/platforms/defaults_darwin.go (100%) rename vendor/github.com/containerd/{containerd => }/platforms/defaults_freebsd.go (100%) rename vendor/github.com/containerd/{containerd => }/platforms/defaults_unix.go (100%) rename vendor/github.com/containerd/{containerd => }/platforms/defaults_windows.go (88%) create mode 100644 vendor/github.com/containerd/platforms/errors.go create mode 100644 vendor/github.com/containerd/platforms/platform_compat_windows.go rename vendor/github.com/containerd/{containerd => }/platforms/platforms.go (74%) rename vendor/github.com/containerd/{containerd => }/platforms/platforms_other.go (94%) rename vendor/github.com/containerd/{containerd => }/platforms/platforms_windows.go (85%) create mode 100644 vendor/github.com/cyphar/filepath-securejoin/doc.go delete mode 100644 vendor/github.com/cyphar/filepath-securejoin/testing_mocks_linux.go delete mode 100644 vendor/go.starlark.net/LICENSE delete mode 100644 vendor/go.starlark.net/internal/compile/compile.go delete mode 100644 vendor/go.starlark.net/internal/compile/serial.go delete mode 100644 vendor/go.starlark.net/internal/spell/spell.go delete mode 100644 vendor/go.starlark.net/resolve/binding.go delete mode 100644 vendor/go.starlark.net/resolve/resolve.go delete mode 100644 vendor/go.starlark.net/starlark/debug.go delete mode 100644 vendor/go.starlark.net/starlark/empty.s delete mode 100644 vendor/go.starlark.net/starlark/eval.go delete mode 100644 vendor/go.starlark.net/starlark/hashtable.go delete mode 100644 vendor/go.starlark.net/starlark/int.go delete mode 100644 vendor/go.starlark.net/starlark/int_generic.go delete mode 100644 vendor/go.starlark.net/starlark/int_posix64.go delete mode 100644 vendor/go.starlark.net/starlark/interp.go delete mode 100644 vendor/go.starlark.net/starlark/library.go delete mode 100644 vendor/go.starlark.net/starlark/profile.go delete mode 100644 vendor/go.starlark.net/starlark/unpack.go delete mode 100644 vendor/go.starlark.net/starlark/value.go delete mode 100644 vendor/go.starlark.net/starlarkstruct/module.go delete mode 100644 vendor/go.starlark.net/starlarkstruct/struct.go delete mode 100644 vendor/go.starlark.net/syntax/grammar.txt delete mode 100644 vendor/go.starlark.net/syntax/options.go delete mode 100644 vendor/go.starlark.net/syntax/parse.go delete mode 100644 vendor/go.starlark.net/syntax/quote.go delete mode 100644 vendor/go.starlark.net/syntax/scan.go delete mode 100644 vendor/go.starlark.net/syntax/syntax.go delete mode 100644 vendor/go.starlark.net/syntax/walk.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlprivateh.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/context.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/doc.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/starlark.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/LICENSE delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/doc.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/util.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/filters.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/fmtr.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/grep.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/local.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge3.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/modify.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/stripcomments.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/merge3.go delete mode 100644 vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/visitor.go diff --git a/go.mod b/go.mod index 3bb76c64a..6714a2658 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/NVIDIA/nvidia-container-toolkit v1.17.3 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc github.com/go-logr/logr v1.4.2 - github.com/mittwald/go-helm-client v0.12.14 + github.com/mittwald/go-helm-client v0.12.16 github.com/onsi/ginkgo/v2 v2.22.0 github.com/onsi/gomega v1.35.1 github.com/openshift/api v0.0.0-20241001152557-e415140e5d5f @@ -44,17 +44,18 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.3.0 // indirect github.com/Masterminds/squirrel v1.5.4 // indirect - github.com/Microsoft/hcsshim v0.11.4 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chai2010/gettext-go v1.0.2 // indirect - github.com/containerd/containerd v1.7.12 // indirect + github.com/containerd/containerd v1.7.23 // indirect + github.com/containerd/errdefs v0.3.0 // indirect github.com/containerd/log v0.1.0 // indirect + github.com/containerd/platforms v0.2.1 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect - github.com/cyphar/filepath-securejoin v0.3.1 // indirect - github.com/distribution/reference v0.5.0 // indirect + github.com/cyphar/filepath-securejoin v0.3.4 // indirect + github.com/distribution/reference v0.6.0 // indirect github.com/docker/cli v25.0.1+incompatible // indirect github.com/docker/distribution v2.8.3+incompatible // indirect github.com/docker/docker v25.0.6+incompatible // indirect @@ -145,16 +146,15 @@ require ( go.opentelemetry.io/otel v1.28.0 // indirect go.opentelemetry.io/otel/metric v1.28.0 // indirect go.opentelemetry.io/otel/trace v1.28.0 // indirect - go.starlark.net v0.0.0-20231121155337-90ade8b19d09 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/crypto v0.28.0 // indirect + golang.org/x/crypto v0.31.0 // indirect golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect golang.org/x/net v0.30.0 // indirect golang.org/x/oauth2 v0.23.0 // indirect - golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/term v0.25.0 // indirect - golang.org/x/text v0.19.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/term v0.27.0 // indirect + golang.org/x/text v0.21.0 // indirect golang.org/x/time v0.7.0 // indirect golang.org/x/tools v0.26.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect @@ -163,18 +163,17 @@ require ( google.golang.org/protobuf v1.35.1 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - helm.sh/helm/v3 v3.16.1 // indirect + helm.sh/helm/v3 v3.16.4 // indirect k8s.io/apiserver v0.32.0 // indirect - k8s.io/cli-runtime v0.31.1 // indirect + k8s.io/cli-runtime v0.32.0 // indirect k8s.io/component-base v0.32.0 // indirect k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect - k8s.io/kubectl v0.31.0 // indirect + k8s.io/kubectl v0.31.3 // indirect k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect oras.land/oras-go v1.2.5 // indirect sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect - sigs.k8s.io/kustomize/api v0.17.2 // indirect - sigs.k8s.io/kustomize/kyaml v0.17.1 // indirect + sigs.k8s.io/kustomize/api v0.18.0 // indirect + sigs.k8s.io/kustomize/kyaml v0.18.1 // indirect sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect ) diff --git a/go.sum b/go.sum index b78002cfd..dd8b85822 100644 --- a/go.sum +++ b/go.sum @@ -20,10 +20,10 @@ github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= -github.com/Microsoft/hcsshim v0.11.4 h1:68vKo2VN8DE9AdN4tnkWnmdhqdbpUFM8OF3Airm7fz8= -github.com/Microsoft/hcsshim v0.11.4/go.mod h1:smjE4dvqPX9Zldna+t5FG3rnoHhaB7QYxPRqGcpAD9w= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/Microsoft/hcsshim v0.11.7 h1:vl/nj3Bar/CvJSYo7gIQPyRWc9f3c6IeSNavBTSZNZQ= +github.com/Microsoft/hcsshim v0.11.7/go.mod h1:MV8xMfmECjl5HdO7U/3/hFVnkmSBjAjmA09d4bExKcU= github.com/NVIDIA/go-nvlib v0.7.0 h1:Z/J7skMdLbTiHvomKVsGYsttfQMZj5FwNYIFXhZ4i/c= github.com/NVIDIA/go-nvlib v0.7.0/go.mod h1:9UrsLGx/q1OrENygXjOuM5Ey5KCtiZhbvBlbUIxtGWY= github.com/NVIDIA/k8s-kata-manager v0.2.2 h1:+xVIp4yLfCjZ31Dfrm9LOKo4T47b4g+DV6XkwAqalns= @@ -60,27 +60,31 @@ github.com/chai2010/gettext-go v1.0.2 h1:1Lwwip6Q2QGsAdl/ZKPCwTe9fe0CjlUbqj5bFNS github.com/chai2010/gettext-go v1.0.2/go.mod h1:y+wnP2cHYaVj19NZhYKAwEMH2CI1gNHeQQ+5AjwawxA= github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaDFBM= github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= -github.com/containerd/containerd v1.7.12 h1:+KQsnv4VnzyxWcfO9mlxxELaoztsDEjOuCMPAuPqgU0= -github.com/containerd/containerd v1.7.12/go.mod h1:/5OMpE1p0ylxtEUGY8kuCYkDRzJm9NO1TFMWjUpdevk= +github.com/containerd/containerd v1.7.23 h1:H2CClyUkmpKAGlhQp95g2WXHfLYc7whAuvZGBNYOOwQ= +github.com/containerd/containerd v1.7.23/go.mod h1:7QUzfURqZWCZV7RLNEn1XjUCQLEf0bkaK4GjUaZehxw= github.com/containerd/continuity v0.4.2 h1:v3y/4Yz5jwnvqPKJJ+7Wf93fyWoCB3F5EclWG023MDM= github.com/containerd/continuity v0.4.2/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= +github.com/containerd/errdefs v0.3.0 h1:FSZgGOeK4yuT/+DnF07/Olde/q4KBoMsaamhXxIMDp4= +github.com/containerd/errdefs v0.3.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= -github.com/cyphar/filepath-securejoin v0.3.1 h1:1V7cHiaW+C+39wEfpH6XlLBQo3j/PciWFrgfCLS8XrE= -github.com/cyphar/filepath-securejoin v0.3.1/go.mod h1:F7i41x/9cBF7lzCrVsYs9fuzwRZm4NQsGTBdpp6mETc= +github.com/cyphar/filepath-securejoin v0.3.4 h1:VBWugsJh2ZxJmLFSM06/0qzQyiQX2Qs0ViKrUAcqdZ8= +github.com/cyphar/filepath-securejoin v0.3.4/go.mod h1:8s/MCNJREmFK0H02MF6Ihv1nakJe4L/w3WZLHNkvlYM= 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= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/distribution/v3 v3.0.0-20221208165359-362910506bc2 h1:aBfCb7iqHmDEIp6fBvC/hQUddQfg+3qdYjwzaiP9Hnc= github.com/distribution/distribution/v3 v3.0.0-20221208165359-362910506bc2/go.mod h1:WHNsWjnIn2V1LYOrME7e8KxSeKunYHsxEm4am0BUtcI= -github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0= -github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/cli v25.0.1+incompatible h1:mFpqnrS6Hsm3v1k7Wa/BO23oz0k121MTbTO1lpcGSkU= github.com/docker/cli v25.0.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= @@ -243,14 +247,16 @@ github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQ github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mittwald/go-helm-client v0.12.14 h1:az3GJ4kRmFK609Ic3iHXveNtg92n9jWG0YpKKTIK4oo= -github.com/mittwald/go-helm-client v0.12.14/go.mod h1:2VogAupgnV7FiuoPqtpCYKS/RrMh9fFA3/pD/OmTaLc= +github.com/mittwald/go-helm-client v0.12.16 h1:YTyJX6L0SI/O7HNTG0qDZI2/jyGELxJOQEjvTj4mf6k= +github.com/mittwald/go-helm-client v0.12.16/go.mod h1:PDF7Ra8bmJ2YTNzoehoMMi+gW/EJBk/4TLz7j52rehY= github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.5.0 h1:7r0J1Si3QO/kjRitvSLVVFUjxMEb/YLj6S9FF62JBCU= github.com/moby/spdystream v0.5.0/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/moby/sys/mountinfo v0.6.2 h1:BzJjoreD5BMFNmD9Rus6gdd1pLuecOFPt8wC+Vygl78= github.com/moby/sys/mountinfo v0.6.2/go.mod h1:IJb6JQeOklcdMU9F5xQ8ZALD+CUr5VlGpwtX+VE0rpI= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -384,8 +390,6 @@ go.opentelemetry.io/otel/metric v1.28.0 h1:f0HGvSl1KRAU1DLgLGFjrwVyismPlnuU6JD6b go.opentelemetry.io/otel/metric v1.28.0/go.mod h1:Fb1eVBFZmLVTMb6PPohq3TO9IIhUisDsbJoL/+uQW4s= go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+lkx9g= go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI= -go.starlark.net v0.0.0-20231121155337-90ade8b19d09 h1:hzy3LFnSN8kuQK8h9tHl4ndF6UruMj47OqwqsS+/Ai4= -go.starlark.net v0.0.0-20231121155337-90ade8b19d09/go.mod h1:LcLNIzVOMp4oV+uusnpk+VU+SzXaJakUuBjoCSWH5dM= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -396,8 +400,8 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf 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.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= -golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -419,8 +423,8 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 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.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -431,14 +435,14 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24= -golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= 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.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -475,8 +479,8 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g= -helm.sh/helm/v3 v3.16.1 h1:cER6tI/8PgUAsaJaQCVBUg3VI9KN4oVaZJgY60RIc0c= -helm.sh/helm/v3 v3.16.1/go.mod h1:r+xBHHP20qJeEqtvBXMf7W35QDJnzY/eiEBzt+TfHps= +helm.sh/helm/v3 v3.16.4 h1:rBn/h9MACw+QlhxQTjpl8Ifx+VTWaYsw3rguGBYBzr0= +helm.sh/helm/v3 v3.16.4/go.mod h1:k8QPotUt57wWbi90w3LNmg3/MWcLPigVv+0/X4B8BzA= k8s.io/api v0.32.0 h1:OL9JpbvAU5ny9ga2fb24X8H6xQlVp+aJMFlgtQjR9CE= k8s.io/api v0.32.0/go.mod h1:4LEwHZEf6Q/cG96F3dqR965sYOfmPM7rq81BLgsE0p0= k8s.io/apiextensions-apiserver v0.32.0 h1:S0Xlqt51qzzqjKPxfgX1xh4HBZE+p8KKBq+k2SWNOE0= @@ -485,8 +489,8 @@ k8s.io/apimachinery v0.32.0 h1:cFSE7N3rmEEtv4ei5X6DaJPHHX0C+upp+v5lVPiEwpg= k8s.io/apimachinery v0.32.0/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= k8s.io/apiserver v0.32.0 h1:VJ89ZvQZ8p1sLeiWdRJpRD6oLozNZD2+qVSLi+ft5Qs= k8s.io/apiserver v0.32.0/go.mod h1:HFh+dM1/BE/Hm4bS4nTXHVfN6Z6tFIZPi649n83b4Ag= -k8s.io/cli-runtime v0.31.1 h1:/ZmKhmZ6hNqDM+yf9s3Y4KEYakNXUn5sod2LWGGwCuk= -k8s.io/cli-runtime v0.31.1/go.mod h1:pKv1cDIaq7ehWGuXQ+A//1OIF+7DI+xudXtExMCbe9U= +k8s.io/cli-runtime v0.32.0 h1:dP+OZqs7zHPpGQMCGAhectbHU2SNCuZtIimRKTv2T1c= +k8s.io/cli-runtime v0.32.0/go.mod h1:Mai8ht2+esoDRK5hr861KRy6z0zHsSTYttNVJXgP3YQ= k8s.io/client-go v0.32.0 h1:DimtMcnN/JIKZcrSrstiwvvZvLjG0aSxy8PxN8IChp8= k8s.io/client-go v0.32.0/go.mod h1:boDWvdM1Drk4NJj/VddSLnx59X3OPgwrOo0vGbtq9+8= k8s.io/component-base v0.32.0 h1:d6cWHZkCiiep41ObYQS6IcgzOUQUNpywm39KVYaUqzU= @@ -495,8 +499,8 @@ 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-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y= k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= -k8s.io/kubectl v0.31.0 h1:kANwAAPVY02r4U4jARP/C+Q1sssCcN/1p9Nk+7BQKVg= -k8s.io/kubectl v0.31.0/go.mod h1:pB47hhFypGsaHAPjlwrNbvhXgmuAr01ZBvAIIUaI8d4= +k8s.io/kubectl v0.31.3 h1:3r111pCjPsvnR98oLLxDMwAeM6OPGmPty6gSKaLTQes= +k8s.io/kubectl v0.31.3/go.mod h1:lhMECDCbJN8He12qcKqs2QfmVo9Pue30geovBVpH5fs= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= oras.land/oras-go v1.2.5 h1:XpYuAwAb0DfQsunIyMfeET92emK8km3W4yEzZvUbsTo= @@ -505,10 +509,10 @@ sigs.k8s.io/controller-runtime v0.19.1 h1:Son+Q40+Be3QWb+niBXAg2vFiYWolDjjRfO8hn sigs.k8s.io/controller-runtime v0.19.1/go.mod h1:iRmWllt8IlaLjvTTDLhRBXIEtkCK6hwVBJJsYS9Ajf4= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= -sigs.k8s.io/kustomize/api v0.17.2 h1:E7/Fjk7V5fboiuijoZHgs4aHuexi5Y2loXlVOAVAG5g= -sigs.k8s.io/kustomize/api v0.17.2/go.mod h1:UWTz9Ct+MvoeQsHcJ5e+vziRRkwimm3HytpZgIYqye0= -sigs.k8s.io/kustomize/kyaml v0.17.1 h1:TnxYQxFXzbmNG6gOINgGWQt09GghzgTP6mIurOgrLCQ= -sigs.k8s.io/kustomize/kyaml v0.17.1/go.mod h1:9V0mCjIEYjlXuCdYsSXvyoy2BTsLESH7TlGV81S282U= +sigs.k8s.io/kustomize/api v0.18.0 h1:hTzp67k+3NEVInwz5BHyzc9rGxIauoXferXyjv5lWPo= +sigs.k8s.io/kustomize/api v0.18.0/go.mod h1:f8isXnX+8b+SGLHQ6yO4JG1rdkZlvhaCf/uZbLVMb0U= +sigs.k8s.io/kustomize/kyaml v0.18.1 h1:WvBo56Wzw3fjS+7vBjN6TeivvpbW9GmRaWZ9CIVmt4E= +sigs.k8s.io/kustomize/kyaml v0.18.1/go.mod h1:C3L2BFVU1jgcddNBE1TxuVLgS46TjObMwW5FT9FcjYo= sigs.k8s.io/structured-merge-diff/v4 v4.4.2 h1:MdmvkGuXi/8io6ixD5wud3vOLwc1rj0aNqRlpuvjmwA= sigs.k8s.io/structured-merge-diff/v4 v4.4.2/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4= sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= diff --git a/vendor/github.com/Microsoft/hcsshim/LICENSE b/vendor/github.com/Microsoft/hcsshim/LICENSE deleted file mode 100644 index 49d21669a..000000000 --- a/vendor/github.com/Microsoft/hcsshim/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -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. \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go b/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go deleted file mode 100644 index 6c435d2b6..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go +++ /dev/null @@ -1,59 +0,0 @@ -package osversion - -import ( - "fmt" - "sync" - - "golang.org/x/sys/windows" -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion struct { - Version uint32 - MajorVersion uint8 - MinorVersion uint8 - Build uint16 -} - -var ( - osv OSVersion - once sync.Once -) - -// Get gets the operating system version on Windows. -// The calling application must be manifested to get the correct version information. -func Get() OSVersion { - once.Do(func() { - var err error - osv = OSVersion{} - osv.Version, err = windows.GetVersion() - if err != nil { - // GetVersion never fails. - panic(err) - } - osv.MajorVersion = uint8(osv.Version & 0xFF) - osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) - osv.Build = uint16(osv.Version >> 16) - }) - return osv -} - -// Build gets the build-number on Windows -// The calling application must be manifested to get the correct version information. -func Build() uint16 { - return Get().Build -} - -// String returns the OSVersion formatted as a string. It implements the -// [fmt.Stringer] interface. -func (osv OSVersion) String() string { - return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build) -} - -// ToString returns the OSVersion formatted as a string. -// -// Deprecated: use [OSVersion.String]. -func (osv OSVersion) ToString() string { - return osv.String() -} diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go b/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go deleted file mode 100644 index f8d411ad7..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go +++ /dev/null @@ -1,35 +0,0 @@ -package osversion - -// List of stable ABI compliant ltsc releases -// Note: List must be sorted in ascending order -var compatLTSCReleases = []uint16{ - V21H2Server, -} - -// CheckHostAndContainerCompat checks if given host and container -// OS versions are compatible. -// It includes support for stable ABI compliant versions as well. -// Every release after WS 2022 will support the previous ltsc -// container image. Stable ABI is in preview mode for windows 11 client. -// Refer: https://learn.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility?tabs=windows-server-2022%2Cwindows-10#windows-server-host-os-compatibility -func CheckHostAndContainerCompat(host, ctr OSVersion) bool { - // check major minor versions of host and guest - if host.MajorVersion != ctr.MajorVersion || - host.MinorVersion != ctr.MinorVersion { - return false - } - - // If host is < WS 2022, exact version match is required - if host.Build < V21H2Server { - return host.Build == ctr.Build - } - - var supportedLtscRelease uint16 - for i := len(compatLTSCReleases) - 1; i >= 0; i-- { - if host.Build >= compatLTSCReleases[i] { - supportedLtscRelease = compatLTSCReleases[i] - break - } - } - return ctr.Build >= supportedLtscRelease && ctr.Build <= host.Build -} diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go b/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go deleted file mode 100644 index 446369591..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go +++ /dev/null @@ -1,84 +0,0 @@ -package osversion - -// Windows Client and Server build numbers. -// -// See: -// https://learn.microsoft.com/en-us/windows/release-health/release-information -// https://learn.microsoft.com/en-us/windows/release-health/windows-server-release-info -// https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information -const ( - // RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server - // 2016 (ltsc2016) and Windows 10 (Anniversary Update). - RS1 = 14393 - // V1607 (version 1607, codename "Redstone 1") is an alias for [RS1]. - V1607 = RS1 - // LTSC2016 (Windows Server 2016) is an alias for [RS1]. - LTSC2016 = RS1 - - // RS2 (version 1703, codename "Redstone 2") was a client-only update, and - // corresponds to Windows 10 (Creators Update). - RS2 = 15063 - // V1703 (version 1703, codename "Redstone 2") is an alias for [RS2]. - V1703 = RS2 - - // RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server - // 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update). - RS3 = 16299 - // V1709 (version 1709, codename "Redstone 3") is an alias for [RS3]. - V1709 = RS3 - - // RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server - // 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update). - RS4 = 17134 - // V1803 (version 1803, codename "Redstone 4") is an alias for [RS4]. - V1803 = RS4 - - // RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server - // 2019 (ltsc2019), and Windows 10 (October 2018 Update). - RS5 = 17763 - // V1809 (version 1809, codename "Redstone 5") is an alias for [RS5]. - V1809 = RS5 - // LTSC2019 (Windows Server 2019) is an alias for [RS5]. - LTSC2019 = RS5 - - // V19H1 (version 1903, codename 19H1) corresponds to Windows Server 1903 (semi-annual - // channel). - V19H1 = 18362 - // V1903 (version 1903) is an alias for [V19H1]. - V1903 = V19H1 - - // V19H2 (version 1909, codename 19H2) corresponds to Windows Server 1909 (semi-annual - // channel). - V19H2 = 18363 - // V1909 (version 1909) is an alias for [V19H2]. - V1909 = V19H2 - - // V20H1 (version 2004, codename 20H1) corresponds to Windows Server 2004 (semi-annual - // channel). - V20H1 = 19041 - // V2004 (version 2004) is an alias for [V20H1]. - V2004 = V20H1 - - // V20H2 corresponds to Windows Server 20H2 (semi-annual channel). - V20H2 = 19042 - - // V21H1 corresponds to Windows Server 21H1 (semi-annual channel). - V21H1 = 19043 - - // V21H2Win10 corresponds to Windows 10 (November 2021 Update). - V21H2Win10 = 19044 - - // V21H2Server corresponds to Windows Server 2022 (ltsc2022). - V21H2Server = 20348 - // LTSC2022 (Windows Server 2022) is an alias for [V21H2Server] - LTSC2022 = V21H2Server - - // V21H2Win11 corresponds to Windows 11 (original release). - V21H2Win11 = 22000 - - // V22H2Win10 corresponds to Windows 10 (2022 Update). - V22H2Win10 = 19045 - - // V22H2Win11 corresponds to Windows 11 (2022 Update). - V22H2Win11 = 22621 -) diff --git a/vendor/github.com/containerd/containerd/archive/compression/compression.go b/vendor/github.com/containerd/containerd/archive/compression/compression.go index 31bbe4124..23ddfab1a 100644 --- a/vendor/github.com/containerd/containerd/archive/compression/compression.go +++ b/vendor/github.com/containerd/containerd/archive/compression/compression.go @@ -29,7 +29,7 @@ import ( "strconv" "sync" - "github.com/containerd/containerd/log" + "github.com/containerd/log" "github.com/klauspost/compress/zstd" ) diff --git a/vendor/github.com/containerd/containerd/content/content.go b/vendor/github.com/containerd/containerd/content/content.go index 8eb1a1692..2dc7bf8b5 100644 --- a/vendor/github.com/containerd/containerd/content/content.go +++ b/vendor/github.com/containerd/containerd/content/content.go @@ -108,6 +108,12 @@ type Status struct { // WalkFunc defines the callback for a blob walk. type WalkFunc func(Info) error +// InfoReaderProvider provides both info and reader for the specific content. +type InfoReaderProvider interface { + InfoProvider + Provider +} + // InfoProvider provides info for content inspection. type InfoProvider interface { // Info will return metadata about content available in the content store. diff --git a/vendor/github.com/containerd/containerd/content/helpers.go b/vendor/github.com/containerd/containerd/content/helpers.go index 147005413..93bcdde10 100644 --- a/vendor/github.com/containerd/containerd/content/helpers.go +++ b/vendor/github.com/containerd/containerd/content/helpers.go @@ -24,15 +24,13 @@ import ( "sync" "time" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/pkg/randutil" + "github.com/containerd/log" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) -// maxResets is the no.of times the Copy() method can tolerate a reset of the body -const maxResets = 5 + "github.com/containerd/containerd/errdefs" + "github.com/containerd/containerd/pkg/randutil" +) var ErrReset = errors.New("writer has been reset") @@ -160,7 +158,7 @@ func Copy(ctx context.Context, cw Writer, or io.Reader, size int64, expected dig } } - for i := 0; i < maxResets; i++ { + for i := 0; ; i++ { if i >= 1 { log.G(ctx).WithField("digest", expected).Debugf("retrying copy due to reset") } @@ -201,9 +199,6 @@ func Copy(ctx context.Context, cw Writer, or io.Reader, size int64, expected dig } return nil } - - log.G(ctx).WithField("digest", expected).Errorf("failed to copy after %d retries", maxResets) - return fmt.Errorf("failed to copy after %d retries", maxResets) } // CopyReaderAt copies to a writer from a given reader at for the given diff --git a/vendor/github.com/containerd/containerd/content/local/store.go b/vendor/github.com/containerd/containerd/content/local/store.go index baae3565b..e1baee4c2 100644 --- a/vendor/github.com/containerd/containerd/content/local/store.go +++ b/vendor/github.com/containerd/containerd/content/local/store.go @@ -27,12 +27,13 @@ import ( "sync" "time" + "github.com/containerd/log" + "github.com/sirupsen/logrus" + "github.com/containerd/containerd/content" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/filters" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/pkg/randutil" - "github.com/sirupsen/logrus" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" diff --git a/vendor/github.com/containerd/containerd/content/local/writer.go b/vendor/github.com/containerd/containerd/content/local/writer.go index b187e524c..0cd8f2d04 100644 --- a/vendor/github.com/containerd/containerd/content/local/writer.go +++ b/vendor/github.com/containerd/containerd/content/local/writer.go @@ -26,10 +26,11 @@ import ( "runtime" "time" + "github.com/containerd/log" + "github.com/opencontainers/go-digest" + "github.com/containerd/containerd/content" "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/opencontainers/go-digest" ) // writer represents a write transaction against the blob store. diff --git a/vendor/github.com/containerd/containerd/errdefs/errors.go b/vendor/github.com/containerd/containerd/errdefs/errors.go index 876225597..de22cadd4 100644 --- a/vendor/github.com/containerd/containerd/errdefs/errors.go +++ b/vendor/github.com/containerd/containerd/errdefs/errors.go @@ -21,14 +21,10 @@ // // To detect an error class, use the IsXXX functions to tell whether an error // is of a certain type. -// -// The functions ToGRPC and FromGRPC can be used to map server-side and -// client-side errors to the correct types. package errdefs import ( - "context" - "errors" + "github.com/containerd/errdefs" ) // Definitions of common error types used throughout containerd. All containerd @@ -36,57 +32,41 @@ import ( // Packages should return errors of these types when they want to instruct a // client to take a particular action. // -// For the most part, we just try to provide local grpc errors. Most conditions -// map very well to those defined by grpc. +// These errors map closely to grpc errors. var ( - ErrUnknown = errors.New("unknown") // used internally to represent a missed mapping. - ErrInvalidArgument = errors.New("invalid argument") - ErrNotFound = errors.New("not found") - ErrAlreadyExists = errors.New("already exists") - ErrFailedPrecondition = errors.New("failed precondition") - ErrUnavailable = errors.New("unavailable") - ErrNotImplemented = errors.New("not implemented") // represents not supported and unimplemented -) - -// IsInvalidArgument returns true if the error is due to an invalid argument -func IsInvalidArgument(err error) bool { - return errors.Is(err, ErrInvalidArgument) -} - -// IsNotFound returns true if the error is due to a missing object -func IsNotFound(err error) bool { - return errors.Is(err, ErrNotFound) -} - -// IsAlreadyExists returns true if the error is due to an already existing -// metadata item -func IsAlreadyExists(err error) bool { - return errors.Is(err, ErrAlreadyExists) -} + ErrUnknown = errdefs.ErrUnknown + ErrInvalidArgument = errdefs.ErrInvalidArgument + ErrNotFound = errdefs.ErrNotFound + ErrAlreadyExists = errdefs.ErrAlreadyExists + ErrPermissionDenied = errdefs.ErrPermissionDenied + ErrResourceExhausted = errdefs.ErrResourceExhausted + ErrFailedPrecondition = errdefs.ErrFailedPrecondition + ErrConflict = errdefs.ErrConflict + ErrNotModified = errdefs.ErrNotModified + ErrAborted = errdefs.ErrAborted + ErrOutOfRange = errdefs.ErrOutOfRange + ErrNotImplemented = errdefs.ErrNotImplemented + ErrInternal = errdefs.ErrInternal + ErrUnavailable = errdefs.ErrUnavailable + ErrDataLoss = errdefs.ErrDataLoss + ErrUnauthenticated = errdefs.ErrUnauthenticated -// IsFailedPrecondition returns true if an operation could not proceed to the -// lack of a particular condition -func IsFailedPrecondition(err error) bool { - return errors.Is(err, ErrFailedPrecondition) -} - -// IsUnavailable returns true if the error is due to a resource being unavailable -func IsUnavailable(err error) bool { - return errors.Is(err, ErrUnavailable) -} - -// IsNotImplemented returns true if the error is due to not being implemented -func IsNotImplemented(err error) bool { - return errors.Is(err, ErrNotImplemented) -} - -// IsCanceled returns true if the error is due to `context.Canceled`. -func IsCanceled(err error) bool { - return errors.Is(err, context.Canceled) -} - -// IsDeadlineExceeded returns true if the error is due to -// `context.DeadlineExceeded`. -func IsDeadlineExceeded(err error) bool { - return errors.Is(err, context.DeadlineExceeded) -} + IsCanceled = errdefs.IsCanceled + IsUnknown = errdefs.IsUnknown + IsInvalidArgument = errdefs.IsInvalidArgument + IsDeadlineExceeded = errdefs.IsDeadlineExceeded + IsNotFound = errdefs.IsNotFound + IsAlreadyExists = errdefs.IsAlreadyExists + IsPermissionDenied = errdefs.IsPermissionDenied + IsResourceExhausted = errdefs.IsResourceExhausted + IsFailedPrecondition = errdefs.IsFailedPrecondition + IsConflict = errdefs.IsConflict + IsNotModified = errdefs.IsNotModified + IsAborted = errdefs.IsAborted + IsOutOfRange = errdefs.IsOutOfRange + IsNotImplemented = errdefs.IsNotImplemented + IsInternal = errdefs.IsInternal + IsUnavailable = errdefs.IsUnavailable + IsDataLoss = errdefs.IsDataLoss + IsUnauthorized = errdefs.IsUnauthorized +) diff --git a/vendor/github.com/containerd/containerd/filters/filter.go b/vendor/github.com/containerd/containerd/filters/filter.go index e13f2625c..dcc569a4b 100644 --- a/vendor/github.com/containerd/containerd/filters/filter.go +++ b/vendor/github.com/containerd/containerd/filters/filter.go @@ -70,7 +70,7 @@ package filters import ( "regexp" - "github.com/containerd/containerd/log" + "github.com/containerd/log" ) // Filter matches specific resources based the provided filter diff --git a/vendor/github.com/containerd/containerd/images/diffid.go b/vendor/github.com/containerd/containerd/images/diffid.go index 56193cc28..85577eede 100644 --- a/vendor/github.com/containerd/containerd/images/diffid.go +++ b/vendor/github.com/containerd/containerd/images/diffid.go @@ -36,7 +36,7 @@ func GetDiffID(ctx context.Context, cs content.Store, desc ocispec.Descriptor) ( MediaTypeDockerSchema2Layer, ocispec.MediaTypeImageLayer, MediaTypeDockerSchema2LayerForeign, - ocispec.MediaTypeImageLayerNonDistributable: + ocispec.MediaTypeImageLayerNonDistributable: //nolint:staticcheck // deprecated return desc.Digest, nil } info, err := cs.Info(ctx, desc.Digest) diff --git a/vendor/github.com/containerd/containerd/images/handlers.go b/vendor/github.com/containerd/containerd/images/handlers.go index 077d88e78..a685092e2 100644 --- a/vendor/github.com/containerd/containerd/images/handlers.go +++ b/vendor/github.com/containerd/containerd/images/handlers.go @@ -22,12 +22,13 @@ import ( "fmt" "sort" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/platforms" + "github.com/containerd/platforms" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" + + "github.com/containerd/containerd/content" + "github.com/containerd/containerd/errdefs" ) var ( diff --git a/vendor/github.com/containerd/containerd/images/image.go b/vendor/github.com/containerd/containerd/images/image.go index 2d2e36a9a..b934e3496 100644 --- a/vendor/github.com/containerd/containerd/images/image.go +++ b/vendor/github.com/containerd/containerd/images/image.go @@ -23,12 +23,13 @@ import ( "sort" "time" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/platforms" + "github.com/containerd/log" + "github.com/containerd/platforms" digest "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" + + "github.com/containerd/containerd/content" + "github.com/containerd/containerd/errdefs" ) // Image provides the model for how containerd views container images. @@ -268,6 +269,9 @@ func Platforms(ctx context.Context, provider content.Provider, image ocispec.Des var platformSpecs []ocispec.Platform return platformSpecs, Walk(ctx, Handlers(HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { if desc.Platform != nil { + if desc.Platform.OS == "unknown" || desc.Platform.Architecture == "unknown" { + return nil, ErrSkipDesc + } platformSpecs = append(platformSpecs, *desc.Platform) return nil, ErrSkipDesc } diff --git a/vendor/github.com/containerd/containerd/images/mediatypes.go b/vendor/github.com/containerd/containerd/images/mediatypes.go index 067963bab..d3b28d42d 100644 --- a/vendor/github.com/containerd/containerd/images/mediatypes.go +++ b/vendor/github.com/containerd/containerd/images/mediatypes.go @@ -81,7 +81,7 @@ func DiffCompression(ctx context.Context, mediaType string) (string, error) { return "", nil } return "gzip", nil - case ocispec.MediaTypeImageLayer, ocispec.MediaTypeImageLayerNonDistributable: + case ocispec.MediaTypeImageLayer, ocispec.MediaTypeImageLayerNonDistributable: //nolint:staticcheck // Non-distributable layers are deprecated if len(ext) > 0 { switch ext[len(ext)-1] { case "gzip": diff --git a/vendor/github.com/containerd/containerd/reference/docker/helpers.go b/vendor/github.com/containerd/containerd/reference/docker/helpers.go deleted file mode 100644 index 386025104..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/helpers.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright The containerd 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 docker - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See https://godoc.org/path#Match for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/normalize.go b/vendor/github.com/containerd/containerd/reference/docker/normalize.go deleted file mode 100644 index b299bf6c0..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/normalize.go +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -var ( - legacyDefaultDomain = "index.docker.io" - defaultDomain = "docker.io" - officialRepoName = "library" - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remoteName string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remoteName = remainder[:tagSep] - } else { - remoteName = remainder - } - if strings.ToLower(remoteName) != remoteName { - return nil, fmt.Errorf("invalid reference format: repository name (%s) must be lowercase", remoteName) - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// ParseDockerRef normalizes the image reference following the docker convention. This is added -// mainly for backward compatibility. -// The reference returned can only be either tagged or digested. For reference contains both tag -// and digest, the function returns digested reference, e.g. docker.io/library/busybox:latest@ -// sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa will be returned as -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa. -func ParseDockerRef(ref string) (Named, error) { - named, err := ParseNormalizedNamed(ref) - if err != nil { - return nil, err - } - if _, ok := named.(NamedTagged); ok { - if canonical, ok := named.(Canonical); ok { - // The reference is both tagged and digested, only - // return digested. - newNamed, err := WithName(canonical.Name()) - if err != nil { - return nil, err - } - newCanonical, err := WithDigest(newNamed, canonical.Digest()) - if err != nil { - return nil, err - } - return newCanonical, nil - } - } - return TagNameOnly(named), nil -} - -// splitDockerDomain splits a repository name to domain and remotename string. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost" && strings.ToLower(name[:i]) == name[:i]) { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoName + "/" + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName { - repo.path = split[1] - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/reference.go b/vendor/github.com/containerd/containerd/reference/docker/reference.go deleted file mode 100644 index 4dc00474e..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/reference.go +++ /dev/null @@ -1,453 +0,0 @@ -/* - Copyright The containerd 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 docker provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] path-component ['/' path-component]* -// domain := host [':' port-number] -// host := domain-name | IPv4address | \[ IPv6address \] ; rfc3986 appendix-A -// domain-name := domain-component ['.' domain-component]* -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]* -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -// short-identifier := /[a-f0-9]{6,64}/ -package docker - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the Named reference -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the Named reference -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// DEPRECATED: Use Domain or Path -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: Parse will not handle short digests. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: ParseNamed will not handle short digests. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - repo := repository{} - if r, ok := ref.(namedRepository); ok { - repo.domain, repo.path = r.Domain(), r.Path() - } else { - repo.domain, repo.path = splitDomain(ref.Name()) - } - return repo -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/regexp.go b/vendor/github.com/containerd/containerd/reference/docker/regexp.go deleted file mode 100644 index 4be3c575e..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/regexp.go +++ /dev/null @@ -1,191 +0,0 @@ -/* - Copyright The containerd 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 docker - -import "regexp" - -var ( - // alphaNumeric defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumeric = `[a-z0-9]+` - - // separator defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. Repeated dashes and underscores are intentionally treated - // differently. In order to support valid hostnames as name components, - // supporting repeated dash was added. Additionally double underscore is - // now allowed as a separator to loosen the restriction for previously - // supported names. - separator = `(?:[._]|__|[-]*)` - - // nameComponent restricts registry path component names to start - // with at least one letter or number, with following parts able to be - // separated by one period, one or two underscore and multiple dashes. - nameComponent = expression( - alphaNumeric, - optional(repeated(separator, alphaNumeric))) - - // domainNameComponent restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp. - domainNameComponent = `(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])` - - // ipv6address are enclosed between square brackets and may be represented - // in many ways, see rfc5952. Only IPv6 in compressed or uncompressed format - // are allowed, IPv6 zone identifiers (rfc6874) or Special addresses such as - // IPv4-Mapped are deliberately excluded. - ipv6address = expression( - literal(`[`), `(?:[a-fA-F0-9:]+)`, literal(`]`), - ) - - // domainName defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. This includes IPv4 addresses on decimal format. - domainName = expression( - domainNameComponent, - optional(repeated(literal(`.`), domainNameComponent)), - ) - - // host defines the structure of potential domains based on the URI - // Host subcomponent on rfc3986. It may be a subset of DNS domain name, - // or an IPv4 address in decimal format, or an IPv6 address between square - // brackets (excluding zone identifiers as defined by rfc6874 or special - // addresses such as IPv4-Mapped). - host = `(?:` + domainName + `|` + ipv6address + `)` - - // allowed by the URI Host subcomponent on rfc3986 to ensure backwards - // compatibility with Docker image names. - domain = expression( - host, - optional(literal(`:`), `[0-9]+`)) - - // DomainRegexp defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. - DomainRegexp = regexp.MustCompile(domain) - - tag = `[\w][\w.-]{0,127}` - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = regexp.MustCompile(tag) - - anchoredTag = anchored(tag) - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = regexp.MustCompile(anchoredTag) - - digestPat = `[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}` - // DigestRegexp matches valid digests. - DigestRegexp = regexp.MustCompile(digestPat) - - anchoredDigest = anchored(digestPat) - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = regexp.MustCompile(anchoredDigest) - - namePat = expression( - optional(domain, literal(`/`)), - nameComponent, - optional(repeated(literal(`/`), nameComponent))) - // NameRegexp is the format for the name component of references. The - // regexp has capturing groups for the domain and name part omitting - // the separating forward slash from either. - NameRegexp = regexp.MustCompile(namePat) - - anchoredName = anchored( - optional(capture(domain), literal(`/`)), - capture(nameComponent, - optional(repeated(literal(`/`), nameComponent)))) - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = regexp.MustCompile(anchoredName) - - referencePat = anchored(capture(namePat), - optional(literal(":"), capture(tag)), - optional(literal("@"), capture(digestPat))) - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = regexp.MustCompile(referencePat) - - identifier = `([a-f0-9]{64})` - // IdentifierRegexp is the format for string identifier used as a - // content addressable identifier using sha256. These identifiers - // are like digests without the algorithm, since sha256 is used. - IdentifierRegexp = regexp.MustCompile(identifier) - - shortIdentifier = `([a-f0-9]{6,64})` - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - ShortIdentifierRegexp = regexp.MustCompile(shortIdentifier) - - anchoredIdentifier = anchored(identifier) - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = regexp.MustCompile(anchoredIdentifier) -) - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) string { - re := regexp.MustCompile(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re.String() -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...string) string { - var s string - for _, re := range res { - s += re - } - - return s -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...string) string { - return group(expression(res...)) + `?` -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...string) string { - return group(expression(res...)) + `+` -} - -// group wraps the regexp in a non-capturing group. -func group(res ...string) string { - return `(?:` + expression(res...) + `)` -} - -// capture wraps the expression in a capturing group. -func capture(res ...string) string { - return `(` + expression(res...) + `)` -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...string) string { - return `^` + expression(res...) + `$` -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/sort.go b/vendor/github.com/containerd/containerd/reference/docker/sort.go deleted file mode 100644 index 984e37528..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/sort.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "sort" -) - -// Sort sorts string references preferring higher information references -// The precedence is as follows: -// 1. Name + Tag + Digest -// 2. Name + Tag -// 3. Name + Digest -// 4. Name -// 5. Digest -// 6. Parse error -func Sort(references []string) []string { - var prefs []Reference - var bad []string - - for _, ref := range references { - pref, err := ParseAnyReference(ref) - if err != nil { - bad = append(bad, ref) - } else { - prefs = append(prefs, pref) - } - } - sort.Slice(prefs, func(a, b int) bool { - ar := refRank(prefs[a]) - br := refRank(prefs[b]) - if ar == br { - return prefs[a].String() < prefs[b].String() - } - return ar < br - }) - sort.Strings(bad) - var refs []string - for _, pref := range prefs { - refs = append(refs, pref.String()) - } - return append(refs, bad...) -} - -func refRank(ref Reference) uint8 { - if _, ok := ref.(Named); ok { - if _, ok = ref.(Tagged); ok { - if _, ok = ref.(Digested); ok { - return 1 - } - return 2 - } - if _, ok = ref.(Digested); ok { - return 3 - } - return 4 - } - return 5 -} diff --git a/vendor/github.com/containerd/containerd/reference/reference.go b/vendor/github.com/containerd/containerd/reference/reference.go index a4bf6da60..9329a9aab 100644 --- a/vendor/github.com/containerd/containerd/reference/reference.go +++ b/vendor/github.com/containerd/containerd/reference/reference.go @@ -18,7 +18,6 @@ package reference import ( "errors" - "fmt" "net/url" "path" "regexp" @@ -136,8 +135,12 @@ func (r Spec) Hostname() string { // Digest returns the digest portion of the reference spec. This may be a // partial or invalid digest, which may be used to lookup a complete digest. func (r Spec) Digest() digest.Digest { - _, dgst := SplitObject(r.Object) - return dgst + i := strings.Index(r.Object, "@") + + if i < 0 { + return "" + } + return digest.Digest(r.Object[i+1:]) } // String returns the normalized string for the ref. @@ -146,21 +149,31 @@ func (r Spec) String() string { return r.Locator } if r.Object[:1] == "@" { - return fmt.Sprintf("%v%v", r.Locator, r.Object) + return r.Locator + r.Object } - return fmt.Sprintf("%v:%v", r.Locator, r.Object) + return r.Locator + ":" + r.Object } -// SplitObject provides two parts of the object spec, delimited by an `@` -// symbol. +// SplitObject provides two parts of the object spec, delimited by an "@" +// symbol. It does not perform any validation on correctness of the values +// returned, and it's the callers' responsibility to validate the result. +// +// If an "@" delimiter is found, it returns the part *including* the "@" +// delimiter as "tag", and the part after the "@" as digest. +// +// The example below produces "docker.io/library/ubuntu:latest@" and +// "sha256:deadbeef"; +// +// t, d := SplitObject("docker.io/library/ubuntu:latest@sha256:deadbeef") +// fmt.Println(t) // docker.io/library/ubuntu:latest@ +// fmt.Println(d) // sha256:deadbeef // -// Either may be empty and it is the callers job to validate them -// appropriately. +// Deprecated: use [Parse] and [Spec.Digest] instead. func SplitObject(obj string) (tag string, dgst digest.Digest) { - parts := strings.SplitAfterN(obj, "@", 2) - if len(parts) < 2 { - return parts[0], "" + if i := strings.Index(obj, "@"); i >= 0 { + // Offset by one so preserve the "@" in the tag returned. + return obj[:i+1], digest.Digest(obj[i+1:]) } - return parts[0], digest.Digest(parts[1]) + return obj, "" } diff --git a/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go b/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go index 64c6a38f9..244e03509 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go @@ -26,9 +26,9 @@ import ( "strings" "time" - "github.com/containerd/containerd/log" remoteserrors "github.com/containerd/containerd/remotes/errors" "github.com/containerd/containerd/version" + "github.com/containerd/log" ) var ( diff --git a/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go b/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go index 9b3663cd1..2bf388e8c 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go @@ -25,8 +25,9 @@ import ( "strings" "sync" + "github.com/containerd/log" + "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/remotes/docker/auth" remoteerrors "github.com/containerd/containerd/remotes/errors" ) @@ -148,9 +149,11 @@ func (a *dockerAuthorizer) AddResponses(ctx context.Context, responses []*http.R defer a.mu.Unlock() for _, c := range auth.ParseAuthHeader(last.Header) { if c.Scheme == auth.BearerAuth { - if err := invalidAuthorization(c, responses); err != nil { + if retry, err := invalidAuthorization(ctx, c, responses); err != nil { delete(a.handlers, host) return err + } else if retry { + delete(a.handlers, host) } // reuse existing handler @@ -328,18 +331,24 @@ func (ah *authHandler) doBearerAuth(ctx context.Context) (token, refreshToken st return resp.Token, resp.RefreshToken, nil } -func invalidAuthorization(c auth.Challenge, responses []*http.Response) error { +func invalidAuthorization(ctx context.Context, c auth.Challenge, responses []*http.Response) (retry bool, _ error) { errStr := c.Parameters["error"] if errStr == "" { - return nil + return retry, nil } n := len(responses) if n == 1 || (n > 1 && !sameRequest(responses[n-2].Request, responses[n-1].Request)) { - return nil + limitedErr := errStr + errLenghLimit := 64 + if len(limitedErr) > errLenghLimit { + limitedErr = limitedErr[:errLenghLimit] + "..." + } + log.G(ctx).WithField("error", limitedErr).Debug("authorization error using bearer token, retrying") + return true, nil } - return fmt.Errorf("server message: %s: %w", errStr, ErrInvalidAuthorization) + return retry, fmt.Errorf("server message: %s: %w", errStr, ErrInvalidAuthorization) } func sameRequest(r1, r2 *http.Request) bool { diff --git a/vendor/github.com/containerd/containerd/remotes/docker/converter.go b/vendor/github.com/containerd/containerd/remotes/docker/converter.go index d7dca0d36..95a68d70e 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/converter.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/converter.go @@ -24,8 +24,8 @@ import ( "github.com/containerd/containerd/content" "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/remotes" + "github.com/containerd/log" digest "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) diff --git a/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go b/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go index 908205392..aa7cf4666 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go @@ -24,7 +24,7 @@ import ( fuzz "github.com/AdaLogics/go-fuzz-headers" "github.com/containerd/containerd/content/local" - "github.com/containerd/containerd/log" + "github.com/containerd/log" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/sirupsen/logrus" ) diff --git a/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go b/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go index ecf245933..c4c401ad1 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go @@ -26,11 +26,12 @@ import ( "net/url" "strings" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" + "github.com/containerd/log" digest "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" + + "github.com/containerd/containerd/errdefs" + "github.com/containerd/containerd/images" ) type dockerFetcher struct { diff --git a/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go b/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go index b98886c59..f396a74f4 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go @@ -25,8 +25,6 @@ import ( "net/http" "net/http/httptest" "net/url" - - refDocker "github.com/containerd/containerd/reference/docker" ) func FuzzFetcher(data []byte) int { @@ -74,8 +72,3 @@ func FuzzFetcher(data []byte) int { } return 1 } - -func FuzzParseDockerRef(data []byte) int { - _, _ = refDocker.ParseDockerRef(string(data)) - return 1 -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/handler.go b/vendor/github.com/containerd/containerd/remotes/docker/handler.go index 27638ccc0..ccec49013 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/handler.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/handler.go @@ -25,8 +25,8 @@ import ( "github.com/containerd/containerd/content" "github.com/containerd/containerd/images" "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/reference" + "github.com/containerd/log" ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) diff --git a/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go b/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go index 824359339..deb888cbc 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go @@ -21,8 +21,9 @@ import ( "fmt" "io" + "github.com/containerd/log" + "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" ) const maxRetry = 3 diff --git a/vendor/github.com/containerd/containerd/remotes/docker/pusher.go b/vendor/github.com/containerd/containerd/remotes/docker/pusher.go index 678e17e12..f97ab144e 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/pusher.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/pusher.go @@ -28,14 +28,15 @@ import ( "sync" "time" + "github.com/containerd/log" + digest "github.com/opencontainers/go-digest" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "github.com/containerd/containerd/content" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/remotes" remoteserrors "github.com/containerd/containerd/remotes/errors" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) type dockerPusher struct { @@ -284,7 +285,7 @@ func (p dockerPusher) push(ctx context.Context, desc ocispec.Descriptor, ref str req.body = func() (io.ReadCloser, error) { pr, pw := io.Pipe() pushw.setPipe(pw) - return io.NopCloser(pr), nil + return pr, nil } req.size = desc.Size @@ -292,7 +293,6 @@ func (p dockerPusher) push(ctx context.Context, desc ocispec.Descriptor, ref str resp, err := req.doWithRetries(ctx, nil) if err != nil { pushw.setError(err) - pushw.Close() return } @@ -302,7 +302,7 @@ func (p dockerPusher) push(ctx context.Context, desc ocispec.Descriptor, ref str err := remoteserrors.NewUnexpectedStatusErr(resp) log.G(ctx).WithField("resp", resp).WithField("body", string(err.(remoteserrors.ErrUnexpectedStatus).Body)).Debug("unexpected response") pushw.setError(err) - pushw.Close() + return } pushw.setResponse(resp) }() @@ -335,10 +335,12 @@ type pushWriter struct { pipe *io.PipeWriter - pipeC chan *io.PipeWriter - respC chan *http.Response + done chan struct{} closeOnce sync.Once - errC chan error + + pipeC chan *io.PipeWriter + respC chan *http.Response + errC chan error isManifest bool @@ -356,19 +358,51 @@ func newPushWriter(db *dockerBase, ref string, expected digest.Digest, tracker S pipeC: make(chan *io.PipeWriter, 1), respC: make(chan *http.Response, 1), errC: make(chan error, 1), + done: make(chan struct{}), isManifest: isManifest, } } func (pw *pushWriter) setPipe(p *io.PipeWriter) { - pw.pipeC <- p + select { + case <-pw.done: + case pw.pipeC <- p: + } } func (pw *pushWriter) setError(err error) { - pw.errC <- err + select { + case <-pw.done: + case pw.errC <- err: + } } + func (pw *pushWriter) setResponse(resp *http.Response) { - pw.respC <- resp + select { + case <-pw.done: + case pw.respC <- resp: + } +} + +func (pw *pushWriter) replacePipe(p *io.PipeWriter) error { + if pw.pipe == nil { + pw.pipe = p + return nil + } + + pw.pipe.CloseWithError(content.ErrReset) + pw.pipe = p + + // If content has already been written, the bytes + // cannot be written again and the caller must reset + status, err := pw.tracker.GetStatus(pw.ref) + if err != nil { + return err + } + status.Offset = 0 + status.UpdatedAt = time.Now() + pw.tracker.SetStatus(pw.ref, status) + return content.ErrReset } func (pw *pushWriter) Write(p []byte) (n int, err error) { @@ -378,26 +412,18 @@ func (pw *pushWriter) Write(p []byte) (n int, err error) { } if pw.pipe == nil { - p, ok := <-pw.pipeC - if !ok { + select { + case <-pw.done: return 0, io.ErrClosedPipe + case p := <-pw.pipeC: + pw.replacePipe(p) } - pw.pipe = p } else { select { - case p, ok := <-pw.pipeC: - if !ok { - return 0, io.ErrClosedPipe - } - pw.pipe.CloseWithError(content.ErrReset) - pw.pipe = p - - // If content has already been written, the bytes - // cannot be written and the caller must reset - status.Offset = 0 - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - return 0, content.ErrReset + case <-pw.done: + return 0, io.ErrClosedPipe + case p := <-pw.pipeC: + return 0, pw.replacePipe(p) default: } } @@ -407,9 +433,13 @@ func (pw *pushWriter) Write(p []byte) (n int, err error) { // if the pipe is closed, we might have the original error on the error // channel - so we should try and get it select { - case err2 := <-pw.errC: - err = err2 - default: + case <-pw.done: + case err = <-pw.errC: + pw.Close() + case p := <-pw.pipeC: + return 0, pw.replacePipe(p) + case resp := <-pw.respC: + pw.setResponse(resp) } } status.Offset += int64(n) @@ -422,7 +452,7 @@ func (pw *pushWriter) Close() error { // Ensure pipeC is closed but handle `Close()` being // called multiple times without panicking pw.closeOnce.Do(func() { - close(pw.pipeC) + close(pw.done) }) if pw.pipe != nil { status, err := pw.tracker.GetStatus(pw.ref) @@ -462,30 +492,18 @@ func (pw *pushWriter) Commit(ctx context.Context, size int64, expected digest.Di // TODO: timeout waiting for response var resp *http.Response select { + case <-pw.done: + return io.ErrClosedPipe case err := <-pw.errC: + pw.Close() return err case resp = <-pw.respC: defer resp.Body.Close() - case p, ok := <-pw.pipeC: + case p := <-pw.pipeC: // check whether the pipe has changed in the commit, because sometimes Write // can complete successfully, but the pipe may have changed. In that case, the // content needs to be reset. - if !ok { - return io.ErrClosedPipe - } - pw.pipe.CloseWithError(content.ErrReset) - pw.pipe = p - - // If content has already been written, the bytes - // cannot be written again and the caller must reset - status, err := pw.tracker.GetStatus(pw.ref) - if err != nil { - return err - } - status.Offset = 0 - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - return content.ErrReset + return pw.replacePipe(p) } // 201 is specified return status, some registries return diff --git a/vendor/github.com/containerd/containerd/remotes/docker/resolver.go b/vendor/github.com/containerd/containerd/remotes/docker/resolver.go index cca4ca6a2..4ca2b921e 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/resolver.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/resolver.go @@ -28,17 +28,18 @@ import ( "path" "strings" + "github.com/containerd/log" + "github.com/opencontainers/go-digest" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/reference" "github.com/containerd/containerd/remotes" "github.com/containerd/containerd/remotes/docker/schema1" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility. remoteerrors "github.com/containerd/containerd/remotes/errors" "github.com/containerd/containerd/tracing" "github.com/containerd/containerd/version" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) var ( @@ -704,9 +705,71 @@ func IsLocalhost(host string) bool { return ip.IsLoopback() } +// NewHTTPFallback returns http.RoundTripper which allows fallback from https to +// http for registry endpoints with configurations for both http and TLS, +// such as defaulted localhost endpoints. +func NewHTTPFallback(transport http.RoundTripper) http.RoundTripper { + return &httpFallback{ + super: transport, + } +} + +type httpFallback struct { + super http.RoundTripper + host string +} + +func (f *httpFallback) RoundTrip(r *http.Request) (*http.Response, error) { + // only fall back if the same host had previously fell back + if f.host != r.URL.Host { + resp, err := f.super.RoundTrip(r) + if !isTLSError(err) { + return resp, err + } + } + + plainHTTPUrl := *r.URL + plainHTTPUrl.Scheme = "http" + + plainHTTPRequest := *r + plainHTTPRequest.URL = &plainHTTPUrl + + if f.host != r.URL.Host { + f.host = r.URL.Host + + // update body on the second attempt + if r.Body != nil && r.GetBody != nil { + body, err := r.GetBody() + if err != nil { + return nil, err + } + plainHTTPRequest.Body = body + } + } + + return f.super.RoundTrip(&plainHTTPRequest) +} + +func isTLSError(err error) bool { + if err == nil { + return false + } + var tlsErr tls.RecordHeaderError + if errors.As(err, &tlsErr) && string(tlsErr.RecordHeader[:]) == "HTTP/" { + return true + } + if strings.Contains(err.Error(), "TLS handshake timeout") { + return true + } + + return false +} + // HTTPFallback is an http.RoundTripper which allows fallback from https to http // for registry endpoints with configurations for both http and TLS, such as // defaulted localhost endpoints. +// +// Deprecated: Use NewHTTPFallback instead. type HTTPFallback struct { http.RoundTripper } @@ -722,6 +785,14 @@ func (f HTTPFallback) RoundTrip(r *http.Request) (*http.Response, error) { plainHTTPRequest := *r plainHTTPRequest.URL = &plainHTTPUrl + if r.Body != nil && r.GetBody != nil { + body, err := r.GetBody() + if err != nil { + return nil, err + } + plainHTTPRequest.Body = body + } + return f.RoundTripper.RoundTrip(&plainHTTPRequest) } diff --git a/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go b/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go index 8c9e520cd..b38c73855 100644 --- a/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go +++ b/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go @@ -32,17 +32,18 @@ import ( "sync" "time" + "github.com/containerd/log" + digest "github.com/opencontainers/go-digest" + specs "github.com/opencontainers/image-spec/specs-go" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "golang.org/x/sync/errgroup" + "github.com/containerd/containerd/archive/compression" "github.com/containerd/containerd/content" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/images" "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" "github.com/containerd/containerd/remotes" - digest "github.com/opencontainers/go-digest" - specs "github.com/opencontainers/image-spec/specs-go" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sync/errgroup" ) const ( diff --git a/vendor/github.com/containerd/containerd/remotes/handlers.go b/vendor/github.com/containerd/containerd/remotes/handlers.go index f24669dc4..365ff5fc0 100644 --- a/vendor/github.com/containerd/containerd/remotes/handlers.go +++ b/vendor/github.com/containerd/containerd/remotes/handlers.go @@ -25,14 +25,15 @@ import ( "strings" "sync" + "github.com/containerd/log" + "github.com/containerd/platforms" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "golang.org/x/sync/semaphore" + "github.com/containerd/containerd/content" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/images" "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/platforms" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sync/semaphore" ) type refKeyPrefix struct{} diff --git a/vendor/github.com/containerd/containerd/version/version.go b/vendor/github.com/containerd/containerd/version/version.go index c01bc57e8..c61791188 100644 --- a/vendor/github.com/containerd/containerd/version/version.go +++ b/vendor/github.com/containerd/containerd/version/version.go @@ -23,7 +23,7 @@ var ( Package = "github.com/containerd/containerd" // Version holds the complete version number. Filled in at linking time. - Version = "1.7.12+unknown" + Version = "1.7.23+unknown" // Revision is filled with the VCS (e.g. git) revision being used to build // the program at linking time. diff --git a/vendor/gopkg.in/yaml.v2/LICENSE b/vendor/github.com/containerd/errdefs/LICENSE similarity index 93% rename from vendor/gopkg.in/yaml.v2/LICENSE rename to vendor/github.com/containerd/errdefs/LICENSE index 8dada3eda..584149b6e 100644 --- a/vendor/gopkg.in/yaml.v2/LICENSE +++ b/vendor/github.com/containerd/errdefs/LICENSE @@ -1,6 +1,7 @@ + Apache License Version 2.0, January 2004 - http://www.apache.org/licenses/ + https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -175,24 +176,13 @@ 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} + Copyright The containerd 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 + https://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, diff --git a/vendor/github.com/containerd/errdefs/README.md b/vendor/github.com/containerd/errdefs/README.md new file mode 100644 index 000000000..bd418c63f --- /dev/null +++ b/vendor/github.com/containerd/errdefs/README.md @@ -0,0 +1,13 @@ +# errdefs + +A Go package for defining and checking common containerd errors. + +## Project details + +**errdefs** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). +As a containerd sub-project, you will find the: + * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), + * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), + * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) + +information in our [`containerd/project`](https://github.com/containerd/project) repository. diff --git a/vendor/github.com/containerd/errdefs/errors.go b/vendor/github.com/containerd/errdefs/errors.go new file mode 100644 index 000000000..f654d1964 --- /dev/null +++ b/vendor/github.com/containerd/errdefs/errors.go @@ -0,0 +1,443 @@ +/* + Copyright The containerd 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 errdefs defines the common errors used throughout containerd +// packages. +// +// Use with fmt.Errorf to add context to an error. +// +// To detect an error class, use the IsXXX functions to tell whether an error +// is of a certain type. +package errdefs + +import ( + "context" + "errors" +) + +// Definitions of common error types used throughout containerd. All containerd +// errors returned by most packages will map into one of these errors classes. +// Packages should return errors of these types when they want to instruct a +// client to take a particular action. +// +// These errors map closely to grpc errors. +var ( + ErrUnknown = errUnknown{} + ErrInvalidArgument = errInvalidArgument{} + ErrNotFound = errNotFound{} + ErrAlreadyExists = errAlreadyExists{} + ErrPermissionDenied = errPermissionDenied{} + ErrResourceExhausted = errResourceExhausted{} + ErrFailedPrecondition = errFailedPrecondition{} + ErrConflict = errConflict{} + ErrNotModified = errNotModified{} + ErrAborted = errAborted{} + ErrOutOfRange = errOutOfRange{} + ErrNotImplemented = errNotImplemented{} + ErrInternal = errInternal{} + ErrUnavailable = errUnavailable{} + ErrDataLoss = errDataLoss{} + ErrUnauthenticated = errUnauthorized{} +) + +// cancelled maps to Moby's "ErrCancelled" +type cancelled interface { + Cancelled() +} + +// IsCanceled returns true if the error is due to `context.Canceled`. +func IsCanceled(err error) bool { + return errors.Is(err, context.Canceled) || isInterface[cancelled](err) +} + +type errUnknown struct{} + +func (errUnknown) Error() string { return "unknown" } + +func (errUnknown) Unknown() {} + +func (e errUnknown) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// unknown maps to Moby's "ErrUnknown" +type unknown interface { + Unknown() +} + +// IsUnknown returns true if the error is due to an unknown error, +// unhandled condition or unexpected response. +func IsUnknown(err error) bool { + return errors.Is(err, errUnknown{}) || isInterface[unknown](err) +} + +type errInvalidArgument struct{} + +func (errInvalidArgument) Error() string { return "invalid argument" } + +func (errInvalidArgument) InvalidParameter() {} + +func (e errInvalidArgument) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// invalidParameter maps to Moby's "ErrInvalidParameter" +type invalidParameter interface { + InvalidParameter() +} + +// IsInvalidArgument returns true if the error is due to an invalid argument +func IsInvalidArgument(err error) bool { + return errors.Is(err, ErrInvalidArgument) || isInterface[invalidParameter](err) +} + +// deadlineExceed maps to Moby's "ErrDeadline" +type deadlineExceeded interface { + DeadlineExceeded() +} + +// IsDeadlineExceeded returns true if the error is due to +// `context.DeadlineExceeded`. +func IsDeadlineExceeded(err error) bool { + return errors.Is(err, context.DeadlineExceeded) || isInterface[deadlineExceeded](err) +} + +type errNotFound struct{} + +func (errNotFound) Error() string { return "not found" } + +func (errNotFound) NotFound() {} + +func (e errNotFound) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// notFound maps to Moby's "ErrNotFound" +type notFound interface { + NotFound() +} + +// IsNotFound returns true if the error is due to a missing object +func IsNotFound(err error) bool { + return errors.Is(err, ErrNotFound) || isInterface[notFound](err) +} + +type errAlreadyExists struct{} + +func (errAlreadyExists) Error() string { return "already exists" } + +func (errAlreadyExists) AlreadyExists() {} + +func (e errAlreadyExists) WithMessage(msg string) error { + return customMessage{e, msg} +} + +type alreadyExists interface { + AlreadyExists() +} + +// IsAlreadyExists returns true if the error is due to an already existing +// metadata item +func IsAlreadyExists(err error) bool { + return errors.Is(err, ErrAlreadyExists) || isInterface[alreadyExists](err) +} + +type errPermissionDenied struct{} + +func (errPermissionDenied) Error() string { return "permission denied" } + +func (errPermissionDenied) Forbidden() {} + +func (e errPermissionDenied) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// forbidden maps to Moby's "ErrForbidden" +type forbidden interface { + Forbidden() +} + +// IsPermissionDenied returns true if the error is due to permission denied +// or forbidden (403) response +func IsPermissionDenied(err error) bool { + return errors.Is(err, ErrPermissionDenied) || isInterface[forbidden](err) +} + +type errResourceExhausted struct{} + +func (errResourceExhausted) Error() string { return "resource exhausted" } + +func (errResourceExhausted) ResourceExhausted() {} + +func (e errResourceExhausted) WithMessage(msg string) error { + return customMessage{e, msg} +} + +type resourceExhausted interface { + ResourceExhausted() +} + +// IsResourceExhausted returns true if the error is due to +// a lack of resources or too many attempts. +func IsResourceExhausted(err error) bool { + return errors.Is(err, errResourceExhausted{}) || isInterface[resourceExhausted](err) +} + +type errFailedPrecondition struct{} + +func (e errFailedPrecondition) Error() string { return "failed precondition" } + +func (errFailedPrecondition) FailedPrecondition() {} + +func (e errFailedPrecondition) WithMessage(msg string) error { + return customMessage{e, msg} +} + +type failedPrecondition interface { + FailedPrecondition() +} + +// IsFailedPrecondition returns true if an operation could not proceed due to +// the lack of a particular condition +func IsFailedPrecondition(err error) bool { + return errors.Is(err, errFailedPrecondition{}) || isInterface[failedPrecondition](err) +} + +type errConflict struct{} + +func (errConflict) Error() string { return "conflict" } + +func (errConflict) Conflict() {} + +func (e errConflict) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// conflict maps to Moby's "ErrConflict" +type conflict interface { + Conflict() +} + +// IsConflict returns true if an operation could not proceed due to +// a conflict. +func IsConflict(err error) bool { + return errors.Is(err, errConflict{}) || isInterface[conflict](err) +} + +type errNotModified struct{} + +func (errNotModified) Error() string { return "not modified" } + +func (errNotModified) NotModified() {} + +func (e errNotModified) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// notModified maps to Moby's "ErrNotModified" +type notModified interface { + NotModified() +} + +// IsNotModified returns true if an operation could not proceed due +// to an object not modified from a previous state. +func IsNotModified(err error) bool { + return errors.Is(err, errNotModified{}) || isInterface[notModified](err) +} + +type errAborted struct{} + +func (errAborted) Error() string { return "aborted" } + +func (errAborted) Aborted() {} + +func (e errAborted) WithMessage(msg string) error { + return customMessage{e, msg} +} + +type aborted interface { + Aborted() +} + +// IsAborted returns true if an operation was aborted. +func IsAborted(err error) bool { + return errors.Is(err, errAborted{}) || isInterface[aborted](err) +} + +type errOutOfRange struct{} + +func (errOutOfRange) Error() string { return "out of range" } + +func (errOutOfRange) OutOfRange() {} + +func (e errOutOfRange) WithMessage(msg string) error { + return customMessage{e, msg} +} + +type outOfRange interface { + OutOfRange() +} + +// IsOutOfRange returns true if an operation could not proceed due +// to data being out of the expected range. +func IsOutOfRange(err error) bool { + return errors.Is(err, errOutOfRange{}) || isInterface[outOfRange](err) +} + +type errNotImplemented struct{} + +func (errNotImplemented) Error() string { return "not implemented" } + +func (errNotImplemented) NotImplemented() {} + +func (e errNotImplemented) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// notImplemented maps to Moby's "ErrNotImplemented" +type notImplemented interface { + NotImplemented() +} + +// IsNotImplemented returns true if the error is due to not being implemented +func IsNotImplemented(err error) bool { + return errors.Is(err, errNotImplemented{}) || isInterface[notImplemented](err) +} + +type errInternal struct{} + +func (errInternal) Error() string { return "internal" } + +func (errInternal) System() {} + +func (e errInternal) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// system maps to Moby's "ErrSystem" +type system interface { + System() +} + +// IsInternal returns true if the error returns to an internal or system error +func IsInternal(err error) bool { + return errors.Is(err, errInternal{}) || isInterface[system](err) +} + +type errUnavailable struct{} + +func (errUnavailable) Error() string { return "unavailable" } + +func (errUnavailable) Unavailable() {} + +func (e errUnavailable) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// unavailable maps to Moby's "ErrUnavailable" +type unavailable interface { + Unavailable() +} + +// IsUnavailable returns true if the error is due to a resource being unavailable +func IsUnavailable(err error) bool { + return errors.Is(err, errUnavailable{}) || isInterface[unavailable](err) +} + +type errDataLoss struct{} + +func (errDataLoss) Error() string { return "data loss" } + +func (errDataLoss) DataLoss() {} + +func (e errDataLoss) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// dataLoss maps to Moby's "ErrDataLoss" +type dataLoss interface { + DataLoss() +} + +// IsDataLoss returns true if data during an operation was lost or corrupted +func IsDataLoss(err error) bool { + return errors.Is(err, errDataLoss{}) || isInterface[dataLoss](err) +} + +type errUnauthorized struct{} + +func (errUnauthorized) Error() string { return "unauthorized" } + +func (errUnauthorized) Unauthorized() {} + +func (e errUnauthorized) WithMessage(msg string) error { + return customMessage{e, msg} +} + +// unauthorized maps to Moby's "ErrUnauthorized" +type unauthorized interface { + Unauthorized() +} + +// IsUnauthorized returns true if the error indicates that the user was +// unauthenticated or unauthorized. +func IsUnauthorized(err error) bool { + return errors.Is(err, errUnauthorized{}) || isInterface[unauthorized](err) +} + +func isInterface[T any](err error) bool { + for { + switch x := err.(type) { + case T: + return true + case customMessage: + err = x.err + case interface{ Unwrap() error }: + err = x.Unwrap() + if err == nil { + return false + } + case interface{ Unwrap() []error }: + for _, err := range x.Unwrap() { + if isInterface[T](err) { + return true + } + } + return false + default: + return false + } + } +} + +// customMessage is used to provide a defined error with a custom message. +// The message is not wrapped but can be compared by the `Is(error) bool` interface. +type customMessage struct { + err error + msg string +} + +func (c customMessage) Is(err error) bool { + return c.err == err +} + +func (c customMessage) As(target any) bool { + return errors.As(c.err, target) +} + +func (c customMessage) Error() string { + return c.msg +} diff --git a/vendor/github.com/containerd/errdefs/resolve.go b/vendor/github.com/containerd/errdefs/resolve.go new file mode 100644 index 000000000..c02d4a73f --- /dev/null +++ b/vendor/github.com/containerd/errdefs/resolve.go @@ -0,0 +1,147 @@ +/* + Copyright The containerd 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 errdefs + +import "context" + +// Resolve returns the first error found in the error chain which matches an +// error defined in this package or context error. A raw, unwrapped error is +// returned or ErrUnknown if no matching error is found. +// +// This is useful for determining a response code based on the outermost wrapped +// error rather than the original cause. For example, a not found error deep +// in the code may be wrapped as an invalid argument. When determining status +// code from Is* functions, the depth or ordering of the error is not +// considered. +// +// The search order is depth first, a wrapped error returned from any part of +// the chain from `Unwrap() error` will be returned before any joined errors +// as returned by `Unwrap() []error`. +func Resolve(err error) error { + if err == nil { + return nil + } + err = firstError(err) + if err == nil { + err = ErrUnknown + } + return err +} + +func firstError(err error) error { + for { + switch err { + case ErrUnknown, + ErrInvalidArgument, + ErrNotFound, + ErrAlreadyExists, + ErrPermissionDenied, + ErrResourceExhausted, + ErrFailedPrecondition, + ErrConflict, + ErrNotModified, + ErrAborted, + ErrOutOfRange, + ErrNotImplemented, + ErrInternal, + ErrUnavailable, + ErrDataLoss, + ErrUnauthenticated, + context.DeadlineExceeded, + context.Canceled: + return err + } + switch e := err.(type) { + case customMessage: + err = e.err + case unknown: + return ErrUnknown + case invalidParameter: + return ErrInvalidArgument + case notFound: + return ErrNotFound + case alreadyExists: + return ErrAlreadyExists + case forbidden: + return ErrPermissionDenied + case resourceExhausted: + return ErrResourceExhausted + case failedPrecondition: + return ErrFailedPrecondition + case conflict: + return ErrConflict + case notModified: + return ErrNotModified + case aborted: + return ErrAborted + case errOutOfRange: + return ErrOutOfRange + case notImplemented: + return ErrNotImplemented + case system: + return ErrInternal + case unavailable: + return ErrUnavailable + case dataLoss: + return ErrDataLoss + case unauthorized: + return ErrUnauthenticated + case deadlineExceeded: + return context.DeadlineExceeded + case cancelled: + return context.Canceled + case interface{ Unwrap() error }: + err = e.Unwrap() + if err == nil { + return nil + } + case interface{ Unwrap() []error }: + for _, ue := range e.Unwrap() { + if fe := firstError(ue); fe != nil { + return fe + } + } + return nil + case interface{ Is(error) bool }: + for _, target := range []error{ErrUnknown, + ErrInvalidArgument, + ErrNotFound, + ErrAlreadyExists, + ErrPermissionDenied, + ErrResourceExhausted, + ErrFailedPrecondition, + ErrConflict, + ErrNotModified, + ErrAborted, + ErrOutOfRange, + ErrNotImplemented, + ErrInternal, + ErrUnavailable, + ErrDataLoss, + ErrUnauthenticated, + context.DeadlineExceeded, + context.Canceled} { + if e.Is(target) { + return target + } + } + return nil + default: + return nil + } + } +} diff --git a/vendor/github.com/containerd/platforms/.gitattributes b/vendor/github.com/containerd/platforms/.gitattributes new file mode 100644 index 000000000..a0717e4b3 --- /dev/null +++ b/vendor/github.com/containerd/platforms/.gitattributes @@ -0,0 +1 @@ +*.go text eol=lf \ No newline at end of file diff --git a/vendor/github.com/containerd/platforms/.golangci.yml b/vendor/github.com/containerd/platforms/.golangci.yml new file mode 100644 index 000000000..a695775df --- /dev/null +++ b/vendor/github.com/containerd/platforms/.golangci.yml @@ -0,0 +1,30 @@ +linters: + enable: + - exportloopref # Checks for pointers to enclosing loop variables + - gofmt + - goimports + - gosec + - ineffassign + - misspell + - nolintlint + - revive + - staticcheck + - tenv # Detects using os.Setenv instead of t.Setenv since Go 1.17 + - unconvert + - unused + - vet + - dupword # Checks for duplicate words in the source code + disable: + - errcheck + +run: + timeout: 5m + skip-dirs: + - api + - cluster + - design + - docs + - docs/man + - releases + - reports + - test # e2e scripts diff --git a/vendor/github.com/containerd/platforms/LICENSE b/vendor/github.com/containerd/platforms/LICENSE new file mode 100644 index 000000000..584149b6e --- /dev/null +++ b/vendor/github.com/containerd/platforms/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://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 + + Copyright The containerd 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 + + https://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/containerd/platforms/README.md b/vendor/github.com/containerd/platforms/README.md new file mode 100644 index 000000000..2059de771 --- /dev/null +++ b/vendor/github.com/containerd/platforms/README.md @@ -0,0 +1,32 @@ +# platforms + +A Go package for formatting, normalizing and matching container platforms. + +This package is based on the Open Containers Image Spec definition of a [platform](https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/descriptor.go#L52). + +## Platform Specifier + +While the OCI platform specifications provide a tool for components to +specify structured information, user input typically doesn't need the full +context and much can be inferred. To solve this problem, this package introduces +"specifiers". A specifier has the format +`||/[/]`. The user can provide either the +operating system or the architecture or both. + +An example of a common specifier is `linux/amd64`. If the host has a default +runtime that matches this, the user can simply provide the component that +matters. For example, if an image provides `amd64` and `arm64` support, the +operating system, `linux` can be inferred, so they only have to provide +`arm64` or `amd64`. Similar behavior is implemented for operating systems, +where the architecture may be known but a runtime may support images from +different operating systems. + +## Project details + +**platforms** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). +As a containerd sub-project, you will find the: + * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), + * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), + * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) + +information in our [`containerd/project`](https://github.com/containerd/project) repository. \ No newline at end of file diff --git a/vendor/github.com/containerd/containerd/platforms/compare.go b/vendor/github.com/containerd/platforms/compare.go similarity index 100% rename from vendor/github.com/containerd/containerd/platforms/compare.go rename to vendor/github.com/containerd/platforms/compare.go diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go b/vendor/github.com/containerd/platforms/cpuinfo.go similarity index 96% rename from vendor/github.com/containerd/containerd/platforms/cpuinfo.go rename to vendor/github.com/containerd/platforms/cpuinfo.go index 8c600fc96..91f50e8c8 100644 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go +++ b/vendor/github.com/containerd/platforms/cpuinfo.go @@ -20,7 +20,7 @@ import ( "runtime" "sync" - "github.com/containerd/containerd/log" + "github.com/containerd/log" ) // Present the ARM instruction set architecture, eg: v7, v8 diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go b/vendor/github.com/containerd/platforms/cpuinfo_linux.go similarity index 94% rename from vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go rename to vendor/github.com/containerd/platforms/cpuinfo_linux.go index 722d86c35..98c7001f9 100644 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go +++ b/vendor/github.com/containerd/platforms/cpuinfo_linux.go @@ -19,12 +19,12 @@ package platforms import ( "bufio" "bytes" + "errors" "fmt" "os" "runtime" "strings" - "github.com/containerd/containerd/errdefs" "golang.org/x/sys/unix" ) @@ -70,7 +70,7 @@ func getCPUInfo(pattern string) (info string, err error) { return "", err } - return "", fmt.Errorf("getCPUInfo for pattern %s: %w", pattern, errdefs.ErrNotFound) + return "", fmt.Errorf("getCPUInfo for pattern %s: %w", pattern, errNotFound) } // getCPUVariantFromArch get CPU variant from arch through a system call @@ -83,7 +83,7 @@ func getCPUVariantFromArch(arch string) (string, error) { if arch == "aarch64" { variant = "8" } else if arch[0:4] == "armv" && len(arch) >= 5 { - //Valid arch format is in form of armvXx + // Valid arch format is in form of armvXx switch arch[3:5] { case "v8": variant = "8" @@ -101,7 +101,7 @@ func getCPUVariantFromArch(arch string) (string, error) { variant = "unknown" } } else { - return "", fmt.Errorf("getCPUVariantFromArch invalid arch: %s, %w", arch, errdefs.ErrInvalidArgument) + return "", fmt.Errorf("getCPUVariantFromArch invalid arch: %s, %w", arch, errInvalidArgument) } return variant, nil } @@ -112,11 +112,10 @@ func getCPUVariantFromArch(arch string) (string, error) { // This is to cover running ARM in emulated environment on x86 host as this field in /proc/cpuinfo // was not present. func getCPUVariant() (string, error) { - variant, err := getCPUInfo("Cpu architecture") if err != nil { - if errdefs.IsNotFound(err) { - //Let's try getting CPU variant from machine architecture + if errors.Is(err, errNotFound) { + // Let's try getting CPU variant from machine architecture arch, err := getMachineArch() if err != nil { return "", fmt.Errorf("failure getting machine architecture: %v", err) diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go b/vendor/github.com/containerd/platforms/cpuinfo_other.go similarity index 94% rename from vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go rename to vendor/github.com/containerd/platforms/cpuinfo_other.go index fa5f19c42..97a1fe8a3 100644 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go +++ b/vendor/github.com/containerd/platforms/cpuinfo_other.go @@ -21,8 +21,6 @@ package platforms import ( "fmt" "runtime" - - "github.com/containerd/containerd/errdefs" ) func getCPUVariant() (string, error) { @@ -49,10 +47,8 @@ func getCPUVariant() (string, error) { default: variant = "unknown" } - } else { - return "", fmt.Errorf("getCPUVariant for OS %s: %v", runtime.GOOS, errdefs.ErrNotImplemented) - + return "", fmt.Errorf("getCPUVariant for OS %s: %v", runtime.GOOS, errNotImplemented) } return variant, nil diff --git a/vendor/github.com/containerd/containerd/platforms/database.go b/vendor/github.com/containerd/platforms/database.go similarity index 100% rename from vendor/github.com/containerd/containerd/platforms/database.go rename to vendor/github.com/containerd/platforms/database.go diff --git a/vendor/github.com/containerd/containerd/platforms/defaults.go b/vendor/github.com/containerd/platforms/defaults.go similarity index 81% rename from vendor/github.com/containerd/containerd/platforms/defaults.go rename to vendor/github.com/containerd/platforms/defaults.go index cfa3ff34a..9d898d60e 100644 --- a/vendor/github.com/containerd/containerd/platforms/defaults.go +++ b/vendor/github.com/containerd/platforms/defaults.go @@ -16,9 +16,11 @@ package platforms -// DefaultString returns the default string specifier for the platform. +// DefaultString returns the default string specifier for the platform, +// with [PR#6](https://github.com/containerd/platforms/pull/6) the result +// may now also include the OSVersion from the provided platform specification. func DefaultString() string { - return Format(DefaultSpec()) + return FormatAll(DefaultSpec()) } // DefaultStrict returns strict form of Default. diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_darwin.go b/vendor/github.com/containerd/platforms/defaults_darwin.go similarity index 100% rename from vendor/github.com/containerd/containerd/platforms/defaults_darwin.go rename to vendor/github.com/containerd/platforms/defaults_darwin.go diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_freebsd.go b/vendor/github.com/containerd/platforms/defaults_freebsd.go similarity index 100% rename from vendor/github.com/containerd/containerd/platforms/defaults_freebsd.go rename to vendor/github.com/containerd/platforms/defaults_freebsd.go diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_unix.go b/vendor/github.com/containerd/platforms/defaults_unix.go similarity index 100% rename from vendor/github.com/containerd/containerd/platforms/defaults_unix.go rename to vendor/github.com/containerd/platforms/defaults_unix.go diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go b/vendor/github.com/containerd/platforms/defaults_windows.go similarity index 88% rename from vendor/github.com/containerd/containerd/platforms/defaults_windows.go rename to vendor/github.com/containerd/platforms/defaults_windows.go index d10fa9012..427ed72eb 100644 --- a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go +++ b/vendor/github.com/containerd/platforms/defaults_windows.go @@ -22,7 +22,6 @@ import ( "strconv" "strings" - "github.com/Microsoft/hcsshim/osversion" specs "github.com/opencontainers/image-spec/specs-go/v1" "golang.org/x/sys/windows" ) @@ -52,29 +51,29 @@ func (m windowsmatcher) Match(p specs.Platform) bool { if match && m.OS == "windows" { // HPC containers do not have OS version filled - if p.OSVersion == "" { + if m.OSVersion == "" || p.OSVersion == "" { return true } - hostOsVersion := GetOsVersion(m.osVersionPrefix) - ctrOsVersion := GetOsVersion(p.OSVersion) - return osversion.CheckHostAndContainerCompat(hostOsVersion, ctrOsVersion) + hostOsVersion := getOSVersion(m.osVersionPrefix) + ctrOsVersion := getOSVersion(p.OSVersion) + return checkHostAndContainerCompat(hostOsVersion, ctrOsVersion) } return match } -func GetOsVersion(osVersionPrefix string) osversion.OSVersion { +func getOSVersion(osVersionPrefix string) osVersion { parts := strings.Split(osVersionPrefix, ".") if len(parts) < 3 { - return osversion.OSVersion{} + return osVersion{} } majorVersion, _ := strconv.Atoi(parts[0]) minorVersion, _ := strconv.Atoi(parts[1]) buildNumber, _ := strconv.Atoi(parts[2]) - return osversion.OSVersion{ + return osVersion{ MajorVersion: uint8(majorVersion), MinorVersion: uint8(minorVersion), Build: uint16(buildNumber), diff --git a/vendor/github.com/containerd/platforms/errors.go b/vendor/github.com/containerd/platforms/errors.go new file mode 100644 index 000000000..5ad721e77 --- /dev/null +++ b/vendor/github.com/containerd/platforms/errors.go @@ -0,0 +1,30 @@ +/* + Copyright The containerd 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 platforms + +import "errors" + +// These errors mirror the errors defined in [github.com/containerd/containerd/errdefs], +// however, they are not exported as they are not expected to be used as sentinel +// errors by consumers of this package. +// +//nolint:unused // not all errors are used on all platforms. +var ( + errNotFound = errors.New("not found") + errInvalidArgument = errors.New("invalid argument") + errNotImplemented = errors.New("not implemented") +) diff --git a/vendor/github.com/containerd/platforms/platform_compat_windows.go b/vendor/github.com/containerd/platforms/platform_compat_windows.go new file mode 100644 index 000000000..89e66f0c0 --- /dev/null +++ b/vendor/github.com/containerd/platforms/platform_compat_windows.go @@ -0,0 +1,78 @@ +/* + Copyright The containerd 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 platforms + +// osVersion is a wrapper for Windows version information +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx +type osVersion struct { + Version uint32 + MajorVersion uint8 + MinorVersion uint8 + Build uint16 +} + +// Windows Client and Server build numbers. +// +// See: +// https://learn.microsoft.com/en-us/windows/release-health/release-information +// https://learn.microsoft.com/en-us/windows/release-health/windows-server-release-info +// https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information +const ( + // rs5 (version 1809, codename "Redstone 5") corresponds to Windows Server + // 2019 (ltsc2019), and Windows 10 (October 2018 Update). + rs5 = 17763 + + // v21H2Server corresponds to Windows Server 2022 (ltsc2022). + v21H2Server = 20348 + + // v22H2Win11 corresponds to Windows 11 (2022 Update). + v22H2Win11 = 22621 +) + +// List of stable ABI compliant ltsc releases +// Note: List must be sorted in ascending order +var compatLTSCReleases = []uint16{ + v21H2Server, +} + +// CheckHostAndContainerCompat checks if given host and container +// OS versions are compatible. +// It includes support for stable ABI compliant versions as well. +// Every release after WS 2022 will support the previous ltsc +// container image. Stable ABI is in preview mode for windows 11 client. +// Refer: https://learn.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility?tabs=windows-server-2022%2Cwindows-10#windows-server-host-os-compatibility +func checkHostAndContainerCompat(host, ctr osVersion) bool { + // check major minor versions of host and guest + if host.MajorVersion != ctr.MajorVersion || + host.MinorVersion != ctr.MinorVersion { + return false + } + + // If host is < WS 2022, exact version match is required + if host.Build < v21H2Server { + return host.Build == ctr.Build + } + + var supportedLtscRelease uint16 + for i := len(compatLTSCReleases) - 1; i >= 0; i-- { + if host.Build >= compatLTSCReleases[i] { + supportedLtscRelease = compatLTSCReleases[i] + break + } + } + return ctr.Build >= supportedLtscRelease && ctr.Build <= host.Build +} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms.go b/vendor/github.com/containerd/platforms/platforms.go similarity index 74% rename from vendor/github.com/containerd/containerd/platforms/platforms.go rename to vendor/github.com/containerd/platforms/platforms.go index 56613b076..1bbbdb91d 100644 --- a/vendor/github.com/containerd/containerd/platforms/platforms.go +++ b/vendor/github.com/containerd/platforms/platforms.go @@ -102,6 +102,9 @@ // unless it is explicitly provided. This is treated as equivalent to armhf. A // previous architecture, armel, will be normalized to arm/v6. // +// Similarly, the most common arm64 version v8, and most common amd64 version v1 +// are represented without the variant. +// // While these normalizations are provided, their support on arm platforms has // not yet been fully implemented and tested. package platforms @@ -115,14 +118,15 @@ import ( "strings" specs "github.com/opencontainers/image-spec/specs-go/v1" - - "github.com/containerd/containerd/errdefs" ) var ( - specifierRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) + specifierRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) + osAndVersionRe = regexp.MustCompile(`^([A-Za-z0-9_-]+)(?:\(([A-Za-z0-9_.-]*)\))?$`) ) +const osAndVersionFormat = "%s(%s)" + // Platform is a type alias for convenience, so there is no need to import image-spec package everywhere. type Platform = specs.Platform @@ -155,40 +159,68 @@ func (m *matcher) Match(platform specs.Platform) bool { } func (m *matcher) String() string { - return Format(m.Platform) + return FormatAll(m.Platform) +} + +// ParseAll parses a list of platform specifiers into a list of platform. +func ParseAll(specifiers []string) ([]specs.Platform, error) { + platforms := make([]specs.Platform, len(specifiers)) + for i, s := range specifiers { + p, err := Parse(s) + if err != nil { + return nil, fmt.Errorf("invalid platform %s: %w", s, err) + } + platforms[i] = p + } + return platforms, nil } // Parse parses the platform specifier syntax into a platform declaration. // -// Platform specifiers are in the format `||/[/]`. +// Platform specifiers are in the format `[()]||[()]/[/]`. // The minimum required information for a platform specifier is the operating -// system or architecture. If there is only a single string (no slashes), the +// system or architecture. The OSVersion can be part of the OS like `windows(10.0.17763)` +// When an OSVersion is specified, then specs.Platform.OSVersion is populated with that value, +// and an empty string otherwise. +// If there is only a single string (no slashes), the // value will be matched against the known set of operating systems, then fall // back to the known set of architectures. The missing component will be // inferred based on the local environment. func Parse(specifier string) (specs.Platform, error) { if strings.Contains(specifier, "*") { // TODO(stevvooe): need to work out exact wildcard handling - return specs.Platform{}, fmt.Errorf("%q: wildcards not yet supported: %w", specifier, errdefs.ErrInvalidArgument) + return specs.Platform{}, fmt.Errorf("%q: wildcards not yet supported: %w", specifier, errInvalidArgument) } - parts := strings.Split(specifier, "/") + // Limit to 4 elements to prevent unbounded split + parts := strings.SplitN(specifier, "/", 4) - for _, part := range parts { - if !specifierRe.MatchString(part) { - return specs.Platform{}, fmt.Errorf("%q is an invalid component of %q: platform specifier component must match %q: %w", part, specifier, specifierRe.String(), errdefs.ErrInvalidArgument) + var p specs.Platform + for i, part := range parts { + if i == 0 { + // First element is [()] + osVer := osAndVersionRe.FindStringSubmatch(part) + if osVer == nil { + return specs.Platform{}, fmt.Errorf("%q is an invalid OS component of %q: OSAndVersion specifier component must match %q: %w", part, specifier, osAndVersionRe.String(), errInvalidArgument) + } + + p.OS = normalizeOS(osVer[1]) + p.OSVersion = osVer[2] + } else { + if !specifierRe.MatchString(part) { + return specs.Platform{}, fmt.Errorf("%q is an invalid component of %q: platform specifier component must match %q: %w", part, specifier, specifierRe.String(), errInvalidArgument) + } } } - var p specs.Platform switch len(parts) { case 1: - // in this case, we will test that the value might be an OS, then look - // it up. If it is not known, we'll treat it as an architecture. Since + // in this case, we will test that the value might be an OS (with or + // without the optional OSVersion specified) and look it up. + // If it is not known, we'll treat it as an architecture. Since // we have very little information about the platform here, we are // going to be a little more strict if we don't know about the argument // value. - p.OS = normalizeOS(parts[0]) if isKnownOS(p.OS) { // picks a default architecture p.Architecture = runtime.GOARCH @@ -196,10 +228,6 @@ func Parse(specifier string) (specs.Platform, error) { p.Variant = cpuVariant() } - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - return p, nil } @@ -212,37 +240,27 @@ func Parse(specifier string) (specs.Platform, error) { return p, nil } - return specs.Platform{}, fmt.Errorf("%q: unknown operating system or architecture: %w", specifier, errdefs.ErrInvalidArgument) + return specs.Platform{}, fmt.Errorf("%q: unknown operating system or architecture: %w", specifier, errInvalidArgument) case 2: - // In this case, we treat as a regular os/arch pair. We don't care + // In this case, we treat as a regular OS[(OSVersion)]/arch pair. We don't care // about whether or not we know of the platform. - p.OS = normalizeOS(parts[0]) p.Architecture, p.Variant = normalizeArch(parts[1], "") if p.Architecture == "arm" && p.Variant == "v7" { p.Variant = "" } - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - return p, nil case 3: // we have a fully specified variant, this is rare - p.OS = normalizeOS(parts[0]) p.Architecture, p.Variant = normalizeArch(parts[1], parts[2]) if p.Architecture == "arm64" && p.Variant == "" { p.Variant = "v8" } - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - return p, nil } - return specs.Platform{}, fmt.Errorf("%q: cannot parse platform specifier: %w", specifier, errdefs.ErrInvalidArgument) + return specs.Platform{}, fmt.Errorf("%q: cannot parse platform specifier: %w", specifier, errInvalidArgument) } // MustParse is like Parses but panics if the specifier cannot be parsed. @@ -264,6 +282,20 @@ func Format(platform specs.Platform) string { return path.Join(platform.OS, platform.Architecture, platform.Variant) } +// FormatAll returns a string specifier that also includes the OSVersion from the +// provided platform specification. +func FormatAll(platform specs.Platform) string { + if platform.OS == "" { + return "unknown" + } + + if platform.OSVersion != "" { + OSAndVersion := fmt.Sprintf(osAndVersionFormat, platform.OS, platform.OSVersion) + return path.Join(OSAndVersion, platform.Architecture, platform.Variant) + } + return path.Join(platform.OS, platform.Architecture, platform.Variant) +} + // Normalize validates and translate the platform to the canonical value. // // For example, if "Aarch64" is encountered, we change it to "arm64" or if diff --git a/vendor/github.com/containerd/containerd/platforms/platforms_other.go b/vendor/github.com/containerd/platforms/platforms_other.go similarity index 94% rename from vendor/github.com/containerd/containerd/platforms/platforms_other.go rename to vendor/github.com/containerd/platforms/platforms_other.go index 59beeb3d1..03f4dcd99 100644 --- a/vendor/github.com/containerd/containerd/platforms/platforms_other.go +++ b/vendor/github.com/containerd/platforms/platforms_other.go @@ -28,7 +28,3 @@ func newDefaultMatcher(platform specs.Platform) Matcher { Platform: Normalize(platform), } } - -func GetWindowsOsVersion() string { - return "" -} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms_windows.go b/vendor/github.com/containerd/platforms/platforms_windows.go similarity index 85% rename from vendor/github.com/containerd/containerd/platforms/platforms_windows.go rename to vendor/github.com/containerd/platforms/platforms_windows.go index 733d18dde..950e2a2dd 100644 --- a/vendor/github.com/containerd/containerd/platforms/platforms_windows.go +++ b/vendor/github.com/containerd/platforms/platforms_windows.go @@ -17,10 +17,7 @@ package platforms import ( - "fmt" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sys/windows" ) // NewMatcher returns a Windows matcher that will match on osVersionPrefix if @@ -35,8 +32,3 @@ func newDefaultMatcher(platform specs.Platform) Matcher { }, } } - -func GetWindowsOsVersion() string { - major, minor, build := windows.RtlGetNtVersionNumbers() - return fmt.Sprintf("%d.%d.%d", major, minor, build) -} diff --git a/vendor/github.com/cyphar/filepath-securejoin/CHANGELOG.md b/vendor/github.com/cyphar/filepath-securejoin/CHANGELOG.md index 7436896e1..04b5685ab 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/CHANGELOG.md +++ b/vendor/github.com/cyphar/filepath-securejoin/CHANGELOG.md @@ -6,6 +6,43 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ## +## [0.3.4] - 2024-10-09 ## + +### Fixed ### +- Previously, some testing mocks we had resulted in us doing `import "testing"` + in non-`_test.go` code, which made some downstreams like Kubernetes unhappy. + This has been fixed. (#32) + +## [0.3.3] - 2024-09-30 ## + +### Fixed ### +- The mode and owner verification logic in `MkdirAll` has been removed. This + was originally intended to protect against some theoretical attacks but upon + further consideration these protections don't actually buy us anything and + they were causing spurious errors with more complicated filesystem setups. +- The "is the created directory empty" logic in `MkdirAll` has also been + removed. This was not causing us issues yet, but some pseudofilesystems (such + as `cgroup`) create non-empty directories and so this logic would've been + wrong for such cases. + +## [0.3.2] - 2024-09-13 ## + +### Changed ### +- Passing the `S_ISUID` or `S_ISGID` modes to `MkdirAllInRoot` will now return + an explicit error saying that those bits are ignored by `mkdirat(2)`. In the + past a different error was returned, but since the silent ignoring behaviour + is codified in the man pages a more explicit error seems apt. While silently + ignoring these bits would be the most compatible option, it could lead to + users thinking their code sets these bits when it doesn't. Programs that need + to deal with compatibility can mask the bits themselves. (#23, #25) + +### Fixed ### +- If a directory has `S_ISGID` set, then all child directories will have + `S_ISGID` set when created and a different gid will be used for any inode + created under the directory. Previously, the "expected owner and mode" + validation in `securejoin.MkdirAll` did not correctly handle this. We now + correctly handle this case. (#24, #25) + ## [0.3.1] - 2024-07-23 ## ### Changed ### @@ -127,7 +164,10 @@ This is our first release of `github.com/cyphar/filepath-securejoin`, containing a full implementation with a coverage of 93.5% (the only missing cases are the error cases, which are hard to mocktest at the moment). -[Unreleased]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.1...HEAD +[Unreleased]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.4...HEAD +[0.3.3]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.3...v0.3.4 +[0.3.3]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.2...v0.3.3 +[0.3.2]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.1...v0.3.2 [0.3.1]: https://github.com/cyphar/filepath-securejoin/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/cyphar/filepath-securejoin/compare/v0.2.5...v0.3.0 [0.2.5]: https://github.com/cyphar/filepath-securejoin/compare/v0.2.4...v0.2.5 diff --git a/vendor/github.com/cyphar/filepath-securejoin/README.md b/vendor/github.com/cyphar/filepath-securejoin/README.md index 253956f86..eaeb53fcd 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/README.md +++ b/vendor/github.com/cyphar/filepath-securejoin/README.md @@ -1,5 +1,6 @@ ## `filepath-securejoin` ## +[![Go Documentation](https://pkg.go.dev/badge/github.com/cyphar/filepath-securejoin.svg)](https://pkg.go.dev/github.com/cyphar/filepath-securejoin) [![Build Status](https://github.com/cyphar/filepath-securejoin/actions/workflows/ci.yml/badge.svg)](https://github.com/cyphar/filepath-securejoin/actions/workflows/ci.yml) ### Old API ### @@ -85,7 +86,7 @@ more secure. In particular: or avoid being tricked by a `/proc` that is not legitimate. This is done using [`openat2`][openat2.2] for all users, and privileged users will also be further protected by using [`fsopen`][fsopen.2] and [`open_tree`][open_tree.2] - (Linux 4.18 or later). + (Linux 5.2 or later). [openat2.2]: https://www.man7.org/linux/man-pages/man2/openat2.2.html [fsopen.2]: https://github.com/brauner/man-pages-md/blob/main/fsopen.md diff --git a/vendor/github.com/cyphar/filepath-securejoin/VERSION b/vendor/github.com/cyphar/filepath-securejoin/VERSION index 9e11b32fc..42045acae 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/VERSION +++ b/vendor/github.com/cyphar/filepath-securejoin/VERSION @@ -1 +1 @@ -0.3.1 +0.3.4 diff --git a/vendor/github.com/cyphar/filepath-securejoin/doc.go b/vendor/github.com/cyphar/filepath-securejoin/doc.go new file mode 100644 index 000000000..1ec7d065e --- /dev/null +++ b/vendor/github.com/cyphar/filepath-securejoin/doc.go @@ -0,0 +1,39 @@ +// Copyright (C) 2014-2015 Docker Inc & Go Authors. All rights reserved. +// Copyright (C) 2017-2024 SUSE LLC. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package securejoin implements a set of helpers to make it easier to write Go +// code that is safe against symlink-related escape attacks. The primary idea +// is to let you resolve a path within a rootfs directory as if the rootfs was +// a chroot. +// +// securejoin has two APIs, a "legacy" API and a "modern" API. +// +// The legacy API is [SecureJoin] and [SecureJoinVFS]. These methods are +// **not** safe against race conditions where an attacker changes the +// filesystem after (or during) the [SecureJoin] operation. +// +// The new API is made up of [OpenInRoot] and [MkdirAll] (and derived +// functions). These are safe against racing attackers and have several other +// protections that are not provided by the legacy API. There are many more +// operations that most programs expect to be able to do safely, but we do not +// provide explicit support for them because we want to encourage users to +// switch to [libpathrs](https://github.com/openSUSE/libpathrs) which is a +// cross-language next-generation library that is entirely designed around +// operating on paths safely. +// +// securejoin has been used by several container runtimes (Docker, runc, +// Kubernetes, etc) for quite a few years as a de-facto standard for operating +// on container filesystem paths "safely". However, most users still use the +// legacy API which is unsafe against various attacks (there is a fairly long +// history of CVEs in dependent as a result). Users should switch to the modern +// API as soon as possible (or even better, switch to libpathrs). +// +// This project was initially intended to be included in the Go standard +// library, but [it was rejected](https://go.dev/issue/20126). There is now a +// [new Go proposal](https://go.dev/issue/67002) for a safe path resolution API +// that shares some of the goals of filepath-securejoin. However, that design +// is intended to work like `openat2(RESOLVE_BENEATH)` which does not fit the +// usecase of container runtimes and most system tools. +package securejoin diff --git a/vendor/github.com/cyphar/filepath-securejoin/join.go b/vendor/github.com/cyphar/filepath-securejoin/join.go index bd86a48b0..e0ee3f2b5 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/join.go +++ b/vendor/github.com/cyphar/filepath-securejoin/join.go @@ -3,11 +3,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package securejoin is an implementation of the hopefully-soon-to-be-included -// SecureJoin helper that is meant to be part of the "path/filepath" package. -// The purpose of this project is to provide a PoC implementation to make the -// SecureJoin proposal (https://github.com/golang/go/issues/20126) more -// tangible. package securejoin import ( @@ -22,27 +17,27 @@ const maxSymlinkLimit = 255 // IsNotExist tells you if err is an error that implies that either the path // accessed does not exist (or path components don't exist). This is -// effectively a more broad version of os.IsNotExist. +// effectively a more broad version of [os.IsNotExist]. func IsNotExist(err error) bool { // Check that it's not actually an ENOTDIR, which in some cases is a more // convoluted case of ENOENT (usually involving weird paths). return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) || errors.Is(err, syscall.ENOENT) } -// SecureJoinVFS joins the two given path components (similar to Join) except +// SecureJoinVFS joins the two given path components (similar to [filepath.Join]) except // that the returned path is guaranteed to be scoped inside the provided root // path (when evaluated). Any symbolic links in the path are evaluated with the // given root treated as the root of the filesystem, similar to a chroot. The -// filesystem state is evaluated through the given VFS interface (if nil, the -// standard os.* family of functions are used). +// filesystem state is evaluated through the given [VFS] interface (if nil, the +// standard [os].* family of functions are used). // // Note that the guarantees provided by this function only apply if the path // components in the returned string are not modified (in other words are not // replaced with symlinks on the filesystem) after this function has returned. -// Such a symlink race is necessarily out-of-scope of SecureJoin. +// Such a symlink race is necessarily out-of-scope of SecureJoinVFS. // // NOTE: Due to the above limitation, Linux users are strongly encouraged to -// use OpenInRoot instead, which does safely protect against these kinds of +// use [OpenInRoot] instead, which does safely protect against these kinds of // attacks. There is no way to solve this problem with SecureJoinVFS because // the API is fundamentally wrong (you cannot return a "safe" path string and // guarantee it won't be modified afterwards). @@ -123,8 +118,8 @@ func SecureJoinVFS(root, unsafePath string, vfs VFS) (string, error) { return filepath.Join(root, finalPath), nil } -// SecureJoin is a wrapper around SecureJoinVFS that just uses the os.* library -// of functions as the VFS. If in doubt, use this function over SecureJoinVFS. +// SecureJoin is a wrapper around [SecureJoinVFS] that just uses the [os].* library +// of functions as the [VFS]. If in doubt, use this function over [SecureJoinVFS]. func SecureJoin(root, unsafePath string) (string, error) { return SecureJoinVFS(root, unsafePath, nil) } diff --git a/vendor/github.com/cyphar/filepath-securejoin/mkdir_linux.go b/vendor/github.com/cyphar/filepath-securejoin/mkdir_linux.go index ad2bd7973..b5f674524 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/mkdir_linux.go +++ b/vendor/github.com/cyphar/filepath-securejoin/mkdir_linux.go @@ -9,7 +9,6 @@ package securejoin import ( "errors" "fmt" - "io" "os" "path/filepath" "slices" @@ -23,29 +22,36 @@ var ( errPossibleAttack = errors.New("possible attack detected") ) -// MkdirAllHandle is equivalent to MkdirAll, except that it is safer to use in -// two respects: +// MkdirAllHandle is equivalent to [MkdirAll], except that it is safer to use +// in two respects: // -// - The caller provides the root directory as an *os.File (preferably O_PATH) +// - The caller provides the root directory as an *[os.File] (preferably O_PATH) // handle. This means that the caller can be sure which root directory is // being used. Note that this can be emulated by using /proc/self/fd/... as -// the root path with MkdirAll. +// the root path with [os.MkdirAll]. // -// - Once all of the directories have been created, an *os.File (O_PATH) handle +// - Once all of the directories have been created, an *[os.File] O_PATH handle // to the directory at unsafePath is returned to the caller. This is done in // an effectively-race-free way (an attacker would only be able to swap the // final directory component), which is not possible to emulate with -// MkdirAll. +// [MkdirAll]. // // In addition, the returned handle is obtained far more efficiently than doing -// a brand new lookup of unsafePath (such as with SecureJoin or openat2) after -// doing MkdirAll. If you intend to open the directory after creating it, you +// a brand new lookup of unsafePath (such as with [SecureJoin] or openat2) after +// doing [MkdirAll]. If you intend to open the directory after creating it, you // should use MkdirAllHandle. func MkdirAllHandle(root *os.File, unsafePath string, mode int) (_ *os.File, Err error) { // Make sure there are no os.FileMode bits set. if mode&^0o7777 != 0 { return nil, fmt.Errorf("%w for mkdir 0o%.3o", errInvalidMode, mode) } + // On Linux, mkdirat(2) (and os.Mkdir) silently ignore the suid and sgid + // bits. We could also silently ignore them but since we have very few + // users it seems more prudent to return an error so users notice that + // these bits will not be set. + if mode&^0o1777 != 0 { + return nil, fmt.Errorf("%w for mkdir 0o%.3o: suid and sgid are ignored by mkdir", errInvalidMode, mode) + } // Try to open as much of the path as possible. currentDir, remainingPath, err := partialLookupInRoot(root, unsafePath) @@ -101,24 +107,6 @@ func MkdirAllHandle(root *os.File, unsafePath string, mode int) (_ *os.File, Err // Make sure the mode doesn't have any type bits. mode &^= unix.S_IFMT - // What properties do we expect any newly created directories to have? - var ( - // While umask(2) is a per-thread property, and thus this value could - // vary between threads, a functioning Go program would LockOSThread - // threads with different umasks and so we don't need to LockOSThread - // for this entire mkdirat loop (if we are in the locked thread with a - // different umask, we are already locked and there's nothing for us to - // do -- and if not then it doesn't matter which thread we run on and - // there's nothing for us to do). - expectedMode = uint32(unix.S_IFDIR | (mode &^ getUmask())) - - // We would want to get the fs[ug]id here, but we can't access those - // from userspace. In practice, nobody uses setfs[ug]id() anymore, so - // just use the effective [ug]id (which is equivalent to the fs[ug]id - // for programs that don't use setfs[ug]id). - expectedUid = uint32(unix.Geteuid()) - expectedGid = uint32(unix.Getegid()) - ) // Create the remaining components. for _, part := range remainingParts { @@ -129,7 +117,7 @@ func MkdirAllHandle(root *os.File, unsafePath string, mode int) (_ *os.File, Err } // NOTE: mkdir(2) will not follow trailing symlinks, so we can safely - // create the finaly component without worrying about symlink-exchange + // create the final component without worrying about symlink-exchange // attacks. if err := unix.Mkdirat(int(currentDir.Fd()), part, uint32(mode)); err != nil { err = &os.PathError{Op: "mkdirat", Path: currentDir.Name() + "/" + part, Err: err} @@ -157,40 +145,30 @@ func MkdirAllHandle(root *os.File, unsafePath string, mode int) (_ *os.File, Err _ = currentDir.Close() currentDir = nextDir - // Make sure that the directory matches what we expect. An attacker - // could have swapped the directory between us making it and opening - // it. There's no way for us to be sure that the directory is - // _precisely_ the same as the directory we created, but if we are in - // an empty directory with the same owner and mode as the one we - // created then there is nothing the attacker could do with this new - // directory that they couldn't do with the old one. - if stat, err := fstat(currentDir); err != nil { - return nil, fmt.Errorf("check newly created directory: %w", err) - } else { - if stat.Mode != expectedMode { - return nil, fmt.Errorf("%w: newly created directory %q has incorrect mode 0o%.3o (expected 0o%.3o)", errPossibleAttack, currentDir.Name(), stat.Mode, expectedMode) - } - if stat.Uid != expectedUid || stat.Gid != expectedGid { - return nil, fmt.Errorf("%w: newly created directory %q has incorrect owner %d:%d (expected %d:%d)", errPossibleAttack, currentDir.Name(), stat.Uid, stat.Gid, expectedUid, expectedGid) - } - // Check that the directory is empty. We only need to check for - // a single entry, and we should get EOF if the directory is - // empty. - _, err := currentDir.Readdirnames(1) - if !errors.Is(err, io.EOF) { - if err == nil { - err = fmt.Errorf("%w: newly created directory %q is non-empty", errPossibleAttack, currentDir.Name()) - } - return nil, fmt.Errorf("check if newly created directory %q is empty: %w", currentDir.Name(), err) - } - // Reset the offset. - _, _ = currentDir.Seek(0, unix.SEEK_SET) - } + // It's possible that the directory we just opened was swapped by an + // attacker. Unfortunately there isn't much we can do to protect + // against this, and MkdirAll's behaviour is that we will reuse + // existing directories anyway so the need to protect against this is + // incredibly limited (and arguably doesn't even deserve mention here). + // + // Ideally we might want to check that the owner and mode match what we + // would've created -- unfortunately, it is non-trivial to verify that + // the owner and mode of the created directory match. While plain Unix + // DAC rules seem simple enough to emulate, there are a bunch of other + // factors that can change the mode or owner of created directories + // (default POSIX ACLs, mount options like uid=1,gid=2,umask=0 on + // filesystems like vfat, etc etc). We used to try to verify this but + // it just lead to a series of spurious errors. + // + // We could also check that the directory is non-empty, but + // unfortunately some pseduofilesystems (like cgroupfs) create + // non-empty directories, which would result in different spurious + // errors. } return currentDir, nil } -// MkdirAll is a race-safe alternative to the Go stdlib's os.MkdirAll function, +// MkdirAll is a race-safe alternative to the [os.MkdirAll] function, // where the new directory is guaranteed to be within the root directory (if an // attacker can move directories from inside the root to outside the root, the // created directory tree might be outside of the root but the key constraint @@ -203,16 +181,16 @@ func MkdirAllHandle(root *os.File, unsafePath string, mode int) (_ *os.File, Err // err := os.MkdirAll(path, mode) // // But is much safer. The above implementation is unsafe because if an attacker -// can modify the filesystem tree between SecureJoin and MkdirAll, it is +// can modify the filesystem tree between [SecureJoin] and [os.MkdirAll], it is // possible for MkdirAll to resolve unsafe symlink components and create // directories outside of the root. // // If you plan to open the directory after you have created it or want to use -// an open directory handle as the root, you should use MkdirAllHandle instead. -// This function is a wrapper around MkdirAllHandle. +// an open directory handle as the root, you should use [MkdirAllHandle] instead. +// This function is a wrapper around [MkdirAllHandle]. // // NOTE: The mode argument must be set the unix mode bits (unix.S_I...), not -// the Go generic mode bits (os.Mode...). +// the Go generic mode bits ([os.FileMode]...). func MkdirAll(root, unsafePath string, mode int) error { rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { diff --git a/vendor/github.com/cyphar/filepath-securejoin/open_linux.go b/vendor/github.com/cyphar/filepath-securejoin/open_linux.go index 52dce76f3..230be73f0 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/open_linux.go +++ b/vendor/github.com/cyphar/filepath-securejoin/open_linux.go @@ -14,8 +14,8 @@ import ( "golang.org/x/sys/unix" ) -// OpenatInRoot is equivalent to OpenInRoot, except that the root is provided -// using an *os.File handle, to ensure that the correct root directory is used. +// OpenatInRoot is equivalent to [OpenInRoot], except that the root is provided +// using an *[os.File] handle, to ensure that the correct root directory is used. func OpenatInRoot(root *os.File, unsafePath string) (*os.File, error) { handle, err := completeLookupInRoot(root, unsafePath) if err != nil { @@ -31,7 +31,7 @@ func OpenatInRoot(root *os.File, unsafePath string) (*os.File, error) { // handle, err := os.OpenFile(path, unix.O_PATH|unix.O_CLOEXEC) // // But is much safer. The above implementation is unsafe because if an attacker -// can modify the filesystem tree between SecureJoin and OpenFile, it is +// can modify the filesystem tree between [SecureJoin] and [os.OpenFile], it is // possible for the returned file to be outside of the root. // // Note that the returned handle is an O_PATH handle, meaning that only a very @@ -39,7 +39,7 @@ func OpenatInRoot(root *os.File, unsafePath string) (*os.File, error) { // accidentally opening an untrusted file that could cause issues (such as a // disconnected TTY that could cause a DoS, or some other issue). In order to // use the returned handle, you can "upgrade" it to a proper handle using -// Reopen. +// [Reopen]. func OpenInRoot(root, unsafePath string) (*os.File, error) { rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { @@ -49,7 +49,7 @@ func OpenInRoot(root, unsafePath string) (*os.File, error) { return OpenatInRoot(rootDir, unsafePath) } -// Reopen takes an *os.File handle and re-opens it through /proc/self/fd. +// Reopen takes an *[os.File] handle and re-opens it through /proc/self/fd. // Reopen(file, flags) is effectively equivalent to // // fdPath := fmt.Sprintf("/proc/self/fd/%d", file.Fd()) @@ -59,7 +59,9 @@ func OpenInRoot(root, unsafePath string) (*os.File, error) { // maliciously-configured /proc mount. While this attack scenario is not // common, in container runtimes it is possible for higher-level runtimes to be // tricked into configuring an unsafe /proc that can be used to attack file -// operations. See CVE-2019-19921 for more details. +// operations. See [CVE-2019-19921] for more details. +// +// [CVE-2019-19921]: https://github.com/advisories/GHSA-fh74-hm69-rqjw func Reopen(handle *os.File, flags int) (*os.File, error) { procRoot, err := getProcRoot() if err != nil { diff --git a/vendor/github.com/cyphar/filepath-securejoin/openat2_linux.go b/vendor/github.com/cyphar/filepath-securejoin/openat2_linux.go index 921b3e1d4..ae3b381ef 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/openat2_linux.go +++ b/vendor/github.com/cyphar/filepath-securejoin/openat2_linux.go @@ -13,34 +13,21 @@ import ( "path/filepath" "strings" "sync" - "testing" "golang.org/x/sys/unix" ) -var ( - hasOpenat2Bool bool - hasOpenat2Once sync.Once - - testingForceHasOpenat2 *bool -) - -func hasOpenat2() bool { - if testing.Testing() && testingForceHasOpenat2 != nil { - return *testingForceHasOpenat2 - } - hasOpenat2Once.Do(func() { - fd, err := unix.Openat2(unix.AT_FDCWD, ".", &unix.OpenHow{ - Flags: unix.O_PATH | unix.O_CLOEXEC, - Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_IN_ROOT, - }) - if err == nil { - hasOpenat2Bool = true - _ = unix.Close(fd) - } +var hasOpenat2 = sync.OnceValue(func() bool { + fd, err := unix.Openat2(unix.AT_FDCWD, ".", &unix.OpenHow{ + Flags: unix.O_PATH | unix.O_CLOEXEC, + Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_IN_ROOT, }) - return hasOpenat2Bool -} + if err != nil { + return false + } + _ = unix.Close(fd) + return true +}) func scopedLookupShouldRetry(how *unix.OpenHow, err error) bool { // RESOLVE_IN_ROOT (and RESOLVE_BENEATH) can return -EAGAIN if we resolve diff --git a/vendor/github.com/cyphar/filepath-securejoin/procfs_linux.go b/vendor/github.com/cyphar/filepath-securejoin/procfs_linux.go index adf0bd08f..8cc827d70 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/procfs_linux.go +++ b/vendor/github.com/cyphar/filepath-securejoin/procfs_linux.go @@ -54,33 +54,26 @@ func verifyProcRoot(procRoot *os.File) error { return nil } -var ( - hasNewMountApiBool bool - hasNewMountApiOnce sync.Once -) - -func hasNewMountApi() bool { - hasNewMountApiOnce.Do(func() { - // All of the pieces of the new mount API we use (fsopen, fsconfig, - // fsmount, open_tree) were added together in Linux 5.1[1,2], so we can - // just check for one of the syscalls and the others should also be - // available. - // - // Just try to use open_tree(2) to open a file without OPEN_TREE_CLONE. - // This is equivalent to openat(2), but tells us if open_tree is - // available (and thus all of the other basic new mount API syscalls). - // open_tree(2) is most light-weight syscall to test here. - // - // [1]: merge commit 400913252d09 - // [2]: - fd, err := unix.OpenTree(-int(unix.EBADF), "/", unix.OPEN_TREE_CLOEXEC) - if err == nil { - hasNewMountApiBool = true - _ = unix.Close(fd) - } - }) - return hasNewMountApiBool -} +var hasNewMountApi = sync.OnceValue(func() bool { + // All of the pieces of the new mount API we use (fsopen, fsconfig, + // fsmount, open_tree) were added together in Linux 5.1[1,2], so we can + // just check for one of the syscalls and the others should also be + // available. + // + // Just try to use open_tree(2) to open a file without OPEN_TREE_CLONE. + // This is equivalent to openat(2), but tells us if open_tree is + // available (and thus all of the other basic new mount API syscalls). + // open_tree(2) is most light-weight syscall to test here. + // + // [1]: merge commit 400913252d09 + // [2]: + fd, err := unix.OpenTree(-int(unix.EBADF), "/", unix.OPEN_TREE_CLOEXEC) + if err != nil { + return false + } + _ = unix.Close(fd) + return true +}) func fsopen(fsName string, flags int) (*os.File, error) { // Make sure we always set O_CLOEXEC. @@ -141,7 +134,7 @@ func clonePrivateProcMount() (_ *os.File, Err error) { // we can be sure there are no over-mounts and so if the root is valid then // we're golden. Otherwise, we have to deal with over-mounts. procfsHandle, err := openTree(nil, "/proc", unix.OPEN_TREE_CLONE) - if err != nil || testingForcePrivateProcRootOpenTreeAtRecursive(procfsHandle) { + if err != nil || hookForcePrivateProcRootOpenTreeAtRecursive(procfsHandle) { procfsHandle, err = openTree(nil, "/proc", unix.OPEN_TREE_CLONE|unix.AT_RECURSIVE) } if err != nil { @@ -159,27 +152,19 @@ func clonePrivateProcMount() (_ *os.File, Err error) { } func privateProcRoot() (*os.File, error) { - if !hasNewMountApi() || testingForceGetProcRootUnsafe() { + if !hasNewMountApi() || hookForceGetProcRootUnsafe() { return nil, fmt.Errorf("new mount api: %w", unix.ENOTSUP) } // Try to create a new procfs mount from scratch if we can. This ensures we // can get a procfs mount even if /proc is fake (for whatever reason). procRoot, err := newPrivateProcMount() - if err != nil || testingForcePrivateProcRootOpenTree(procRoot) { + if err != nil || hookForcePrivateProcRootOpenTree(procRoot) { // Try to clone /proc then... procRoot, err = clonePrivateProcMount() } return procRoot, err } -var ( - procRootHandle *os.File - procRootError error - procRootOnce sync.Once - - errUnsafeProcfs = errors.New("unsafe procfs detected") -) - func unsafeHostProcRoot() (_ *os.File, Err error) { procRoot, err := os.OpenFile("/proc", unix.O_PATH|unix.O_NOFOLLOW|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { @@ -207,17 +192,15 @@ func doGetProcRoot() (*os.File, error) { return procRoot, err } -func getProcRoot() (*os.File, error) { - procRootOnce.Do(func() { - procRootHandle, procRootError = doGetProcRoot() - }) - return procRootHandle, procRootError -} +var getProcRoot = sync.OnceValues(func() (*os.File, error) { + return doGetProcRoot() +}) -var ( - haveProcThreadSelf bool - haveProcThreadSelfOnce sync.Once -) +var hasProcThreadSelf = sync.OnceValue(func() bool { + return unix.Access("/proc/thread-self/", unix.F_OK) == nil +}) + +var errUnsafeProcfs = errors.New("unsafe procfs detected") type procThreadSelfCloser func() @@ -230,13 +213,6 @@ type procThreadSelfCloser func() // This is similar to ProcThreadSelf from runc, but with extra hardening // applied and using *os.File. func procThreadSelf(procRoot *os.File, subpath string) (_ *os.File, _ procThreadSelfCloser, Err error) { - haveProcThreadSelfOnce.Do(func() { - // If the kernel doesn't support thread-self, it doesn't matter which - // /proc handle we use. - _, err := fstatatFile(procRoot, "thread-self", unix.AT_SYMLINK_NOFOLLOW) - haveProcThreadSelf = (err == nil) - }) - // We need to lock our thread until the caller is done with the handle // because between getting the handle and using it we could get interrupted // by the Go runtime and hit the case where the underlying thread is @@ -251,10 +227,10 @@ func procThreadSelf(procRoot *os.File, subpath string) (_ *os.File, _ procThread // Figure out what prefix we want to use. threadSelf := "thread-self/" - if !haveProcThreadSelf || testingForceProcSelfTask() { + if !hasProcThreadSelf() || hookForceProcSelfTask() { /// Pre-3.17 kernels don't have /proc/thread-self, so do it manually. threadSelf = "self/task/" + strconv.Itoa(unix.Gettid()) + "/" - if _, err := fstatatFile(procRoot, threadSelf, unix.AT_SYMLINK_NOFOLLOW); err != nil || testingForceProcSelf() { + if _, err := fstatatFile(procRoot, threadSelf, unix.AT_SYMLINK_NOFOLLOW); err != nil || hookForceProcSelf() { // In this case, we running in a pid namespace that doesn't match // the /proc mount we have. This can happen inside runc. // @@ -275,7 +251,7 @@ func procThreadSelf(procRoot *os.File, subpath string) (_ *os.File, _ procThread // absolutely sure we are operating on a clean /proc handle that // doesn't have any cheeky overmounts that could trick us (including // symlink mounts on top of /proc/thread-self). RESOLVE_BENEATH isn't - // stricly needed, but just use it since we have it. + // strictly needed, but just use it since we have it. // // NOTE: /proc/self is technically a magic-link (the contents of the // symlink are generated dynamically), but it doesn't use @@ -313,24 +289,16 @@ func procThreadSelf(procRoot *os.File, subpath string) (_ *os.File, _ procThread return handle, runtime.UnlockOSThread, nil } -var ( - hasStatxMountIdBool bool - hasStatxMountIdOnce sync.Once -) - -func hasStatxMountId() bool { - hasStatxMountIdOnce.Do(func() { - var ( - stx unix.Statx_t - // We don't care which mount ID we get. The kernel will give us the - // unique one if it is supported. - wantStxMask uint32 = unix.STATX_MNT_ID_UNIQUE | unix.STATX_MNT_ID - ) - err := unix.Statx(-int(unix.EBADF), "/", 0, int(wantStxMask), &stx) - hasStatxMountIdBool = (err == nil && (stx.Mask&wantStxMask != 0)) - }) - return hasStatxMountIdBool -} +var hasStatxMountId = sync.OnceValue(func() bool { + var ( + stx unix.Statx_t + // We don't care which mount ID we get. The kernel will give us the + // unique one if it is supported. + wantStxMask uint32 = unix.STATX_MNT_ID_UNIQUE | unix.STATX_MNT_ID + ) + err := unix.Statx(-int(unix.EBADF), "/", 0, int(wantStxMask), &stx) + return err == nil && stx.Mask&wantStxMask != 0 +}) func getMountId(dir *os.File, path string) (uint64, error) { // If we don't have statx(STATX_MNT_ID*) support, we can't do anything. @@ -443,22 +411,6 @@ func isDeadInode(file *os.File) error { return nil } -func getUmask() int { - // umask is a per-thread property, but it is inherited by children, so we - // need to lock our OS thread to make sure that no other goroutine runs in - // this thread and no goroutines are spawned from this thread until we - // revert to the old umask. - // - // We could parse /proc/self/status to avoid this get-set problem, but - // /proc/thread-self requires LockOSThread anyway, so there's no real - // benefit over just using umask(2). - runtime.LockOSThread() - umask := unix.Umask(0) - unix.Umask(umask) - runtime.UnlockOSThread() - return umask -} - func checkProcSelfFdPath(path string, file *os.File) error { if err := isDeadInode(file); err != nil { return err @@ -472,3 +424,17 @@ func checkProcSelfFdPath(path string, file *os.File) error { } return nil } + +// Test hooks used in the procfs tests to verify that the fallback logic works. +// See testing_mocks_linux_test.go and procfs_linux_test.go for more details. +var ( + hookForcePrivateProcRootOpenTree = hookDummyFile + hookForcePrivateProcRootOpenTreeAtRecursive = hookDummyFile + hookForceGetProcRootUnsafe = hookDummy + + hookForceProcSelfTask = hookDummy + hookForceProcSelf = hookDummy +) + +func hookDummy() bool { return false } +func hookDummyFile(_ *os.File) bool { return false } diff --git a/vendor/github.com/cyphar/filepath-securejoin/testing_mocks_linux.go b/vendor/github.com/cyphar/filepath-securejoin/testing_mocks_linux.go deleted file mode 100644 index a3aedf03d..000000000 --- a/vendor/github.com/cyphar/filepath-securejoin/testing_mocks_linux.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build linux - -// Copyright (C) 2024 SUSE LLC. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package securejoin - -import ( - "os" - "testing" -) - -type forceGetProcRootLevel int - -const ( - forceGetProcRootDefault forceGetProcRootLevel = iota - forceGetProcRootOpenTree // force open_tree() - forceGetProcRootOpenTreeAtRecursive // force open_tree(AT_RECURSIVE) - forceGetProcRootUnsafe // force open() -) - -var testingForceGetProcRoot *forceGetProcRootLevel - -func testingCheckClose(check bool, f *os.File) bool { - if check { - if f != nil { - _ = f.Close() - } - return true - } - return false -} - -func testingForcePrivateProcRootOpenTree(f *os.File) bool { - return testing.Testing() && testingForceGetProcRoot != nil && - testingCheckClose(*testingForceGetProcRoot >= forceGetProcRootOpenTree, f) -} - -func testingForcePrivateProcRootOpenTreeAtRecursive(f *os.File) bool { - return testing.Testing() && testingForceGetProcRoot != nil && - testingCheckClose(*testingForceGetProcRoot >= forceGetProcRootOpenTreeAtRecursive, f) -} - -func testingForceGetProcRootUnsafe() bool { - return testing.Testing() && testingForceGetProcRoot != nil && - *testingForceGetProcRoot >= forceGetProcRootUnsafe -} - -type forceProcThreadSelfLevel int - -const ( - forceProcThreadSelfDefault forceProcThreadSelfLevel = iota - forceProcSelfTask - forceProcSelf -) - -var testingForceProcThreadSelf *forceProcThreadSelfLevel - -func testingForceProcSelfTask() bool { - return testing.Testing() && testingForceProcThreadSelf != nil && - *testingForceProcThreadSelf >= forceProcSelfTask -} - -func testingForceProcSelf() bool { - return testing.Testing() && testingForceProcThreadSelf != nil && - *testingForceProcThreadSelf >= forceProcSelf -} diff --git a/vendor/github.com/cyphar/filepath-securejoin/vfs.go b/vendor/github.com/cyphar/filepath-securejoin/vfs.go index 6e27c7dd8..36373f8c5 100644 --- a/vendor/github.com/cyphar/filepath-securejoin/vfs.go +++ b/vendor/github.com/cyphar/filepath-securejoin/vfs.go @@ -10,19 +10,19 @@ import "os" // are several projects (umoci and go-mtree) that are using this sort of // interface. -// VFS is the minimal interface necessary to use SecureJoinVFS. A nil VFS is -// equivalent to using the standard os.* family of functions. This is mainly +// VFS is the minimal interface necessary to use [SecureJoinVFS]. A nil VFS is +// equivalent to using the standard [os].* family of functions. This is mainly // used for the purposes of mock testing, but also can be used to otherwise use -// SecureJoin with VFS-like system. +// [SecureJoinVFS] with VFS-like system. type VFS interface { - // Lstat returns a FileInfo describing the named file. If the file is a - // symbolic link, the returned FileInfo describes the symbolic link. Lstat - // makes no attempt to follow the link. These semantics are identical to - // os.Lstat. + // Lstat returns an [os.FileInfo] describing the named file. If the + // file is a symbolic link, the returned [os.FileInfo] describes the + // symbolic link. Lstat makes no attempt to follow the link. + // The semantics are identical to [os.Lstat]. Lstat(name string) (os.FileInfo, error) - // Readlink returns the destination of the named symbolic link. These - // semantics are identical to os.Readlink. + // Readlink returns the destination of the named symbolic link. + // The semantics are identical to [os.Readlink]. Readlink(name string) (string, error) } @@ -30,12 +30,6 @@ type VFS interface { // module. type osVFS struct{} -// Lstat returns a FileInfo describing the named file. If the file is a -// symbolic link, the returned FileInfo describes the symbolic link. Lstat -// makes no attempt to follow the link. These semantics are identical to -// os.Lstat. func (o osVFS) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } -// Readlink returns the destination of the named symbolic link. These -// semantics are identical to os.Readlink. func (o osVFS) Readlink(name string) (string, error) { return os.Readlink(name) } diff --git a/vendor/github.com/distribution/reference/README.md b/vendor/github.com/distribution/reference/README.md index e2531e49c..172a02e0b 100644 --- a/vendor/github.com/distribution/reference/README.md +++ b/vendor/github.com/distribution/reference/README.md @@ -10,7 +10,7 @@ Go library to handle references to container images. [![codecov](https://codecov.io/gh/distribution/reference/branch/main/graph/badge.svg)](https://codecov.io/gh/distribution/reference) [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference.svg?type=shield)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference?ref=badge_shield) -This repository contains a library for handling refrences to container images held in container registries. Please see [godoc](https://pkg.go.dev/github.com/distribution/reference) for details. +This repository contains a library for handling references to container images held in container registries. Please see [godoc](https://pkg.go.dev/github.com/distribution/reference) for details. ## Contribution diff --git a/vendor/github.com/distribution/reference/normalize.go b/vendor/github.com/distribution/reference/normalize.go index a30229d01..f4128314c 100644 --- a/vendor/github.com/distribution/reference/normalize.go +++ b/vendor/github.com/distribution/reference/normalize.go @@ -123,20 +123,51 @@ func ParseDockerRef(ref string) (Named, error) { // splitDockerDomain splits a repository name to domain and remote-name. // If no valid domain is found, the default domain is used. Repository name // needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != localhost && strings.ToLower(name[:i]) == name[:i]) { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoPrefix + remainder - } - return +func splitDockerDomain(name string) (domain, remoteName string) { + maybeDomain, maybeRemoteName, ok := strings.Cut(name, "/") + if !ok { + // Fast-path for single element ("familiar" names), such as "ubuntu" + // or "ubuntu:latest". Familiar names must be handled separately, to + // prevent them from being handled as "hostname:port". + // + // Canonicalize them as "docker.io/library/name[:tag]" + + // FIXME(thaJeztah): account for bare "localhost" or "example.com" names, which SHOULD be considered a domain. + return defaultDomain, officialRepoPrefix + name + } + + switch { + case maybeDomain == localhost: + // localhost is a reserved namespace and always considered a domain. + domain, remoteName = maybeDomain, maybeRemoteName + case maybeDomain == legacyDefaultDomain: + // canonicalize the Docker Hub and legacy "Docker Index" domains. + domain, remoteName = defaultDomain, maybeRemoteName + case strings.ContainsAny(maybeDomain, ".:"): + // Likely a domain or IP-address: + // + // - contains a "." (e.g., "example.com" or "127.0.0.1") + // - contains a ":" (e.g., "example:5000", "::1", or "[::1]:5000") + domain, remoteName = maybeDomain, maybeRemoteName + case strings.ToLower(maybeDomain) != maybeDomain: + // Uppercase namespaces are not allowed, so if the first element + // is not lowercase, we assume it to be a domain-name. + domain, remoteName = maybeDomain, maybeRemoteName + default: + // None of the above: it's not a domain, so use the default, and + // use the name input the remote-name. + domain, remoteName = defaultDomain, name + } + + if domain == defaultDomain && !strings.ContainsRune(remoteName, '/') { + // Canonicalize "familiar" names, but only on Docker Hub, not + // on other domains: + // + // "docker.io/ubuntu[:tag]" => "docker.io/library/ubuntu[:tag]" + remoteName = officialRepoPrefix + remoteName + } + + return domain, remoteName } // familiarizeName returns a shortened version of the name familiar diff --git a/vendor/github.com/distribution/reference/reference.go b/vendor/github.com/distribution/reference/reference.go index e98c44daa..900398bde 100644 --- a/vendor/github.com/distribution/reference/reference.go +++ b/vendor/github.com/distribution/reference/reference.go @@ -35,8 +35,13 @@ import ( ) const ( + // RepositoryNameTotalLengthMax is the maximum total number of characters in a repository name. + RepositoryNameTotalLengthMax = 255 + // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 + // + // Deprecated: use [RepositoryNameTotalLengthMax] instead. + NameTotalLengthMax = RepositoryNameTotalLengthMax ) var ( @@ -55,8 +60,8 @@ var ( // ErrNameEmpty is returned for empty, invalid repository names. ErrNameEmpty = errors.New("repository name must have at least one component") - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) + // ErrNameTooLong is returned when a repository name is longer than RepositoryNameTotalLengthMax. + ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", RepositoryNameTotalLengthMax) // ErrNameNotCanonical is returned when a name is not canonical. ErrNameNotCanonical = errors.New("repository name must be canonical") @@ -165,6 +170,9 @@ func Path(named Named) (name string) { return path } +// splitDomain splits a named reference into a hostname and path string. +// If no valid hostname is found, the hostname is empty and the full value +// is returned as name func splitDomain(name string) (string, string) { match := anchoredNameRegexp.FindStringSubmatch(name) if len(match) != 3 { @@ -173,19 +181,6 @@ func splitDomain(name string) (string, string) { return match[1], match[2] } -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// -// Deprecated: Use [Domain] or [Path]. -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - // Parse parses s and returns a syntactically valid Reference. // If an error was encountered it is returned, along with a nil Reference. func Parse(s string) (Reference, error) { @@ -200,10 +195,6 @@ func Parse(s string) (Reference, error) { return nil, ErrReferenceInvalidFormat } - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - var repo repository nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) @@ -215,6 +206,10 @@ func Parse(s string) (Reference, error) { repo.path = matches[1] } + if len(repo.path) > RepositoryNameTotalLengthMax { + return nil, ErrNameTooLong + } + ref := reference{ namedRepository: repo, tag: matches[2], @@ -253,14 +248,15 @@ func ParseNamed(s string) (Named, error) { // WithName returns a named object representing the given string. If the input // is invalid ErrReferenceInvalidFormat will be returned. func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - match := anchoredNameRegexp.FindStringSubmatch(name) if match == nil || len(match) != 3 { return nil, ErrReferenceInvalidFormat } + + if len(match[2]) > RepositoryNameTotalLengthMax { + return nil, ErrNameTooLong + } + return repository{ domain: match[1], path: match[2], diff --git a/vendor/github.com/mittwald/go-helm-client/client.go b/vendor/github.com/mittwald/go-helm-client/client.go index a76ab28a7..944adc48c 100644 --- a/vendor/github.com/mittwald/go-helm-client/client.go +++ b/vendor/github.com/mittwald/go-helm-client/client.go @@ -206,9 +206,11 @@ func (c *HelmClient) UpdateChartRepos() error { } chartRepo.CachePath = c.Settings.RepositoryCache - _, err = chartRepo.DownloadIndexFile() - if err != nil { - return err + if !registry.IsOCI(entry.URL) { + _, err = chartRepo.DownloadIndexFile() + if err != nil { + return err + } } c.storage.Update(entry) diff --git a/vendor/go.starlark.net/LICENSE b/vendor/go.starlark.net/LICENSE deleted file mode 100644 index a6609a143..000000000 --- a/vendor/go.starlark.net/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2017 The Bazel Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. 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. - -3. Neither the name of the copyright holder 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 -HOLDER 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/go.starlark.net/internal/compile/compile.go b/vendor/go.starlark.net/internal/compile/compile.go deleted file mode 100644 index ecf689f05..000000000 --- a/vendor/go.starlark.net/internal/compile/compile.go +++ /dev/null @@ -1,1927 +0,0 @@ -// Package compile defines the Starlark bytecode compiler. -// It is an internal package of the Starlark interpreter and is not directly accessible to clients. -// -// The compiler generates byte code with optional uint32 operands for a -// virtual machine with the following components: -// - a program counter, which is an index into the byte code array. -// - an operand stack, whose maximum size is computed for each function by the compiler. -// - an stack of active iterators. -// - an array of local variables. -// The number of local variables and their indices are computed by the resolver. -// Locals (possibly including parameters) that are shared with nested functions -// are 'cells': their locals array slot will contain a value of type 'cell', -// an indirect value in a box that is explicitly read/updated by instructions. -// - an array of free variables, for nested functions. -// Free variables are a subset of the ancestors' cell variables. -// As with locals and cells, these are computed by the resolver. -// - an array of global variables, shared among all functions in the same module. -// All elements are initially nil. -// - two maps of predeclared and universal identifiers. -// -// Each function has a line number table that maps each program counter -// offset to a source position, including the column number. -// -// Operands, logically uint32s, are encoded using little-endian 7-bit -// varints, the top bit indicating that more bytes follow. -package compile // import "go.starlark.net/internal/compile" - -import ( - "bytes" - "fmt" - "log" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - - "go.starlark.net/resolve" - "go.starlark.net/syntax" -) - -// Disassemble causes the assembly code for each function -// to be printed to stderr as it is generated. -var Disassemble = false - -const debug = false // make code generation verbose, for debugging the compiler - -// Increment this to force recompilation of saved bytecode files. -const Version = 14 - -type Opcode uint8 - -// "x DUP x x" is a "stack picture" that describes the state of the -// stack before and after execution of the instruction. -// -// OP indicates an immediate operand that is an index into the -// specified table: locals, names, freevars, constants. -const ( - NOP Opcode = iota // - NOP - - - // stack operations - DUP // x DUP x x - DUP2 // x y DUP2 x y x y - POP // x POP - - EXCH // x y EXCH y x - - // binary comparisons - // (order must match Token) - LT - GT - GE - LE - EQL - NEQ - - // binary arithmetic - // (order must match Token) - PLUS - MINUS - STAR - SLASH - SLASHSLASH - PERCENT - AMP - PIPE - CIRCUMFLEX - LTLT - GTGT - - IN - - // unary operators - UPLUS // x UPLUS x - UMINUS // x UMINUS -x - TILDE // x TILDE ~x - - NONE // - NONE None - TRUE // - TRUE True - FALSE // - FALSE False - MANDATORY // - MANDATORY Mandatory [sentinel value for required kwonly args] - - ITERPUSH // iterable ITERPUSH - [pushes the iterator stack] - ITERPOP // - ITERPOP - [pops the iterator stack] - NOT // value NOT bool - RETURN // value RETURN - - SETINDEX // a i new SETINDEX - - INDEX // a i INDEX elem - SETDICT // dict key value SETDICT - - SETDICTUNIQ // dict key value SETDICTUNIQ - - APPEND // list elem APPEND - - SLICE // x lo hi step SLICE slice - INPLACE_ADD // x y INPLACE_ADD z where z is x+y or x.extend(y) - INPLACE_PIPE // x y INPLACE_PIPE z where z is x|y - MAKEDICT // - MAKEDICT dict - - // --- opcodes with an argument must go below this line --- - - // control flow - JMP // - JMP - - CJMP // cond CJMP - - ITERJMP // - ITERJMP elem (and fall through) [acts on topmost iterator] - // or: - ITERJMP - (and jump) - - CONSTANT // - CONSTANT value - MAKETUPLE // x1 ... xn MAKETUPLE tuple - MAKELIST // x1 ... xn MAKELIST list - MAKEFUNC // defaults+freevars MAKEFUNC fn - LOAD // from1 ... fromN module LOAD v1 ... vN - SETLOCAL // value SETLOCAL - - SETGLOBAL // value SETGLOBAL - - LOCAL // - LOCAL value - FREE // - FREE cell - FREECELL // - FREECELL value (content of FREE cell) - LOCALCELL // - LOCALCELL value (content of LOCAL cell) - SETLOCALCELL // value SETLOCALCELL - (set content of LOCAL cell) - GLOBAL // - GLOBAL value - PREDECLARED // - PREDECLARED value - UNIVERSAL // - UNIVERSAL value - ATTR // x ATTR y y = x.name - SETFIELD // x y SETFIELD - x.name = y - UNPACK // iterable UNPACK vn ... v1 - - // n>>8 is #positional args and n&0xff is #named args (pairs). - CALL // fn positional named CALL result - CALL_VAR // fn positional named *args CALL_VAR result - CALL_KW // fn positional named **kwargs CALL_KW result - CALL_VAR_KW // fn positional named *args **kwargs CALL_VAR_KW result - - OpcodeArgMin = JMP - OpcodeMax = CALL_VAR_KW -) - -// TODO(adonovan): add dynamic checks for missing opcodes in the tables below. - -var opcodeNames = [...]string{ - AMP: "amp", - APPEND: "append", - ATTR: "attr", - CALL: "call", - CALL_KW: "call_kw ", - CALL_VAR: "call_var", - CALL_VAR_KW: "call_var_kw", - CIRCUMFLEX: "circumflex", - CJMP: "cjmp", - CONSTANT: "constant", - DUP2: "dup2", - DUP: "dup", - EQL: "eql", - EXCH: "exch", - FALSE: "false", - FREE: "free", - FREECELL: "freecell", - GE: "ge", - GLOBAL: "global", - GT: "gt", - GTGT: "gtgt", - IN: "in", - INDEX: "index", - INPLACE_ADD: "inplace_add", - INPLACE_PIPE: "inplace_pipe", - ITERJMP: "iterjmp", - ITERPOP: "iterpop", - ITERPUSH: "iterpush", - JMP: "jmp", - LE: "le", - LOAD: "load", - LOCAL: "local", - LOCALCELL: "localcell", - LT: "lt", - LTLT: "ltlt", - MAKEDICT: "makedict", - MAKEFUNC: "makefunc", - MAKELIST: "makelist", - MAKETUPLE: "maketuple", - MANDATORY: "mandatory", - MINUS: "minus", - NEQ: "neq", - NONE: "none", - NOP: "nop", - NOT: "not", - PERCENT: "percent", - PIPE: "pipe", - PLUS: "plus", - POP: "pop", - PREDECLARED: "predeclared", - RETURN: "return", - SETDICT: "setdict", - SETDICTUNIQ: "setdictuniq", - SETFIELD: "setfield", - SETGLOBAL: "setglobal", - SETINDEX: "setindex", - SETLOCAL: "setlocal", - SETLOCALCELL: "setlocalcell", - SLASH: "slash", - SLASHSLASH: "slashslash", - SLICE: "slice", - STAR: "star", - TILDE: "tilde", - TRUE: "true", - UMINUS: "uminus", - UNIVERSAL: "universal", - UNPACK: "unpack", - UPLUS: "uplus", -} - -const variableStackEffect = 0x7f - -// stackEffect records the effect on the size of the operand stack of -// each kind of instruction. For some instructions this requires computation. -var stackEffect = [...]int8{ - AMP: -1, - APPEND: -2, - ATTR: 0, - CALL: variableStackEffect, - CALL_KW: variableStackEffect, - CALL_VAR: variableStackEffect, - CALL_VAR_KW: variableStackEffect, - CIRCUMFLEX: -1, - CJMP: -1, - CONSTANT: +1, - DUP2: +2, - DUP: +1, - EQL: -1, - FALSE: +1, - FREE: +1, - FREECELL: +1, - GE: -1, - GLOBAL: +1, - GT: -1, - GTGT: -1, - IN: -1, - INDEX: -1, - INPLACE_ADD: -1, - INPLACE_PIPE: -1, - ITERJMP: variableStackEffect, - ITERPOP: 0, - ITERPUSH: -1, - JMP: 0, - LE: -1, - LOAD: -1, - LOCAL: +1, - LOCALCELL: +1, - LT: -1, - LTLT: -1, - MAKEDICT: +1, - MAKEFUNC: 0, - MAKELIST: variableStackEffect, - MAKETUPLE: variableStackEffect, - MANDATORY: +1, - MINUS: -1, - NEQ: -1, - NONE: +1, - NOP: 0, - NOT: 0, - PERCENT: -1, - PIPE: -1, - PLUS: -1, - POP: -1, - PREDECLARED: +1, - RETURN: -1, - SETLOCALCELL: -1, - SETDICT: -3, - SETDICTUNIQ: -3, - SETFIELD: -2, - SETGLOBAL: -1, - SETINDEX: -3, - SETLOCAL: -1, - SLASH: -1, - SLASHSLASH: -1, - SLICE: -3, - STAR: -1, - TRUE: +1, - UMINUS: 0, - UNIVERSAL: +1, - UNPACK: variableStackEffect, - UPLUS: 0, -} - -func (op Opcode) String() string { - if op < OpcodeMax { - if name := opcodeNames[op]; name != "" { - return name - } - } - return fmt.Sprintf("illegal op (%d)", op) -} - -// A Program is a Starlark file in executable form. -// -// Programs are serialized by the Program.Encode method, -// which must be updated whenever this declaration is changed. -type Program struct { - Loads []Binding // name (really, string) and position of each load stmt - Names []string // names of attributes and predeclared variables - Constants []interface{} // = string | int64 | float64 | *big.Int | Bytes - Functions []*Funcode - Globals []Binding // for error messages and tracing - Toplevel *Funcode // module initialization function - Recursion bool // disable recursion check for functions in this file -} - -// The type of a bytes literal value, to distinguish from text string. -type Bytes string - -// A Funcode is the code of a compiled Starlark function. -// -// Funcodes are serialized by the encoder.function method, -// which must be updated whenever this declaration is changed. -type Funcode struct { - Prog *Program - Pos syntax.Position // position of def or lambda token - Name string // name of this function - Doc string // docstring of this function - Code []byte // the byte code - pclinetab []uint16 // mapping from pc to linenum - Locals []Binding // locals, parameters first - Cells []int // indices of Locals that require cells - Freevars []Binding // for tracing - MaxStack int - NumParams int - NumKwonlyParams int - HasVarargs, HasKwargs bool - - // -- transient state -- - - lntOnce sync.Once - lnt []pclinecol // decoded line number table -} - -type pclinecol struct { - pc uint32 - line, col int32 -} - -// A Binding is the name and position of a binding identifier. -type Binding struct { - Name string - Pos syntax.Position -} - -// A pcomp holds the compiler state for a Program. -type pcomp struct { - prog *Program // what we're building - - names map[string]uint32 - constants map[interface{}]uint32 - functions map[*Funcode]uint32 -} - -// An fcomp holds the compiler state for a Funcode. -type fcomp struct { - fn *Funcode // what we're building - - pcomp *pcomp - pos syntax.Position // current position of generated code - loops []loop - block *block -} - -type loop struct { - break_, continue_ *block -} - -type block struct { - insns []insn - - // If the last insn is a RETURN, jmp and cjmp are nil. - // If the last insn is a CJMP or ITERJMP, - // cjmp and jmp are the "true" and "false" successors. - // Otherwise, jmp is the sole successor. - jmp, cjmp *block - - initialstack int // for stack depth computation - - // Used during encoding - index int // -1 => not encoded yet - addr uint32 -} - -type insn struct { - op Opcode - arg uint32 - line, col int32 -} - -// Position returns the source position for program counter pc. -func (fn *Funcode) Position(pc uint32) syntax.Position { - fn.lntOnce.Do(fn.decodeLNT) - - // Binary search to find last LNT entry not greater than pc. - // To avoid dynamic dispatch, this is a specialization of - // sort.Search using this predicate: - // !(i < len(fn.lnt)-1 && fn.lnt[i+1].pc <= pc) - n := len(fn.lnt) - i, j := 0, n - for i < j { - h := int(uint(i+j) >> 1) - if !(h >= n-1 || fn.lnt[h+1].pc > pc) { - i = h + 1 - } else { - j = h - } - } - - var line, col int32 - if i < n { - line = fn.lnt[i].line - col = fn.lnt[i].col - } - - pos := fn.Pos // copy the (annoyingly inaccessible) filename - pos.Col = col - pos.Line = line - return pos -} - -// decodeLNT decodes the line number table and populates fn.lnt. -// It is called at most once. -func (fn *Funcode) decodeLNT() { - // Conceptually the table contains rows of the form - // (pc uint32, line int32, col int32), sorted by pc. - // We use a delta encoding, since the differences - // between successive pc, line, and column values - // are typically small and positive (though line and - // especially column differences may be negative). - // The delta encoding starts from - // {pc: 0, line: fn.Pos.Line, col: fn.Pos.Col}. - // - // Each entry is packed into one or more 16-bit values: - // Δpc uint4 - // Δline int5 - // Δcol int6 - // incomplete uint1 - // The top 4 bits are the unsigned delta pc. - // The next 5 bits are the signed line number delta. - // The next 6 bits are the signed column number delta. - // The bottom bit indicates that more rows follow because - // one of the deltas was maxed out. - // These field widths were chosen from a sample of real programs, - // and allow >97% of rows to be encoded in a single uint16. - - fn.lnt = make([]pclinecol, 0, len(fn.pclinetab)) // a minor overapproximation - entry := pclinecol{ - pc: 0, - line: fn.Pos.Line, - col: fn.Pos.Col, - } - for _, x := range fn.pclinetab { - entry.pc += uint32(x) >> 12 - entry.line += int32((int16(x) << 4) >> (16 - 5)) // sign extend Δline - entry.col += int32((int16(x) << 9) >> (16 - 6)) // sign extend Δcol - if (x & 1) == 0 { - fn.lnt = append(fn.lnt, entry) - } - } -} - -// bindings converts resolve.Bindings to compiled form. -func bindings(bindings []*resolve.Binding) []Binding { - res := make([]Binding, len(bindings)) - for i, bind := range bindings { - res[i].Name = bind.First.Name - res[i].Pos = bind.First.NamePos - } - return res -} - -// Expr compiles an expression to a program whose toplevel function evaluates it. -// The options must be consistent with those used when parsing expr. -func Expr(opts *syntax.FileOptions, expr syntax.Expr, name string, locals []*resolve.Binding) *Program { - pos := syntax.Start(expr) - stmts := []syntax.Stmt{&syntax.ReturnStmt{Result: expr}} - return File(opts, stmts, pos, name, locals, nil) -} - -// File compiles the statements of a file into a program. -// The options must be consistent with those used when parsing stmts. -func File(opts *syntax.FileOptions, stmts []syntax.Stmt, pos syntax.Position, name string, locals, globals []*resolve.Binding) *Program { - pcomp := &pcomp{ - prog: &Program{ - Globals: bindings(globals), - Recursion: opts.Recursion, - }, - names: make(map[string]uint32), - constants: make(map[interface{}]uint32), - functions: make(map[*Funcode]uint32), - } - pcomp.prog.Toplevel = pcomp.function(name, pos, stmts, locals, nil) - - return pcomp.prog -} - -func (pcomp *pcomp) function(name string, pos syntax.Position, stmts []syntax.Stmt, locals, freevars []*resolve.Binding) *Funcode { - fcomp := &fcomp{ - pcomp: pcomp, - pos: pos, - fn: &Funcode{ - Prog: pcomp.prog, - Pos: pos, - Name: name, - Doc: docStringFromBody(stmts), - Locals: bindings(locals), - Freevars: bindings(freevars), - }, - } - - // Record indices of locals that require cells. - for i, local := range locals { - if local.Scope == resolve.Cell { - fcomp.fn.Cells = append(fcomp.fn.Cells, i) - } - } - - if debug { - fmt.Fprintf(os.Stderr, "start function(%s @ %s)\n", name, pos) - } - - // Convert AST to a CFG of instructions. - entry := fcomp.newBlock() - fcomp.block = entry - fcomp.stmts(stmts) - if fcomp.block != nil { - fcomp.emit(NONE) - fcomp.emit(RETURN) - } - - var oops bool // something bad happened - - setinitialstack := func(b *block, depth int) { - if b.initialstack == -1 { - b.initialstack = depth - } else if b.initialstack != depth { - fmt.Fprintf(os.Stderr, "%d: setinitialstack: depth mismatch: %d vs %d\n", - b.index, b.initialstack, depth) - oops = true - } - } - - // Linearize the CFG: - // compute order, address, and initial - // stack depth of each reachable block. - var pc uint32 - var blocks []*block - var maxstack int - var visit func(b *block) - visit = func(b *block) { - if b.index >= 0 { - return // already visited - } - b.index = len(blocks) - b.addr = pc - blocks = append(blocks, b) - - stack := b.initialstack - if debug { - fmt.Fprintf(os.Stderr, "%s block %d: (stack = %d)\n", name, b.index, stack) - } - var cjmpAddr *uint32 - var isiterjmp int - for i, insn := range b.insns { - pc++ - - // Compute size of argument. - if insn.op >= OpcodeArgMin { - switch insn.op { - case ITERJMP: - isiterjmp = 1 - fallthrough - case CJMP: - cjmpAddr = &b.insns[i].arg - pc += 4 - default: - pc += uint32(argLen(insn.arg)) - } - } - - // Compute effect on stack. - se := insn.stackeffect() - if debug { - fmt.Fprintln(os.Stderr, "\t", insn.op, stack, stack+se) - } - stack += se - if stack < 0 { - fmt.Fprintf(os.Stderr, "After pc=%d: stack underflow\n", pc) - oops = true - } - if stack+isiterjmp > maxstack { - maxstack = stack + isiterjmp - } - } - - if debug { - fmt.Fprintf(os.Stderr, "successors of block %d (start=%d):\n", - b.addr, b.index) - if b.jmp != nil { - fmt.Fprintf(os.Stderr, "jmp to %d\n", b.jmp.index) - } - if b.cjmp != nil { - fmt.Fprintf(os.Stderr, "cjmp to %d\n", b.cjmp.index) - } - } - - // Place the jmp block next. - if b.jmp != nil { - // jump threading (empty cycles are impossible) - for b.jmp.insns == nil { - b.jmp = b.jmp.jmp - } - - setinitialstack(b.jmp, stack+isiterjmp) - if b.jmp.index < 0 { - // Successor is not yet visited: - // place it next and fall through. - visit(b.jmp) - } else { - // Successor already visited; - // explicit backward jump required. - pc += 5 - } - } - - // Then the cjmp block. - if b.cjmp != nil { - // jump threading (empty cycles are impossible) - for b.cjmp.insns == nil { - b.cjmp = b.cjmp.jmp - } - - setinitialstack(b.cjmp, stack) - visit(b.cjmp) - - // Patch the CJMP/ITERJMP, if present. - if cjmpAddr != nil { - *cjmpAddr = b.cjmp.addr - } - } - } - setinitialstack(entry, 0) - visit(entry) - - fn := fcomp.fn - fn.MaxStack = maxstack - - // Emit bytecode (and position table). - if Disassemble { - fmt.Fprintf(os.Stderr, "Function %s: (%d blocks, %d bytes)\n", name, len(blocks), pc) - } - fcomp.generate(blocks, pc) - - if debug { - fmt.Fprintf(os.Stderr, "code=%d maxstack=%d\n", fn.Code, fn.MaxStack) - } - - // Don't panic until we've completed printing of the function. - if oops { - panic("internal error") - } - - if debug { - fmt.Fprintf(os.Stderr, "end function(%s @ %s)\n", name, pos) - } - - return fn -} - -func docStringFromBody(body []syntax.Stmt) string { - if len(body) == 0 { - return "" - } - expr, ok := body[0].(*syntax.ExprStmt) - if !ok { - return "" - } - lit, ok := expr.X.(*syntax.Literal) - if !ok { - return "" - } - if lit.Token != syntax.STRING { - return "" - } - return lit.Value.(string) -} - -func (insn *insn) stackeffect() int { - se := int(stackEffect[insn.op]) - if se == variableStackEffect { - arg := int(insn.arg) - switch insn.op { - case CALL, CALL_KW, CALL_VAR, CALL_VAR_KW: - se = -int(2*(insn.arg&0xff) + insn.arg>>8) - if insn.op != CALL { - se-- - } - if insn.op == CALL_VAR_KW { - se-- - } - case ITERJMP: - // Stack effect differs by successor: - // +1 for jmp/false/ok - // 0 for cjmp/true/exhausted - // Handled specially in caller. - se = 0 - case MAKELIST, MAKETUPLE: - se = 1 - arg - case UNPACK: - se = arg - 1 - default: - panic(insn.op) - } - } - return se -} - -// generate emits the linear instruction stream from the CFG, -// and builds the PC-to-line number table. -func (fcomp *fcomp) generate(blocks []*block, codelen uint32) { - code := make([]byte, 0, codelen) - var pclinetab []uint16 - prev := pclinecol{ - pc: 0, - line: fcomp.fn.Pos.Line, - col: fcomp.fn.Pos.Col, - } - - for _, b := range blocks { - if Disassemble { - fmt.Fprintf(os.Stderr, "%d:\n", b.index) - } - pc := b.addr - for _, insn := range b.insns { - if insn.line != 0 { - // Instruction has a source position. Delta-encode it. - // See Funcode.Position for the encoding. - for { - var incomplete uint16 - - // Δpc, uint4 - deltapc := pc - prev.pc - if deltapc > 0x0f { - deltapc = 0x0f - incomplete = 1 - } - prev.pc += deltapc - - // Δline, int5 - deltaline, ok := clip(insn.line-prev.line, -0x10, 0x0f) - if !ok { - incomplete = 1 - } - prev.line += deltaline - - // Δcol, int6 - deltacol, ok := clip(insn.col-prev.col, -0x20, 0x1f) - if !ok { - incomplete = 1 - } - prev.col += deltacol - - entry := uint16(deltapc<<12) | uint16(deltaline&0x1f)<<7 | uint16(deltacol&0x3f)<<1 | incomplete - pclinetab = append(pclinetab, entry) - if incomplete == 0 { - break - } - } - - if Disassemble { - fmt.Fprintf(os.Stderr, "\t\t\t\t\t; %s:%d:%d\n", - filepath.Base(fcomp.fn.Pos.Filename()), insn.line, insn.col) - } - } - if Disassemble { - PrintOp(fcomp.fn, pc, insn.op, insn.arg) - } - code = append(code, byte(insn.op)) - pc++ - if insn.op >= OpcodeArgMin { - if insn.op == CJMP || insn.op == ITERJMP { - code = addUint32(code, insn.arg, 4) // pad arg to 4 bytes - } else { - code = addUint32(code, insn.arg, 0) - } - pc = uint32(len(code)) - } - } - - if b.jmp != nil && b.jmp.index != b.index+1 { - addr := b.jmp.addr - if Disassemble { - fmt.Fprintf(os.Stderr, "\t%d\tjmp\t\t%d\t; block %d\n", - pc, addr, b.jmp.index) - } - code = append(code, byte(JMP)) - code = addUint32(code, addr, 4) - } - } - if len(code) != int(codelen) { - panic("internal error: wrong code length") - } - - fcomp.fn.pclinetab = pclinetab - fcomp.fn.Code = code -} - -// clip returns the value nearest x in the range [min...max], -// and whether it equals x. -func clip(x, min, max int32) (int32, bool) { - if x > max { - return max, false - } else if x < min { - return min, false - } else { - return x, true - } -} - -// addUint32 encodes x as 7-bit little-endian varint. -// TODO(adonovan): opt: steal top two bits of opcode -// to encode the number of complete bytes that follow. -func addUint32(code []byte, x uint32, min int) []byte { - end := len(code) + min - for x >= 0x80 { - code = append(code, byte(x)|0x80) - x >>= 7 - } - code = append(code, byte(x)) - // Pad the operand with NOPs to exactly min bytes. - for len(code) < end { - code = append(code, byte(NOP)) - } - return code -} - -func argLen(x uint32) int { - n := 0 - for x >= 0x80 { - n++ - x >>= 7 - } - return n + 1 -} - -// PrintOp prints an instruction. -// It is provided for debugging. -func PrintOp(fn *Funcode, pc uint32, op Opcode, arg uint32) { - if op < OpcodeArgMin { - fmt.Fprintf(os.Stderr, "\t%d\t%s\n", pc, op) - return - } - - var comment string - switch op { - case CONSTANT: - switch x := fn.Prog.Constants[arg].(type) { - case string: - comment = strconv.Quote(x) - case Bytes: - comment = "b" + strconv.Quote(string(x)) - default: - comment = fmt.Sprint(x) - } - case MAKEFUNC: - comment = fn.Prog.Functions[arg].Name - case SETLOCAL, LOCAL: - comment = fn.Locals[arg].Name - case SETGLOBAL, GLOBAL: - comment = fn.Prog.Globals[arg].Name - case ATTR, SETFIELD, PREDECLARED, UNIVERSAL: - comment = fn.Prog.Names[arg] - case FREE: - comment = fn.Freevars[arg].Name - case CALL, CALL_VAR, CALL_KW, CALL_VAR_KW: - comment = fmt.Sprintf("%d pos, %d named", arg>>8, arg&0xff) - default: - // JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK: - // arg is just a number - } - var buf bytes.Buffer - fmt.Fprintf(&buf, "\t%d\t%-10s\t%d", pc, op, arg) - if comment != "" { - fmt.Fprint(&buf, "\t; ", comment) - } - fmt.Fprintln(&buf) - os.Stderr.Write(buf.Bytes()) -} - -// newBlock returns a new block. -func (fcomp) newBlock() *block { - return &block{index: -1, initialstack: -1} -} - -// emit emits an instruction to the current block. -func (fcomp *fcomp) emit(op Opcode) { - if op >= OpcodeArgMin { - panic("missing arg: " + op.String()) - } - insn := insn{op: op, line: fcomp.pos.Line, col: fcomp.pos.Col} - fcomp.block.insns = append(fcomp.block.insns, insn) - fcomp.pos.Line = 0 - fcomp.pos.Col = 0 -} - -// emit1 emits an instruction with an immediate operand. -func (fcomp *fcomp) emit1(op Opcode, arg uint32) { - if op < OpcodeArgMin { - panic("unwanted arg: " + op.String()) - } - insn := insn{op: op, arg: arg, line: fcomp.pos.Line, col: fcomp.pos.Col} - fcomp.block.insns = append(fcomp.block.insns, insn) - fcomp.pos.Line = 0 - fcomp.pos.Col = 0 -} - -// jump emits a jump to the specified block. -// On return, the current block is unset. -func (fcomp *fcomp) jump(b *block) { - if b == fcomp.block { - panic("self-jump") // unreachable: Starlark has no arbitrary looping constructs - } - fcomp.block.jmp = b - fcomp.block = nil -} - -// condjump emits a conditional jump (CJMP or ITERJMP) -// to the specified true/false blocks. -// (For ITERJMP, the cases are jmp/f/ok and cjmp/t/exhausted.) -// On return, the current block is unset. -func (fcomp *fcomp) condjump(op Opcode, t, f *block) { - if !(op == CJMP || op == ITERJMP) { - panic("not a conditional jump: " + op.String()) - } - fcomp.emit1(op, 0) // fill in address later - fcomp.block.cjmp = t - fcomp.jump(f) -} - -// nameIndex returns the index of the specified name -// within the name pool, adding it if necessary. -func (pcomp *pcomp) nameIndex(name string) uint32 { - index, ok := pcomp.names[name] - if !ok { - index = uint32(len(pcomp.prog.Names)) - pcomp.names[name] = index - pcomp.prog.Names = append(pcomp.prog.Names, name) - } - return index -} - -// constantIndex returns the index of the specified constant -// within the constant pool, adding it if necessary. -func (pcomp *pcomp) constantIndex(v interface{}) uint32 { - index, ok := pcomp.constants[v] - if !ok { - index = uint32(len(pcomp.prog.Constants)) - pcomp.constants[v] = index - pcomp.prog.Constants = append(pcomp.prog.Constants, v) - } - return index -} - -// functionIndex returns the index of the specified function -// AST the nestedfun pool, adding it if necessary. -func (pcomp *pcomp) functionIndex(fn *Funcode) uint32 { - index, ok := pcomp.functions[fn] - if !ok { - index = uint32(len(pcomp.prog.Functions)) - pcomp.functions[fn] = index - pcomp.prog.Functions = append(pcomp.prog.Functions, fn) - } - return index -} - -// string emits code to push the specified string. -func (fcomp *fcomp) string(s string) { - fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(s)) -} - -// setPos sets the current source position. -// It should be called prior to any operation that can fail dynamically. -// All positions are assumed to belong to the same file. -func (fcomp *fcomp) setPos(pos syntax.Position) { - fcomp.pos = pos -} - -// set emits code to store the top-of-stack value -// to the specified local, cell, or global variable. -func (fcomp *fcomp) set(id *syntax.Ident) { - bind := id.Binding.(*resolve.Binding) - switch bind.Scope { - case resolve.Local: - fcomp.emit1(SETLOCAL, uint32(bind.Index)) - case resolve.Cell: - fcomp.emit1(SETLOCALCELL, uint32(bind.Index)) - case resolve.Global: - fcomp.emit1(SETGLOBAL, uint32(bind.Index)) - default: - log.Panicf("%s: set(%s): not global/local/cell (%d)", id.NamePos, id.Name, bind.Scope) - } -} - -// lookup emits code to push the value of the specified variable. -func (fcomp *fcomp) lookup(id *syntax.Ident) { - bind := id.Binding.(*resolve.Binding) - if bind.Scope != resolve.Universal { // (universal lookup can't fail) - fcomp.setPos(id.NamePos) - } - switch bind.Scope { - case resolve.Local: - fcomp.emit1(LOCAL, uint32(bind.Index)) - case resolve.Free: - fcomp.emit1(FREECELL, uint32(bind.Index)) - case resolve.Cell: - fcomp.emit1(LOCALCELL, uint32(bind.Index)) - case resolve.Global: - fcomp.emit1(GLOBAL, uint32(bind.Index)) - case resolve.Predeclared: - fcomp.emit1(PREDECLARED, fcomp.pcomp.nameIndex(id.Name)) - case resolve.Universal: - fcomp.emit1(UNIVERSAL, fcomp.pcomp.nameIndex(id.Name)) - default: - log.Panicf("%s: compiler.lookup(%s): scope = %d", id.NamePos, id.Name, bind.Scope) - } -} - -func (fcomp *fcomp) stmts(stmts []syntax.Stmt) { - for _, stmt := range stmts { - fcomp.stmt(stmt) - } -} - -func (fcomp *fcomp) stmt(stmt syntax.Stmt) { - switch stmt := stmt.(type) { - case *syntax.ExprStmt: - if _, ok := stmt.X.(*syntax.Literal); ok { - // Opt: don't compile doc comments only to pop them. - return - } - fcomp.expr(stmt.X) - fcomp.emit(POP) - - case *syntax.BranchStmt: - // Resolver invariant: break/continue appear only within loops. - switch stmt.Token { - case syntax.PASS: - // no-op - case syntax.BREAK: - b := fcomp.loops[len(fcomp.loops)-1].break_ - fcomp.jump(b) - fcomp.block = fcomp.newBlock() // dead code - case syntax.CONTINUE: - b := fcomp.loops[len(fcomp.loops)-1].continue_ - fcomp.jump(b) - fcomp.block = fcomp.newBlock() // dead code - } - - case *syntax.IfStmt: - // Keep consistent with CondExpr. - t := fcomp.newBlock() - f := fcomp.newBlock() - done := fcomp.newBlock() - - fcomp.ifelse(stmt.Cond, t, f) - - fcomp.block = t - fcomp.stmts(stmt.True) - fcomp.jump(done) - - fcomp.block = f - fcomp.stmts(stmt.False) - fcomp.jump(done) - - fcomp.block = done - - case *syntax.AssignStmt: - switch stmt.Op { - case syntax.EQ: - // simple assignment: x = y - fcomp.expr(stmt.RHS) - fcomp.assign(stmt.OpPos, stmt.LHS) - - case syntax.PLUS_EQ, - syntax.MINUS_EQ, - syntax.STAR_EQ, - syntax.SLASH_EQ, - syntax.SLASHSLASH_EQ, - syntax.PERCENT_EQ, - syntax.AMP_EQ, - syntax.PIPE_EQ, - syntax.CIRCUMFLEX_EQ, - syntax.LTLT_EQ, - syntax.GTGT_EQ: - // augmented assignment: x += y - - var set func() - - // Evaluate "address" of x exactly once to avoid duplicate side-effects. - switch lhs := unparen(stmt.LHS).(type) { - case *syntax.Ident: - // x = ... - fcomp.lookup(lhs) - set = func() { - fcomp.set(lhs) - } - - case *syntax.IndexExpr: - // x[y] = ... - fcomp.expr(lhs.X) - fcomp.expr(lhs.Y) - fcomp.emit(DUP2) - fcomp.setPos(lhs.Lbrack) - fcomp.emit(INDEX) - set = func() { - fcomp.setPos(lhs.Lbrack) - fcomp.emit(SETINDEX) - } - - case *syntax.DotExpr: - // x.f = ... - fcomp.expr(lhs.X) - fcomp.emit(DUP) - name := fcomp.pcomp.nameIndex(lhs.Name.Name) - fcomp.setPos(lhs.Dot) - fcomp.emit1(ATTR, name) - set = func() { - fcomp.setPos(lhs.Dot) - fcomp.emit1(SETFIELD, name) - } - - default: - panic(lhs) - } - - fcomp.expr(stmt.RHS) - - // In-place x+=y and x|=y have special semantics: - // the resulting x aliases the original x. - switch stmt.Op { - case syntax.PLUS_EQ: - fcomp.setPos(stmt.OpPos) - fcomp.emit(INPLACE_ADD) - case syntax.PIPE_EQ: - fcomp.setPos(stmt.OpPos) - fcomp.emit(INPLACE_PIPE) - default: - fcomp.binop(stmt.OpPos, stmt.Op-syntax.PLUS_EQ+syntax.PLUS) - } - set() - } - - case *syntax.DefStmt: - fcomp.function(stmt.Function.(*resolve.Function)) - fcomp.set(stmt.Name) - - case *syntax.ForStmt: - // Keep consistent with ForClause. - head := fcomp.newBlock() - body := fcomp.newBlock() - tail := fcomp.newBlock() - - fcomp.expr(stmt.X) - fcomp.setPos(stmt.For) - fcomp.emit(ITERPUSH) - fcomp.jump(head) - - fcomp.block = head - fcomp.condjump(ITERJMP, tail, body) - - fcomp.block = body - fcomp.assign(stmt.For, stmt.Vars) - fcomp.loops = append(fcomp.loops, loop{break_: tail, continue_: head}) - fcomp.stmts(stmt.Body) - fcomp.loops = fcomp.loops[:len(fcomp.loops)-1] - fcomp.jump(head) - - fcomp.block = tail - fcomp.emit(ITERPOP) - - case *syntax.WhileStmt: - head := fcomp.newBlock() - body := fcomp.newBlock() - done := fcomp.newBlock() - - fcomp.jump(head) - fcomp.block = head - fcomp.ifelse(stmt.Cond, body, done) - - fcomp.block = body - fcomp.loops = append(fcomp.loops, loop{break_: done, continue_: head}) - fcomp.stmts(stmt.Body) - fcomp.loops = fcomp.loops[:len(fcomp.loops)-1] - fcomp.jump(head) - - fcomp.block = done - - case *syntax.ReturnStmt: - if stmt.Result != nil { - fcomp.expr(stmt.Result) - } else { - fcomp.emit(NONE) - } - fcomp.emit(RETURN) - fcomp.block = fcomp.newBlock() // dead code - - case *syntax.LoadStmt: - for i := range stmt.From { - fcomp.string(stmt.From[i].Name) - } - module := stmt.Module.Value.(string) - fcomp.pcomp.prog.Loads = append(fcomp.pcomp.prog.Loads, Binding{ - Name: module, - Pos: stmt.Module.TokenPos, - }) - fcomp.string(module) - fcomp.setPos(stmt.Load) - fcomp.emit1(LOAD, uint32(len(stmt.From))) - for i := range stmt.To { - fcomp.set(stmt.To[len(stmt.To)-1-i]) - } - - default: - start, _ := stmt.Span() - log.Panicf("%s: exec: unexpected statement %T", start, stmt) - } -} - -// assign implements lhs = rhs for arbitrary expressions lhs. -// RHS is on top of stack, consumed. -func (fcomp *fcomp) assign(pos syntax.Position, lhs syntax.Expr) { - switch lhs := lhs.(type) { - case *syntax.ParenExpr: - // (lhs) = rhs - fcomp.assign(pos, lhs.X) - - case *syntax.Ident: - // x = rhs - fcomp.set(lhs) - - case *syntax.TupleExpr: - // x, y = rhs - fcomp.assignSequence(pos, lhs.List) - - case *syntax.ListExpr: - // [x, y] = rhs - fcomp.assignSequence(pos, lhs.List) - - case *syntax.IndexExpr: - // x[y] = rhs - fcomp.expr(lhs.X) - fcomp.emit(EXCH) - fcomp.expr(lhs.Y) - fcomp.emit(EXCH) - fcomp.setPos(lhs.Lbrack) - fcomp.emit(SETINDEX) - - case *syntax.DotExpr: - // x.f = rhs - fcomp.expr(lhs.X) - fcomp.emit(EXCH) - fcomp.setPos(lhs.Dot) - fcomp.emit1(SETFIELD, fcomp.pcomp.nameIndex(lhs.Name.Name)) - - default: - panic(lhs) - } -} - -func (fcomp *fcomp) assignSequence(pos syntax.Position, lhs []syntax.Expr) { - fcomp.setPos(pos) - fcomp.emit1(UNPACK, uint32(len(lhs))) - for i := range lhs { - fcomp.assign(pos, lhs[i]) - } -} - -func (fcomp *fcomp) expr(e syntax.Expr) { - switch e := e.(type) { - case *syntax.ParenExpr: - fcomp.expr(e.X) - - case *syntax.Ident: - fcomp.lookup(e) - - case *syntax.Literal: - // e.Value is int64, float64, *bigInt, string - v := e.Value - if e.Token == syntax.BYTES { - v = Bytes(v.(string)) - } - fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(v)) - - case *syntax.ListExpr: - for _, x := range e.List { - fcomp.expr(x) - } - fcomp.emit1(MAKELIST, uint32(len(e.List))) - - case *syntax.CondExpr: - // Keep consistent with IfStmt. - t := fcomp.newBlock() - f := fcomp.newBlock() - done := fcomp.newBlock() - - fcomp.ifelse(e.Cond, t, f) - - fcomp.block = t - fcomp.expr(e.True) - fcomp.jump(done) - - fcomp.block = f - fcomp.expr(e.False) - fcomp.jump(done) - - fcomp.block = done - - case *syntax.IndexExpr: - fcomp.expr(e.X) - fcomp.expr(e.Y) - fcomp.setPos(e.Lbrack) - fcomp.emit(INDEX) - - case *syntax.SliceExpr: - fcomp.setPos(e.Lbrack) - fcomp.expr(e.X) - if e.Lo != nil { - fcomp.expr(e.Lo) - } else { - fcomp.emit(NONE) - } - if e.Hi != nil { - fcomp.expr(e.Hi) - } else { - fcomp.emit(NONE) - } - if e.Step != nil { - fcomp.expr(e.Step) - } else { - fcomp.emit(NONE) - } - fcomp.emit(SLICE) - - case *syntax.Comprehension: - if e.Curly { - fcomp.emit(MAKEDICT) - } else { - fcomp.emit1(MAKELIST, 0) - } - fcomp.comprehension(e, 0) - - case *syntax.TupleExpr: - fcomp.tuple(e.List) - - case *syntax.DictExpr: - fcomp.emit(MAKEDICT) - for _, entry := range e.List { - entry := entry.(*syntax.DictEntry) - fcomp.emit(DUP) - fcomp.expr(entry.Key) - fcomp.expr(entry.Value) - fcomp.setPos(entry.Colon) - fcomp.emit(SETDICTUNIQ) - } - - case *syntax.UnaryExpr: - fcomp.expr(e.X) - fcomp.setPos(e.OpPos) - switch e.Op { - case syntax.MINUS: - fcomp.emit(UMINUS) - case syntax.PLUS: - fcomp.emit(UPLUS) - case syntax.NOT: - fcomp.emit(NOT) - case syntax.TILDE: - fcomp.emit(TILDE) - default: - log.Panicf("%s: unexpected unary op: %s", e.OpPos, e.Op) - } - - case *syntax.BinaryExpr: - switch e.Op { - // short-circuit operators - // TODO(adonovan): use ifelse to simplify conditions. - case syntax.OR: - // x or y => if x then x else y - done := fcomp.newBlock() - y := fcomp.newBlock() - - fcomp.expr(e.X) - fcomp.emit(DUP) - fcomp.condjump(CJMP, done, y) - - fcomp.block = y - fcomp.emit(POP) // discard X - fcomp.expr(e.Y) - fcomp.jump(done) - - fcomp.block = done - - case syntax.AND: - // x and y => if x then y else x - done := fcomp.newBlock() - y := fcomp.newBlock() - - fcomp.expr(e.X) - fcomp.emit(DUP) - fcomp.condjump(CJMP, y, done) - - fcomp.block = y - fcomp.emit(POP) // discard X - fcomp.expr(e.Y) - fcomp.jump(done) - - fcomp.block = done - - case syntax.PLUS: - fcomp.plus(e) - - default: - // all other strict binary operator (includes comparisons) - fcomp.expr(e.X) - fcomp.expr(e.Y) - fcomp.binop(e.OpPos, e.Op) - } - - case *syntax.DotExpr: - fcomp.expr(e.X) - fcomp.setPos(e.Dot) - fcomp.emit1(ATTR, fcomp.pcomp.nameIndex(e.Name.Name)) - - case *syntax.CallExpr: - fcomp.call(e) - - case *syntax.LambdaExpr: - fcomp.function(e.Function.(*resolve.Function)) - - default: - start, _ := e.Span() - log.Panicf("%s: unexpected expr %T", start, e) - } -} - -type summand struct { - x syntax.Expr - plusPos syntax.Position -} - -// plus emits optimized code for ((a+b)+...)+z that avoids naive -// quadratic behavior for strings, tuples, and lists, -// and folds together adjacent literals of the same type. -func (fcomp *fcomp) plus(e *syntax.BinaryExpr) { - // Gather all the right operands of the left tree of plusses. - // A tree (((a+b)+c)+d) becomes args=[a +b +c +d]. - args := make([]summand, 0, 2) // common case: 2 operands - for plus := e; ; { - args = append(args, summand{unparen(plus.Y), plus.OpPos}) - left := unparen(plus.X) - x, ok := left.(*syntax.BinaryExpr) - if !ok || x.Op != syntax.PLUS { - args = append(args, summand{x: left}) - break - } - plus = x - } - // Reverse args to syntactic order. - for i, n := 0, len(args)/2; i < n; i++ { - j := len(args) - 1 - i - args[i], args[j] = args[j], args[i] - } - - // Fold sums of adjacent literals of the same type: ""+"", []+[], ()+(). - out := args[:0] // compact in situ - for i := 0; i < len(args); { - j := i + 1 - if code := addable(args[i].x); code != 0 { - for j < len(args) && addable(args[j].x) == code { - j++ - } - if j > i+1 { - args[i].x = add(code, args[i:j]) - } - } - out = append(out, args[i]) - i = j - } - args = out - - // Emit code for an n-ary sum (n > 0). - fcomp.expr(args[0].x) - for _, summand := range args[1:] { - fcomp.expr(summand.x) - fcomp.setPos(summand.plusPos) - fcomp.emit(PLUS) - } - - // If len(args) > 2, use of an accumulator instead of a chain of - // PLUS operations may be more efficient. - // However, no gain was measured on a workload analogous to Bazel loading; - // TODO(adonovan): opt: re-evaluate on a Bazel analysis-like workload. - // - // We cannot use a single n-ary SUM operation - // a b c SUM<3> - // because we need to report a distinct error for each - // individual '+' operation, so three additional operations are - // needed: - // - // ACCSTART => create buffer and append to it - // ACCUM => append to buffer - // ACCEND => get contents of buffer - // - // For string, list, and tuple values, the interpreter can - // optimize these operations by using a mutable buffer. - // For all other types, ACCSTART and ACCEND would behave like - // the identity function and ACCUM behaves like PLUS. - // ACCUM must correctly support user-defined operations - // such as list+foo. - // - // fcomp.emit(ACCSTART) - // for _, summand := range args[1:] { - // fcomp.expr(summand.x) - // fcomp.setPos(summand.plusPos) - // fcomp.emit(ACCUM) - // } - // fcomp.emit(ACCEND) -} - -// addable reports whether e is a statically addable -// expression: a [s]tring, [b]ytes, [l]ist, or [t]uple. -func addable(e syntax.Expr) rune { - switch e := e.(type) { - case *syntax.Literal: - // TODO(adonovan): opt: support INT/FLOAT/BIGINT constant folding. - switch e.Token { - case syntax.STRING: - return 's' - case syntax.BYTES: - return 'b' - } - case *syntax.ListExpr: - return 'l' - case *syntax.TupleExpr: - return 't' - } - return 0 -} - -// add returns an expression denoting the sum of args, -// which are all addable values of the type indicated by code. -// The resulting syntax is degenerate, lacking position, etc. -func add(code rune, args []summand) syntax.Expr { - switch code { - case 's', 'b': - var buf strings.Builder - for _, arg := range args { - buf.WriteString(arg.x.(*syntax.Literal).Value.(string)) - } - tok := syntax.STRING - if code == 'b' { - tok = syntax.BYTES - } - return &syntax.Literal{Token: tok, Value: buf.String()} - case 'l': - var elems []syntax.Expr - for _, arg := range args { - elems = append(elems, arg.x.(*syntax.ListExpr).List...) - } - return &syntax.ListExpr{List: elems} - case 't': - var elems []syntax.Expr - for _, arg := range args { - elems = append(elems, arg.x.(*syntax.TupleExpr).List...) - } - return &syntax.TupleExpr{List: elems} - } - panic(code) -} - -func unparen(e syntax.Expr) syntax.Expr { - if p, ok := e.(*syntax.ParenExpr); ok { - return unparen(p.X) - } - return e -} - -func (fcomp *fcomp) binop(pos syntax.Position, op syntax.Token) { - // TODO(adonovan): simplify by assuming syntax and compiler constants align. - fcomp.setPos(pos) - switch op { - // arithmetic - case syntax.PLUS: - fcomp.emit(PLUS) - case syntax.MINUS: - fcomp.emit(MINUS) - case syntax.STAR: - fcomp.emit(STAR) - case syntax.SLASH: - fcomp.emit(SLASH) - case syntax.SLASHSLASH: - fcomp.emit(SLASHSLASH) - case syntax.PERCENT: - fcomp.emit(PERCENT) - case syntax.AMP: - fcomp.emit(AMP) - case syntax.PIPE: - fcomp.emit(PIPE) - case syntax.CIRCUMFLEX: - fcomp.emit(CIRCUMFLEX) - case syntax.LTLT: - fcomp.emit(LTLT) - case syntax.GTGT: - fcomp.emit(GTGT) - case syntax.IN: - fcomp.emit(IN) - case syntax.NOT_IN: - fcomp.emit(IN) - fcomp.emit(NOT) - - // comparisons - case syntax.EQL, - syntax.NEQ, - syntax.GT, - syntax.LT, - syntax.LE, - syntax.GE: - fcomp.emit(Opcode(op-syntax.EQL) + EQL) - - default: - log.Panicf("%s: unexpected binary op: %s", pos, op) - } -} - -func (fcomp *fcomp) call(call *syntax.CallExpr) { - // TODO(adonovan): opt: Use optimized path for calling methods - // of built-ins: x.f(...) to avoid materializing a closure. - // if dot, ok := call.Fcomp.(*syntax.DotExpr); ok { - // fcomp.expr(dot.X) - // fcomp.args(call) - // fcomp.emit1(CALL_ATTR, fcomp.name(dot.Name.Name)) - // return - // } - - // usual case - fcomp.expr(call.Fn) - op, arg := fcomp.args(call) - fcomp.setPos(call.Lparen) - fcomp.emit1(op, arg) -} - -// args emits code to push a tuple of positional arguments -// and a tuple of named arguments containing alternating keys and values. -// Either or both tuples may be empty (TODO(adonovan): optimize). -func (fcomp *fcomp) args(call *syntax.CallExpr) (op Opcode, arg uint32) { - var callmode int - // Compute the number of each kind of parameter. - var p, n int // number of positional, named arguments - var varargs, kwargs syntax.Expr - for _, arg := range call.Args { - if binary, ok := arg.(*syntax.BinaryExpr); ok && binary.Op == syntax.EQ { - - // named argument (name, value) - fcomp.string(binary.X.(*syntax.Ident).Name) - fcomp.expr(binary.Y) - n++ - continue - } - if unary, ok := arg.(*syntax.UnaryExpr); ok { - if unary.Op == syntax.STAR { - callmode |= 1 - varargs = unary.X - continue - } else if unary.Op == syntax.STARSTAR { - callmode |= 2 - kwargs = unary.X - continue - } - } - - // positional argument - fcomp.expr(arg) - p++ - } - - // Python2 and Python3 both permit named arguments - // to appear both before and after a *args argument: - // f(1, 2, x=3, *[4], y=5, **dict(z=6)) - // - // They also differ in their evaluation order: - // Python2: 1 2 3 5 4 6 (*args and **kwargs evaluated last) - // Python3: 1 2 4 3 5 6 (positional args evaluated before named args) - // Starlark-in-Java historically used a third order: - // Lexical: 1 2 3 4 5 6 (all args evaluated left-to-right) - // - // After discussion in github.com/bazelbuild/starlark#13, the - // spec now requires Starlark to statically reject named - // arguments after *args (e.g. y=5), and to use Python2-style - // evaluation order. This is both easy to implement and - // consistent with lexical order: - // - // f(1, 2, x=3, *[4], **dict(z=6)) # 1 2 3 4 6 - - // *args - if varargs != nil { - fcomp.expr(varargs) - } - - // **kwargs - if kwargs != nil { - fcomp.expr(kwargs) - } - - // TODO(adonovan): avoid this with a more flexible encoding. - if p >= 256 || n >= 256 { - // resolve already checked this; should be unreachable - panic("too many arguments in call") - } - - return CALL + Opcode(callmode), uint32(p<<8 | n) -} - -func (fcomp *fcomp) tuple(elems []syntax.Expr) { - for _, elem := range elems { - fcomp.expr(elem) - } - fcomp.emit1(MAKETUPLE, uint32(len(elems))) -} - -func (fcomp *fcomp) comprehension(comp *syntax.Comprehension, clauseIndex int) { - if clauseIndex == len(comp.Clauses) { - fcomp.emit(DUP) // accumulator - if comp.Curly { - // dict: {k:v for ...} - // Parser ensures that body is of form k:v. - // Python-style set comprehensions {body for vars in x} - // are not supported. - entry := comp.Body.(*syntax.DictEntry) - fcomp.expr(entry.Key) - fcomp.expr(entry.Value) - fcomp.setPos(entry.Colon) - fcomp.emit(SETDICT) - } else { - // list: [body for vars in x] - fcomp.expr(comp.Body) - fcomp.emit(APPEND) - } - return - } - - clause := comp.Clauses[clauseIndex] - switch clause := clause.(type) { - case *syntax.IfClause: - t := fcomp.newBlock() - done := fcomp.newBlock() - fcomp.ifelse(clause.Cond, t, done) - - fcomp.block = t - fcomp.comprehension(comp, clauseIndex+1) - fcomp.jump(done) - - fcomp.block = done - return - - case *syntax.ForClause: - // Keep consistent with ForStmt. - head := fcomp.newBlock() - body := fcomp.newBlock() - tail := fcomp.newBlock() - - fcomp.expr(clause.X) - fcomp.setPos(clause.For) - fcomp.emit(ITERPUSH) - fcomp.jump(head) - - fcomp.block = head - fcomp.condjump(ITERJMP, tail, body) - - fcomp.block = body - fcomp.assign(clause.For, clause.Vars) - fcomp.comprehension(comp, clauseIndex+1) - fcomp.jump(head) - - fcomp.block = tail - fcomp.emit(ITERPOP) - return - } - - start, _ := clause.Span() - log.Panicf("%s: unexpected comprehension clause %T", start, clause) -} - -func (fcomp *fcomp) function(f *resolve.Function) { - // Evaluation of the defaults may fail, so record the position. - fcomp.setPos(f.Pos) - - // To reduce allocation, we emit a combined tuple - // for the defaults and the freevars. - // The function knows where to split it at run time. - - // Generate tuple of parameter defaults. For: - // def f(p1, p2=dp2, p3=dp3, *, k1, k2=dk2, k3, **kwargs) - // the tuple is: - // (dp2, dp3, MANDATORY, dk2, MANDATORY). - ndefaults := 0 - seenStar := false - for _, param := range f.Params { - switch param := param.(type) { - case *syntax.BinaryExpr: - fcomp.expr(param.Y) - ndefaults++ - case *syntax.UnaryExpr: - seenStar = true // * or *args (also **kwargs) - case *syntax.Ident: - if seenStar { - fcomp.emit(MANDATORY) - ndefaults++ - } - } - } - - // Capture the cells of the function's - // free variables from the lexical environment. - for _, freevar := range f.FreeVars { - // Don't call fcomp.lookup because we want - // the cell itself, not its content. - switch freevar.Scope { - case resolve.Free: - fcomp.emit1(FREE, uint32(freevar.Index)) - case resolve.Cell: - fcomp.emit1(LOCAL, uint32(freevar.Index)) - } - } - - fcomp.emit1(MAKETUPLE, uint32(ndefaults+len(f.FreeVars))) - - funcode := fcomp.pcomp.function(f.Name, f.Pos, f.Body, f.Locals, f.FreeVars) - - if debug { - // TODO(adonovan): do compilations sequentially not as a tree, - // to make the log easier to read. - // Simplify by identifying Toplevel and functionIndex 0. - fmt.Fprintf(os.Stderr, "resuming %s @ %s\n", fcomp.fn.Name, fcomp.pos) - } - - // def f(a, *, b=1) has only 2 parameters. - numParams := len(f.Params) - if f.NumKwonlyParams > 0 && !f.HasVarargs { - numParams-- - } - - funcode.NumParams = numParams - funcode.NumKwonlyParams = f.NumKwonlyParams - funcode.HasVarargs = f.HasVarargs - funcode.HasKwargs = f.HasKwargs - fcomp.emit1(MAKEFUNC, fcomp.pcomp.functionIndex(funcode)) -} - -// ifelse emits a Boolean control flow decision. -// On return, the current block is unset. -func (fcomp *fcomp) ifelse(cond syntax.Expr, t, f *block) { - switch cond := cond.(type) { - case *syntax.UnaryExpr: - if cond.Op == syntax.NOT { - // if not x then goto t else goto f - // => - // if x then goto f else goto t - fcomp.ifelse(cond.X, f, t) - return - } - - case *syntax.BinaryExpr: - switch cond.Op { - case syntax.AND: - // if x and y then goto t else goto f - // => - // if x then ifelse(y, t, f) else goto f - fcomp.expr(cond.X) - y := fcomp.newBlock() - fcomp.condjump(CJMP, y, f) - - fcomp.block = y - fcomp.ifelse(cond.Y, t, f) - return - - case syntax.OR: - // if x or y then goto t else goto f - // => - // if x then goto t else ifelse(y, t, f) - fcomp.expr(cond.X) - y := fcomp.newBlock() - fcomp.condjump(CJMP, t, y) - - fcomp.block = y - fcomp.ifelse(cond.Y, t, f) - return - case syntax.NOT_IN: - // if x not in y then goto t else goto f - // => - // if x in y then goto f else goto t - copy := *cond - copy.Op = syntax.IN - fcomp.expr(©) - fcomp.condjump(CJMP, f, t) - return - } - } - - // general case - fcomp.expr(cond) - fcomp.condjump(CJMP, t, f) -} diff --git a/vendor/go.starlark.net/internal/compile/serial.go b/vendor/go.starlark.net/internal/compile/serial.go deleted file mode 100644 index 4d71738cc..000000000 --- a/vendor/go.starlark.net/internal/compile/serial.go +++ /dev/null @@ -1,399 +0,0 @@ -package compile - -// This file defines functions to read and write a compile.Program to a file. -// -// It is the client's responsibility to avoid version skew between the -// compiler used to produce a file and the interpreter that consumes it. -// The version number is provided as a constant. -// Incompatible protocol changes should also increment the version number. -// -// Encoding -// -// Program: -// "sky!" [4]byte # magic number -// str uint32le # offset of section -// version varint # must match Version -// filename string -// numloads varint -// loads []Ident -// numnames varint -// names []string -// numconsts varint -// consts []Constant -// numglobals varint -// globals []Ident -// toplevel Funcode -// numfuncs varint -// funcs []Funcode -// recursion varint (0 or 1) -// []byte # concatenation of all referenced strings -// EOF -// -// Funcode: -// id Ident -// code []byte -// pclinetablen varint -// pclinetab []varint -// numlocals varint -// locals []Ident -// numcells varint -// cells []int -// numfreevars varint -// freevar []Ident -// maxstack varint -// numparams varint -// numkwonlyparams varint -// hasvarargs varint (0 or 1) -// haskwargs varint (0 or 1) -// -// Ident: -// filename string -// line, col varint -// -// Constant: # type data -// type varint # 0=string string -// data ... # 1=bytes string -// # 2=int varint -// # 3=float varint (bits as uint64) -// # 4=bigint string (decimal ASCII text) -// -// The encoding starts with a four-byte magic number. -// The next four bytes are a little-endian uint32 -// that provides the offset of the string section -// at the end of the file, which contains the ordered -// concatenation of all strings referenced by the -// program. This design permits the decoder to read -// the first and second parts of the file into different -// memory allocations: the first (the encoded program) -// is transient, but the second (the strings) persists -// for the life of the Program. -// -// Within the encoded program, all strings are referred -// to by their length. As the encoder and decoder process -// the entire file sequentially, they are in lock step, -// so the start offset of each string is implicit. -// -// Program.Code is represented as a []byte slice to permit -// modification when breakpoints are set. All other strings -// are represented as strings. They all (unsafely) share the -// same backing byte slice. -// -// Aside from the str field, all integers are encoded as varints. - -import ( - "encoding/binary" - "fmt" - "math" - "math/big" - debugpkg "runtime/debug" - "unsafe" - - "go.starlark.net/syntax" -) - -const magic = "!sky" - -// Encode encodes a compiled Starlark program. -func (prog *Program) Encode() []byte { - var e encoder - e.p = append(e.p, magic...) - e.p = append(e.p, "????"...) // string data offset; filled in later - e.int(Version) - e.string(prog.Toplevel.Pos.Filename()) - e.bindings(prog.Loads) - e.int(len(prog.Names)) - for _, name := range prog.Names { - e.string(name) - } - e.int(len(prog.Constants)) - for _, c := range prog.Constants { - switch c := c.(type) { - case string: - e.int(0) - e.string(c) - case Bytes: - e.int(1) - e.string(string(c)) - case int64: - e.int(2) - e.int64(c) - case float64: - e.int(3) - e.uint64(math.Float64bits(c)) - case *big.Int: - e.int(4) - e.string(c.Text(10)) - } - } - e.bindings(prog.Globals) - e.function(prog.Toplevel) - e.int(len(prog.Functions)) - for _, fn := range prog.Functions { - e.function(fn) - } - e.int(b2i(prog.Recursion)) - - // Patch in the offset of the string data section. - binary.LittleEndian.PutUint32(e.p[4:8], uint32(len(e.p))) - - return append(e.p, e.s...) -} - -type encoder struct { - p []byte // encoded program - s []byte // strings - tmp [binary.MaxVarintLen64]byte -} - -func (e *encoder) int(x int) { - e.int64(int64(x)) -} - -func (e *encoder) int64(x int64) { - n := binary.PutVarint(e.tmp[:], x) - e.p = append(e.p, e.tmp[:n]...) -} - -func (e *encoder) uint64(x uint64) { - n := binary.PutUvarint(e.tmp[:], x) - e.p = append(e.p, e.tmp[:n]...) -} - -func (e *encoder) string(s string) { - e.int(len(s)) - e.s = append(e.s, s...) -} - -func (e *encoder) bytes(b []byte) { - e.int(len(b)) - e.s = append(e.s, b...) -} - -func (e *encoder) binding(bind Binding) { - e.string(bind.Name) - e.int(int(bind.Pos.Line)) - e.int(int(bind.Pos.Col)) -} - -func (e *encoder) bindings(binds []Binding) { - e.int(len(binds)) - for _, bind := range binds { - e.binding(bind) - } -} - -func (e *encoder) function(fn *Funcode) { - e.binding(Binding{fn.Name, fn.Pos}) - e.string(fn.Doc) - e.bytes(fn.Code) - e.int(len(fn.pclinetab)) - for _, x := range fn.pclinetab { - e.int64(int64(x)) - } - e.bindings(fn.Locals) - e.int(len(fn.Cells)) - for _, index := range fn.Cells { - e.int(index) - } - e.bindings(fn.Freevars) - e.int(fn.MaxStack) - e.int(fn.NumParams) - e.int(fn.NumKwonlyParams) - e.int(b2i(fn.HasVarargs)) - e.int(b2i(fn.HasKwargs)) -} - -func b2i(b bool) int { - if b { - return 1 - } else { - return 0 - } -} - -// DecodeProgram decodes a compiled Starlark program from data. -func DecodeProgram(data []byte) (_ *Program, err error) { - if len(data) < len(magic) { - return nil, fmt.Errorf("not a compiled module: no magic number") - } - if got := string(data[:4]); got != magic { - return nil, fmt.Errorf("not a compiled module: got magic number %q, want %q", - got, magic) - } - defer func() { - if x := recover(); x != nil { - debugpkg.PrintStack() - err = fmt.Errorf("internal error while decoding program: %v", x) - } - }() - - offset := binary.LittleEndian.Uint32(data[4:8]) - d := decoder{ - p: data[8:offset], - s: append([]byte(nil), data[offset:]...), // allocate a copy, which will persist - } - - if v := d.int(); v != Version { - return nil, fmt.Errorf("version mismatch: read %d, want %d", v, Version) - } - - filename := d.string() - d.filename = &filename - - loads := d.bindings() - - names := make([]string, d.int()) - for i := range names { - names[i] = d.string() - } - - // constants - constants := make([]interface{}, d.int()) - for i := range constants { - var c interface{} - switch d.int() { - case 0: - c = d.string() - case 1: - c = Bytes(d.string()) - case 2: - c = d.int64() - case 3: - c = math.Float64frombits(d.uint64()) - case 4: - c, _ = new(big.Int).SetString(d.string(), 10) - } - constants[i] = c - } - - globals := d.bindings() - toplevel := d.function() - funcs := make([]*Funcode, d.int()) - for i := range funcs { - funcs[i] = d.function() - } - recursion := d.int() != 0 - - prog := &Program{ - Loads: loads, - Names: names, - Constants: constants, - Globals: globals, - Functions: funcs, - Toplevel: toplevel, - Recursion: recursion, - } - toplevel.Prog = prog - for _, f := range funcs { - f.Prog = prog - } - - if len(d.p)+len(d.s) > 0 { - return nil, fmt.Errorf("internal error: unconsumed data during decoding") - } - - return prog, nil -} - -type decoder struct { - p []byte // encoded program - s []byte // strings - filename *string // (indirect to avoid keeping decoder live) -} - -func (d *decoder) int() int { - return int(d.int64()) -} - -func (d *decoder) int64() int64 { - x, len := binary.Varint(d.p[:]) - d.p = d.p[len:] - return x -} - -func (d *decoder) uint64() uint64 { - x, len := binary.Uvarint(d.p[:]) - d.p = d.p[len:] - return x -} - -func (d *decoder) string() (s string) { - if slice := d.bytes(); len(slice) > 0 { - // Avoid a memory allocation for each string - // by unsafely aliasing slice. - type string struct { - data *byte - len int - } - ptr := (*string)(unsafe.Pointer(&s)) - ptr.data = &slice[0] - ptr.len = len(slice) - } - return s -} - -func (d *decoder) bytes() []byte { - len := d.int() - r := d.s[:len:len] - d.s = d.s[len:] - return r -} - -func (d *decoder) binding() Binding { - name := d.string() - line := int32(d.int()) - col := int32(d.int()) - return Binding{Name: name, Pos: syntax.MakePosition(d.filename, line, col)} -} - -func (d *decoder) bindings() []Binding { - bindings := make([]Binding, d.int()) - for i := range bindings { - bindings[i] = d.binding() - } - return bindings -} - -func (d *decoder) ints() []int { - ints := make([]int, d.int()) - for i := range ints { - ints[i] = d.int() - } - return ints -} - -func (d *decoder) bool() bool { return d.int() != 0 } - -func (d *decoder) function() *Funcode { - id := d.binding() - doc := d.string() - code := d.bytes() - pclinetab := make([]uint16, d.int()) - for i := range pclinetab { - pclinetab[i] = uint16(d.int()) - } - locals := d.bindings() - cells := d.ints() - freevars := d.bindings() - maxStack := d.int() - numParams := d.int() - numKwonlyParams := d.int() - hasVarargs := d.int() != 0 - hasKwargs := d.int() != 0 - return &Funcode{ - // Prog is filled in later. - Pos: id.Pos, - Name: id.Name, - Doc: doc, - Code: code, - pclinetab: pclinetab, - Locals: locals, - Cells: cells, - Freevars: freevars, - MaxStack: maxStack, - NumParams: numParams, - NumKwonlyParams: numKwonlyParams, - HasVarargs: hasVarargs, - HasKwargs: hasKwargs, - } -} diff --git a/vendor/go.starlark.net/internal/spell/spell.go b/vendor/go.starlark.net/internal/spell/spell.go deleted file mode 100644 index 7739fabaa..000000000 --- a/vendor/go.starlark.net/internal/spell/spell.go +++ /dev/null @@ -1,115 +0,0 @@ -// Package spell file defines a simple spelling checker for use in attribute errors -// such as "no such field .foo; did you mean .food?". -package spell - -import ( - "strings" - "unicode" -) - -// Nearest returns the element of candidates -// nearest to x using the Levenshtein metric, -// or "" if none were promising. -func Nearest(x string, candidates []string) string { - // Ignore underscores and case when matching. - fold := func(s string) string { - return strings.Map(func(r rune) rune { - if r == '_' { - return -1 - } - return unicode.ToLower(r) - }, s) - } - - x = fold(x) - - var best string - bestD := (len(x) + 1) / 2 // allow up to 50% typos - for _, c := range candidates { - d := levenshtein(x, fold(c), bestD) - if d < bestD { - bestD = d - best = c - } - } - return best -} - -// levenshtein returns the non-negative Levenshtein edit distance -// between the byte strings x and y. -// -// If the computed distance exceeds max, -// the function may return early with an approximate value > max. -func levenshtein(x, y string, max int) int { - // This implementation is derived from one by Laurent Le Brun in - // Bazel that uses the single-row space efficiency trick - // described at bitbucket.org/clearer/iosifovich. - - // Let x be the shorter string. - if len(x) > len(y) { - x, y = y, x - } - - // Remove common prefix. - for i := 0; i < len(x); i++ { - if x[i] != y[i] { - x = x[i:] - y = y[i:] - break - } - } - if x == "" { - return len(y) - } - - if d := abs(len(x) - len(y)); d > max { - return d // excessive length divergence - } - - row := make([]int, len(y)+1) - for i := range row { - row[i] = i - } - - for i := 1; i <= len(x); i++ { - row[0] = i - best := i - prev := i - 1 - for j := 1; j <= len(y); j++ { - a := prev + b2i(x[i-1] != y[j-1]) // substitution - b := 1 + row[j-1] // deletion - c := 1 + row[j] // insertion - k := min(a, min(b, c)) - prev, row[j] = row[j], k - best = min(best, k) - } - if best > max { - return best - } - } - return row[len(y)] -} - -func b2i(b bool) int { - if b { - return 1 - } else { - return 0 - } -} - -func min(x, y int) int { - if x < y { - return x - } else { - return y - } -} - -func abs(x int) int { - if x >= 0 { - return x - } else { - return -x - } -} diff --git a/vendor/go.starlark.net/resolve/binding.go b/vendor/go.starlark.net/resolve/binding.go deleted file mode 100644 index 8507e64c7..000000000 --- a/vendor/go.starlark.net/resolve/binding.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2019 The Bazel 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 resolve - -import "go.starlark.net/syntax" - -// This file defines resolver data types saved in the syntax tree. -// We cannot guarantee API stability for these types -// as they are closely tied to the implementation. - -// A Binding contains resolver information about an identifier. -// The resolver populates the Binding field of each syntax.Identifier. -// The Binding ties together all identifiers that denote the same variable. -type Binding struct { - Scope Scope - - // Index records the index into the enclosing - // - {DefStmt,File}.Locals, if Scope==Local - // - DefStmt.FreeVars, if Scope==Free - // - File.Globals, if Scope==Global. - // It is zero if Scope is Predeclared, Universal, or Undefined. - Index int - - First *syntax.Ident // first binding use (iff Scope==Local/Free/Global) -} - -// The Scope of Binding indicates what kind of scope it has. -type Scope uint8 - -const ( - Undefined Scope = iota // name is not defined - Local // name is local to its function or file - Cell // name is function-local but shared with a nested function - Free // name is cell of some enclosing function - Global // name is global to module - Predeclared // name is predeclared for this module (e.g. glob) - Universal // name is universal (e.g. len) -) - -var scopeNames = [...]string{ - Undefined: "undefined", - Local: "local", - Cell: "cell", - Free: "free", - Global: "global", - Predeclared: "predeclared", - Universal: "universal", -} - -func (scope Scope) String() string { return scopeNames[scope] } - -// A Module contains resolver information about a file. -// The resolver populates the Module field of each syntax.File. -type Module struct { - Locals []*Binding // the file's (comprehension-)local variables - Globals []*Binding // the file's global variables -} - -// A Function contains resolver information about a named or anonymous function. -// The resolver populates the Function field of each syntax.DefStmt and syntax.LambdaExpr. -type Function struct { - Pos syntax.Position // of DEF or LAMBDA - Name string // name of def, or "lambda" - Params []syntax.Expr // param = ident | ident=expr | * | *ident | **ident - Body []syntax.Stmt // contains synthetic 'return expr' for lambda - - HasVarargs bool // whether params includes *args (convenience) - HasKwargs bool // whether params includes **kwargs (convenience) - NumKwonlyParams int // number of keyword-only optional parameters - Locals []*Binding // this function's local/cell variables, parameters first - FreeVars []*Binding // enclosing cells to capture in closure -} diff --git a/vendor/go.starlark.net/resolve/resolve.go b/vendor/go.starlark.net/resolve/resolve.go deleted file mode 100644 index c576a6baf..000000000 --- a/vendor/go.starlark.net/resolve/resolve.go +++ /dev/null @@ -1,981 +0,0 @@ -// Copyright 2017 The Bazel 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 resolve defines a name-resolution pass for Starlark abstract -// syntax trees. -// -// The resolver sets the Locals and FreeVars arrays of each DefStmt and -// the LocalIndex field of each syntax.Ident that refers to a local or -// free variable. It also sets the Locals array of a File for locals -// bound by top-level comprehensions and load statements. -// Identifiers for global variables do not get an index. -package resolve // import "go.starlark.net/resolve" - -// All references to names are statically resolved. Names may be -// predeclared, global, or local to a function or file. -// File-local variables include those bound by top-level comprehensions -// and by load statements. ("Top-level" means "outside of any function".) -// The resolver maps each global name to a small integer and each local -// name to a small integer; these integers enable a fast and compact -// representation of globals and locals in the evaluator. -// -// As an optimization, the resolver classifies each predeclared name as -// either universal (e.g. None, len) or per-module (e.g. glob in Bazel's -// build language), enabling the evaluator to share the representation -// of the universal environment across all modules. -// -// The lexical environment is a tree of blocks with the file block at -// its root. The file's child blocks may be of two kinds: functions -// and comprehensions, and these may have further children of either -// kind. -// -// Python-style resolution requires multiple passes because a name is -// determined to be local to a function only if the function contains a -// "binding" use of it; similarly, a name is determined to be global (as -// opposed to predeclared) if the module contains a top-level binding use. -// Unlike ordinary top-level assignments, the bindings created by load -// statements are local to the file block. -// A non-binding use may lexically precede the binding to which it is resolved. -// In the first pass, we inspect each function, recording in -// 'uses' each identifier and the environment block in which it occurs. -// If a use of a name is binding, such as a function parameter or -// assignment, we add the name to the block's bindings mapping and add a -// local variable to the enclosing function. -// -// As we finish resolving each function, we inspect all the uses within -// that function and discard ones that were found to be function-local. The -// remaining ones must be either free (local to some lexically enclosing -// function), or top-level (global, predeclared, or file-local), but we cannot tell -// which until we have finished inspecting the outermost enclosing -// function. At that point, we can distinguish local from top-level names -// (and this is when Python would compute free variables). -// -// However, Starlark additionally requires that all references to global -// names are satisfied by some declaration in the current module; -// Starlark permits a function to forward-reference a global or file-local -// that has not -// been declared yet so long as it is declared before the end of the -// module. So, instead of re-resolving the unresolved references after -// each top-level function, we defer this until the end of the module -// and ensure that all such references are satisfied by some definition. -// -// At the end of the module, we visit each of the nested function blocks -// in bottom-up order, doing a recursive lexical lookup for each -// unresolved name. If the name is found to be local to some enclosing -// function, we must create a DefStmt.FreeVar (capture) parameter for -// each intervening function. We enter these synthetic bindings into -// the bindings map so that we create at most one freevar per name. If -// the name was not local, we check that it was defined at module level. -// -// We resolve all uses of locals in the module (due to load statements -// and comprehensions) in a similar way and compute the file's set of -// local variables. -// -// Starlark enforces that all global names are assigned at most once on -// all control flow paths by forbidding if/else statements and loops at -// top level. A global may be used before it is defined, leading to a -// dynamic error. However, the AllowGlobalReassign flag (really: allow -// top-level reassign) makes the resolver allow multiple to a variable -// at top-level. It also allows if-, for-, and while-loops at top-level, -// which in turn may make the evaluator dynamically assign multiple -// values to a variable at top-level. (These two roles should be separated.) - -import ( - "fmt" - "log" - "sort" - "strings" - - "go.starlark.net/internal/spell" - "go.starlark.net/syntax" -) - -const debug = false -const doesnt = "this Starlark dialect does not " - -// global options -// These features are either not standard Starlark (yet), or deprecated -// features of the BUILD language, so we put them behind flags. -// -// Deprecated: use an explicit [syntax.FileOptions] argument instead, -// as it avoids all the usual problems of global variables. -var ( - AllowSet = false // allow the 'set' built-in - AllowGlobalReassign = false // allow reassignment to top-level names; also, allow if/for/while at top-level - AllowRecursion = false // allow while statements and recursive functions - LoadBindsGlobally = false // load creates global not file-local bindings (deprecated) - - // obsolete flags for features that are now standard. No effect. - AllowNestedDef = true - AllowLambda = true - AllowFloat = true - AllowBitwise = true -) - -// File resolves the specified file and records information about the -// module in file.Module. -// -// The isPredeclared and isUniversal predicates report whether a name is -// a pre-declared identifier (visible in the current module) or a -// universal identifier (visible in every module). -// Clients should typically pass predeclared.Has for the first and -// starlark.Universe.Has for the second, where predeclared is the -// module's StringDict of predeclared names and starlark.Universe is the -// standard set of built-ins. -// The isUniverse predicate is supplied a parameter to avoid a cyclic -// dependency upon starlark.Universe, not because users should ever need -// to redefine it. -func File(file *syntax.File, isPredeclared, isUniversal func(name string) bool) error { - return REPLChunk(file, nil, isPredeclared, isUniversal) -} - -// REPLChunk is a generalization of the File function that supports a -// non-empty initial global block, as occurs in a REPL. -func REPLChunk(file *syntax.File, isGlobal, isPredeclared, isUniversal func(name string) bool) error { - r := newResolver(file.Options, isGlobal, isPredeclared, isUniversal) - r.stmts(file.Stmts) - - r.env.resolveLocalUses() - - // At the end of the module, resolve all non-local variable references, - // computing closures. - // Function bodies may contain forward references to later global declarations. - r.resolveNonLocalUses(r.env) - - file.Module = &Module{ - Locals: r.moduleLocals, - Globals: r.moduleGlobals, - } - - if len(r.errors) > 0 { - return r.errors - } - return nil -} - -// Expr calls [ExprOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func Expr(expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*Binding, error) { - return ExprOptions(syntax.LegacyFileOptions(), expr, isPredeclared, isUniversal) -} - -// ExprOptions resolves the specified expression. -// It returns the local variables bound within the expression. -// -// The isPredeclared and isUniversal predicates behave as for the File function -func ExprOptions(opts *syntax.FileOptions, expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*Binding, error) { - r := newResolver(opts, nil, isPredeclared, isUniversal) - r.expr(expr) - r.env.resolveLocalUses() - r.resolveNonLocalUses(r.env) // globals & universals - if len(r.errors) > 0 { - return nil, r.errors - } - return r.moduleLocals, nil -} - -// An ErrorList is a non-empty list of resolver error messages. -type ErrorList []Error // len > 0 - -func (e ErrorList) Error() string { return e[0].Error() } - -// An Error describes the nature and position of a resolver error. -type Error struct { - Pos syntax.Position - Msg string -} - -func (e Error) Error() string { return e.Pos.String() + ": " + e.Msg } - -func newResolver(options *syntax.FileOptions, isGlobal, isPredeclared, isUniversal func(name string) bool) *resolver { - file := new(block) - return &resolver{ - options: options, - file: file, - env: file, - isGlobal: isGlobal, - isPredeclared: isPredeclared, - isUniversal: isUniversal, - globals: make(map[string]*Binding), - predeclared: make(map[string]*Binding), - } -} - -type resolver struct { - options *syntax.FileOptions - - // env is the current local environment: - // a linked list of blocks, innermost first. - // The tail of the list is the file block. - env *block - file *block // file block (contains load bindings) - - // moduleLocals contains the local variables of the module - // (due to load statements and comprehensions outside any function). - // moduleGlobals contains the global variables of the module. - moduleLocals []*Binding - moduleGlobals []*Binding - - // globals maps each global name in the module to its binding. - // predeclared does the same for predeclared and universal names. - globals map[string]*Binding - predeclared map[string]*Binding - - // These predicates report whether a name is - // pre-declared, either in this module or universally, - // or already declared in the module globals (as in a REPL). - // isGlobal may be nil. - isGlobal, isPredeclared, isUniversal func(name string) bool - - loops int // number of enclosing for/while loops - ifstmts int // number of enclosing if statements loops - - errors ErrorList -} - -// container returns the innermost enclosing "container" block: -// a function (function != nil) or file (function == nil). -// Container blocks accumulate local variable bindings. -func (r *resolver) container() *block { - for b := r.env; ; b = b.parent { - if b.function != nil || b == r.file { - return b - } - } -} - -func (r *resolver) push(b *block) { - r.env.children = append(r.env.children, b) - b.parent = r.env - r.env = b -} - -func (r *resolver) pop() { r.env = r.env.parent } - -type block struct { - parent *block // nil for file block - - // In the file (root) block, both these fields are nil. - function *Function // only for function blocks - comp *syntax.Comprehension // only for comprehension blocks - - // bindings maps a name to its binding. - // A local binding has an index into its innermost enclosing container's locals array. - // A free binding has an index into its innermost enclosing function's freevars array. - bindings map[string]*Binding - - // children records the child blocks of the current one. - children []*block - - // uses records all identifiers seen in this container (function or file), - // and a reference to the environment in which they appear. - // As we leave each container block, we resolve them, - // so that only free and global ones remain. - // At the end of each top-level function we compute closures. - uses []use -} - -func (b *block) bind(name string, bind *Binding) { - if b.bindings == nil { - b.bindings = make(map[string]*Binding) - } - b.bindings[name] = bind -} - -func (b *block) String() string { - if b.function != nil { - return "function block at " + fmt.Sprint(b.function.Pos) - } - if b.comp != nil { - return "comprehension block at " + fmt.Sprint(b.comp.Span()) - } - return "file block" -} - -func (r *resolver) errorf(posn syntax.Position, format string, args ...interface{}) { - r.errors = append(r.errors, Error{posn, fmt.Sprintf(format, args...)}) -} - -// A use records an identifier and the environment in which it appears. -type use struct { - id *syntax.Ident - env *block -} - -// bind creates a binding for id: a global (not file-local) -// binding at top-level, a local binding otherwise. -// At top-level, it reports an error if a global or file-local -// binding already exists, unless AllowGlobalReassign. -// It sets id.Binding to the binding (whether old or new), -// and returns whether a binding already existed. -func (r *resolver) bind(id *syntax.Ident) bool { - // Binding outside any local (comprehension/function) block? - if r.env == r.file { - bind, ok := r.file.bindings[id.Name] - if !ok { - bind, ok = r.globals[id.Name] - if !ok { - // first global binding of this name - bind = &Binding{ - First: id, - Scope: Global, - Index: len(r.moduleGlobals), - } - r.globals[id.Name] = bind - r.moduleGlobals = append(r.moduleGlobals, bind) - } - } - if ok && !r.options.GlobalReassign { - r.errorf(id.NamePos, "cannot reassign %s %s declared at %s", - bind.Scope, id.Name, bind.First.NamePos) - } - id.Binding = bind - return ok - } - - return r.bindLocal(id) -} - -func (r *resolver) bindLocal(id *syntax.Ident) bool { - // Mark this name as local to current block. - // Assign it a new local (positive) index in the current container. - _, ok := r.env.bindings[id.Name] - if !ok { - var locals *[]*Binding - if fn := r.container().function; fn != nil { - locals = &fn.Locals - } else { - locals = &r.moduleLocals - } - bind := &Binding{ - First: id, - Scope: Local, - Index: len(*locals), - } - r.env.bind(id.Name, bind) - *locals = append(*locals, bind) - } - - r.use(id) - return ok -} - -func (r *resolver) use(id *syntax.Ident) { - use := use{id, r.env} - - // The spec says that if there is a global binding of a name - // then all references to that name in that block refer to the - // global, even if the use precedes the def---just as for locals. - // For example, in this code, - // - // print(len); len=1; print(len) - // - // both occurrences of len refer to the len=1 binding, which - // completely shadows the predeclared len function. - // - // The rationale for these semantics, which differ from Python, - // is that the static meaning of len (a reference to a global) - // does not change depending on where it appears in the file. - // Of course, its dynamic meaning does change, from an error - // into a valid reference, so it's not clear these semantics - // have any practical advantage. - // - // In any case, the Bazel implementation lags behind the spec - // and follows Python behavior, so the first use of len refers - // to the predeclared function. This typically used in a BUILD - // file that redefines a predeclared name half way through, - // for example: - // - // proto_library(...) # built-in rule - // load("myproto.bzl", "proto_library") - // proto_library(...) # user-defined rule - // - // We will piggyback support for the legacy semantics on the - // AllowGlobalReassign flag, which is loosely related and also - // required for Bazel. - if r.options.GlobalReassign && r.env == r.file { - r.useToplevel(use) - return - } - - b := r.container() - b.uses = append(b.uses, use) -} - -// useToplevel resolves use.id as a reference to a name visible at top-level. -// The use.env field captures the original environment for error reporting. -func (r *resolver) useToplevel(use use) (bind *Binding) { - id := use.id - - if prev, ok := r.file.bindings[id.Name]; ok { - // use of load-defined name in file block - bind = prev - } else if prev, ok := r.globals[id.Name]; ok { - // use of global declared by module - bind = prev - } else if r.isGlobal != nil && r.isGlobal(id.Name) { - // use of global defined in a previous REPL chunk - bind = &Binding{ - First: id, // wrong: this is not even a binding use - Scope: Global, - Index: len(r.moduleGlobals), - } - r.globals[id.Name] = bind - r.moduleGlobals = append(r.moduleGlobals, bind) - } else if prev, ok := r.predeclared[id.Name]; ok { - // repeated use of predeclared or universal - bind = prev - } else if r.isPredeclared(id.Name) { - // use of pre-declared name - bind = &Binding{Scope: Predeclared} - r.predeclared[id.Name] = bind // save it - } else if r.isUniversal(id.Name) { - // use of universal name - if !r.options.Set && id.Name == "set" { - r.errorf(id.NamePos, doesnt+"support sets") - } - bind = &Binding{Scope: Universal} - r.predeclared[id.Name] = bind // save it - } else { - bind = &Binding{Scope: Undefined} - var hint string - if n := r.spellcheck(use); n != "" { - hint = fmt.Sprintf(" (did you mean %s?)", n) - } - r.errorf(id.NamePos, "undefined: %s%s", id.Name, hint) - } - id.Binding = bind - return bind -} - -// spellcheck returns the most likely misspelling of -// the name use.id in the environment use.env. -func (r *resolver) spellcheck(use use) string { - var names []string - - // locals - for b := use.env; b != nil; b = b.parent { - for name := range b.bindings { - names = append(names, name) - } - } - - // globals - // - // We have no way to enumerate the sets whose membership - // tests are isPredeclared, isUniverse, and isGlobal, - // which includes prior names in the REPL session. - for _, bind := range r.moduleGlobals { - names = append(names, bind.First.Name) - } - - sort.Strings(names) - return spell.Nearest(use.id.Name, names) -} - -// resolveLocalUses is called when leaving a container (function/module) -// block. It resolves all uses of locals/cells within that block. -func (b *block) resolveLocalUses() { - unresolved := b.uses[:0] - for _, use := range b.uses { - if bind := lookupLocal(use); bind != nil && (bind.Scope == Local || bind.Scope == Cell) { - use.id.Binding = bind - } else { - unresolved = append(unresolved, use) - } - } - b.uses = unresolved -} - -func (r *resolver) stmts(stmts []syntax.Stmt) { - for _, stmt := range stmts { - r.stmt(stmt) - } -} - -func (r *resolver) stmt(stmt syntax.Stmt) { - switch stmt := stmt.(type) { - case *syntax.ExprStmt: - r.expr(stmt.X) - - case *syntax.BranchStmt: - if r.loops == 0 && (stmt.Token == syntax.BREAK || stmt.Token == syntax.CONTINUE) { - r.errorf(stmt.TokenPos, "%s not in a loop", stmt.Token) - } - - case *syntax.IfStmt: - if !r.options.TopLevelControl && r.container().function == nil { - r.errorf(stmt.If, "if statement not within a function") - } - r.expr(stmt.Cond) - r.ifstmts++ - r.stmts(stmt.True) - r.stmts(stmt.False) - r.ifstmts-- - - case *syntax.AssignStmt: - r.expr(stmt.RHS) - isAugmented := stmt.Op != syntax.EQ - r.assign(stmt.LHS, isAugmented) - - case *syntax.DefStmt: - r.bind(stmt.Name) - fn := &Function{ - Name: stmt.Name.Name, - Pos: stmt.Def, - Params: stmt.Params, - Body: stmt.Body, - } - stmt.Function = fn - r.function(fn, stmt.Def) - - case *syntax.ForStmt: - if !r.options.TopLevelControl && r.container().function == nil { - r.errorf(stmt.For, "for loop not within a function") - } - r.expr(stmt.X) - const isAugmented = false - r.assign(stmt.Vars, isAugmented) - r.loops++ - r.stmts(stmt.Body) - r.loops-- - - case *syntax.WhileStmt: - if !r.options.While { - r.errorf(stmt.While, doesnt+"support while loops") - } - if !r.options.TopLevelControl && r.container().function == nil { - r.errorf(stmt.While, "while loop not within a function") - } - r.expr(stmt.Cond) - r.loops++ - r.stmts(stmt.Body) - r.loops-- - - case *syntax.ReturnStmt: - if r.container().function == nil { - r.errorf(stmt.Return, "return statement not within a function") - } - if stmt.Result != nil { - r.expr(stmt.Result) - } - - case *syntax.LoadStmt: - // A load statement may not be nested in any other statement. - if r.container().function != nil { - r.errorf(stmt.Load, "load statement within a function") - } else if r.loops > 0 { - r.errorf(stmt.Load, "load statement within a loop") - } else if r.ifstmts > 0 { - r.errorf(stmt.Load, "load statement within a conditional") - } - - for i, from := range stmt.From { - if from.Name == "" { - r.errorf(from.NamePos, "load: empty identifier") - continue - } - if from.Name[0] == '_' { - r.errorf(from.NamePos, "load: names with leading underscores are not exported: %s", from.Name) - } - - id := stmt.To[i] - if r.options.LoadBindsGlobally { - r.bind(id) - } else if r.bindLocal(id) && !r.options.GlobalReassign { - // "Global" in AllowGlobalReassign is a misnomer for "toplevel". - // Sadly we can't report the previous declaration - // as id.Binding may not be set yet. - r.errorf(id.NamePos, "cannot reassign top-level %s", id.Name) - } - } - - default: - log.Panicf("unexpected stmt %T", stmt) - } -} - -func (r *resolver) assign(lhs syntax.Expr, isAugmented bool) { - switch lhs := lhs.(type) { - case *syntax.Ident: - // x = ... - r.bind(lhs) - - case *syntax.IndexExpr: - // x[i] = ... - r.expr(lhs.X) - r.expr(lhs.Y) - - case *syntax.DotExpr: - // x.f = ... - r.expr(lhs.X) - - case *syntax.TupleExpr: - // (x, y) = ... - if isAugmented { - r.errorf(syntax.Start(lhs), "can't use tuple expression in augmented assignment") - } - for _, elem := range lhs.List { - r.assign(elem, isAugmented) - } - - case *syntax.ListExpr: - // [x, y, z] = ... - if isAugmented { - r.errorf(syntax.Start(lhs), "can't use list expression in augmented assignment") - } - for _, elem := range lhs.List { - r.assign(elem, isAugmented) - } - - case *syntax.ParenExpr: - r.assign(lhs.X, isAugmented) - - default: - name := strings.ToLower(strings.TrimPrefix(fmt.Sprintf("%T", lhs), "*syntax.")) - r.errorf(syntax.Start(lhs), "can't assign to %s", name) - } -} - -func (r *resolver) expr(e syntax.Expr) { - switch e := e.(type) { - case *syntax.Ident: - r.use(e) - - case *syntax.Literal: - - case *syntax.ListExpr: - for _, x := range e.List { - r.expr(x) - } - - case *syntax.CondExpr: - r.expr(e.Cond) - r.expr(e.True) - r.expr(e.False) - - case *syntax.IndexExpr: - r.expr(e.X) - r.expr(e.Y) - - case *syntax.DictEntry: - r.expr(e.Key) - r.expr(e.Value) - - case *syntax.SliceExpr: - r.expr(e.X) - if e.Lo != nil { - r.expr(e.Lo) - } - if e.Hi != nil { - r.expr(e.Hi) - } - if e.Step != nil { - r.expr(e.Step) - } - - case *syntax.Comprehension: - // The 'in' operand of the first clause (always a ForClause) - // is resolved in the outer block; consider: [x for x in x]. - clause := e.Clauses[0].(*syntax.ForClause) - r.expr(clause.X) - - // A list/dict comprehension defines a new lexical block. - // Locals defined within the block will be allotted - // distinct slots in the locals array of the innermost - // enclosing container (function/module) block. - r.push(&block{comp: e}) - - const isAugmented = false - r.assign(clause.Vars, isAugmented) - - for _, clause := range e.Clauses[1:] { - switch clause := clause.(type) { - case *syntax.IfClause: - r.expr(clause.Cond) - case *syntax.ForClause: - r.assign(clause.Vars, isAugmented) - r.expr(clause.X) - } - } - r.expr(e.Body) // body may be *DictEntry - r.pop() - - case *syntax.TupleExpr: - for _, x := range e.List { - r.expr(x) - } - - case *syntax.DictExpr: - for _, entry := range e.List { - entry := entry.(*syntax.DictEntry) - r.expr(entry.Key) - r.expr(entry.Value) - } - - case *syntax.UnaryExpr: - r.expr(e.X) - - case *syntax.BinaryExpr: - r.expr(e.X) - r.expr(e.Y) - - case *syntax.DotExpr: - r.expr(e.X) - // ignore e.Name - - case *syntax.CallExpr: - r.expr(e.Fn) - var seenVarargs, seenKwargs bool - var seenName map[string]bool - var n, p int - for _, arg := range e.Args { - pos, _ := arg.Span() - if unop, ok := arg.(*syntax.UnaryExpr); ok && unop.Op == syntax.STARSTAR { - // **kwargs - if seenKwargs { - r.errorf(pos, "multiple **kwargs not allowed") - } - seenKwargs = true - r.expr(arg) - } else if ok && unop.Op == syntax.STAR { - // *args - if seenKwargs { - r.errorf(pos, "*args may not follow **kwargs") - } else if seenVarargs { - r.errorf(pos, "multiple *args not allowed") - } - seenVarargs = true - r.expr(arg) - } else if binop, ok := arg.(*syntax.BinaryExpr); ok && binop.Op == syntax.EQ { - // k=v - n++ - if seenKwargs { - r.errorf(pos, "keyword argument may not follow **kwargs") - } else if seenVarargs { - r.errorf(pos, "keyword argument may not follow *args") - } - x := binop.X.(*syntax.Ident) - if seenName[x.Name] { - r.errorf(x.NamePos, "keyword argument %q is repeated", x.Name) - } else { - if seenName == nil { - seenName = make(map[string]bool) - } - seenName[x.Name] = true - } - r.expr(binop.Y) - } else { - // positional argument - p++ - if seenVarargs { - r.errorf(pos, "positional argument may not follow *args") - } else if seenKwargs { - r.errorf(pos, "positional argument may not follow **kwargs") - } else if len(seenName) > 0 { - r.errorf(pos, "positional argument may not follow named") - } - r.expr(arg) - } - } - - // Fail gracefully if compiler-imposed limit is exceeded. - if p >= 256 { - pos, _ := e.Span() - r.errorf(pos, "%v positional arguments in call, limit is 255", p) - } - if n >= 256 { - pos, _ := e.Span() - r.errorf(pos, "%v keyword arguments in call, limit is 255", n) - } - - case *syntax.LambdaExpr: - fn := &Function{ - Name: "lambda", - Pos: e.Lambda, - Params: e.Params, - Body: []syntax.Stmt{&syntax.ReturnStmt{Result: e.Body}}, - } - e.Function = fn - r.function(fn, e.Lambda) - - case *syntax.ParenExpr: - r.expr(e.X) - - default: - log.Panicf("unexpected expr %T", e) - } -} - -func (r *resolver) function(function *Function, pos syntax.Position) { - // Resolve defaults in enclosing environment. - for _, param := range function.Params { - if binary, ok := param.(*syntax.BinaryExpr); ok { - r.expr(binary.Y) - } - } - - // Enter function block. - b := &block{function: function} - r.push(b) - - var seenOptional bool - var star *syntax.UnaryExpr // * or *args param - var starStar *syntax.Ident // **kwargs ident - var numKwonlyParams int - for _, param := range function.Params { - switch param := param.(type) { - case *syntax.Ident: - // e.g. x - if starStar != nil { - r.errorf(param.NamePos, "required parameter may not follow **%s", starStar.Name) - } else if star != nil { - numKwonlyParams++ - } else if seenOptional { - r.errorf(param.NamePos, "required parameter may not follow optional") - } - if r.bind(param) { - r.errorf(param.NamePos, "duplicate parameter: %s", param.Name) - } - - case *syntax.BinaryExpr: - // e.g. y=dflt - if starStar != nil { - r.errorf(param.OpPos, "optional parameter may not follow **%s", starStar.Name) - } else if star != nil { - numKwonlyParams++ - } - if id := param.X.(*syntax.Ident); r.bind(id) { - r.errorf(param.OpPos, "duplicate parameter: %s", id.Name) - } - seenOptional = true - - case *syntax.UnaryExpr: - // * or *args or **kwargs - if param.Op == syntax.STAR { - if starStar != nil { - r.errorf(param.OpPos, "* parameter may not follow **%s", starStar.Name) - } else if star != nil { - r.errorf(param.OpPos, "multiple * parameters not allowed") - } else { - star = param - } - } else { - if starStar != nil { - r.errorf(param.OpPos, "multiple ** parameters not allowed") - } - starStar = param.X.(*syntax.Ident) - } - } - } - - // Bind the *args and **kwargs parameters at the end, - // so that regular parameters a/b/c are contiguous and - // there is no hole for the "*": - // def f(a, b, *args, c=0, **kwargs) - // def f(a, b, *, c=0, **kwargs) - if star != nil { - if id, _ := star.X.(*syntax.Ident); id != nil { - // *args - if r.bind(id) { - r.errorf(id.NamePos, "duplicate parameter: %s", id.Name) - } - function.HasVarargs = true - } else if numKwonlyParams == 0 { - r.errorf(star.OpPos, "bare * must be followed by keyword-only parameters") - } - } - if starStar != nil { - if r.bind(starStar) { - r.errorf(starStar.NamePos, "duplicate parameter: %s", starStar.Name) - } - function.HasKwargs = true - } - - function.NumKwonlyParams = numKwonlyParams - r.stmts(function.Body) - - // Resolve all uses of this function's local vars, - // and keep just the remaining uses of free/global vars. - b.resolveLocalUses() - - // Leave function block. - r.pop() - - // References within the function body to globals are not - // resolved until the end of the module. -} - -func (r *resolver) resolveNonLocalUses(b *block) { - // First resolve inner blocks. - for _, child := range b.children { - r.resolveNonLocalUses(child) - } - for _, use := range b.uses { - use.id.Binding = r.lookupLexical(use, use.env) - } -} - -// lookupLocal looks up an identifier within its immediately enclosing function. -func lookupLocal(use use) *Binding { - for env := use.env; env != nil; env = env.parent { - if bind, ok := env.bindings[use.id.Name]; ok { - if bind.Scope == Free { - // shouldn't exist till later - log.Panicf("%s: internal error: %s, %v", use.id.NamePos, use.id.Name, bind) - } - return bind // found - } - if env.function != nil { - break - } - } - return nil // not found in this function -} - -// lookupLexical looks up an identifier use.id within its lexically enclosing environment. -// The use.env field captures the original environment for error reporting. -func (r *resolver) lookupLexical(use use, env *block) (bind *Binding) { - if debug { - fmt.Printf("lookupLexical %s in %s = ...\n", use.id.Name, env) - defer func() { fmt.Printf("= %v\n", bind) }() - } - - // Is this the file block? - if env == r.file { - return r.useToplevel(use) // file-local, global, predeclared, or not found - } - - // Defined in this block? - bind, ok := env.bindings[use.id.Name] - if !ok { - // Defined in parent block? - bind = r.lookupLexical(use, env.parent) - if env.function != nil && (bind.Scope == Local || bind.Scope == Free || bind.Scope == Cell) { - // Found in parent block, which belongs to enclosing function. - // Add the parent's binding to the function's freevars, - // and add a new 'free' binding to the inner function's block, - // and turn the parent's local into cell. - if bind.Scope == Local { - bind.Scope = Cell - } - index := len(env.function.FreeVars) - env.function.FreeVars = append(env.function.FreeVars, bind) - bind = &Binding{ - First: bind.First, - Scope: Free, - Index: index, - } - if debug { - fmt.Printf("creating freevar %v in function at %s: %s\n", - len(env.function.FreeVars), env.function.Pos, use.id.Name) - } - } - - // Memoize, to avoid duplicate free vars - // and redundant global (failing) lookups. - env.bind(use.id.Name, bind) - } - return bind -} diff --git a/vendor/go.starlark.net/starlark/debug.go b/vendor/go.starlark.net/starlark/debug.go deleted file mode 100644 index 22a21240f..000000000 --- a/vendor/go.starlark.net/starlark/debug.go +++ /dev/null @@ -1,42 +0,0 @@ -package starlark - -import "go.starlark.net/syntax" - -// This file defines an experimental API for the debugging tools. -// Some of these declarations expose details of internal packages. -// (The debugger makes liberal use of exported fields of unexported types.) -// Breaking changes may occur without notice. - -// Local returns the value of the i'th local variable. -// It may be nil if not yet assigned. -// -// Local may be called only for frames whose Callable is a *Function (a -// function defined by Starlark source code), and only while the frame -// is active; it will panic otherwise. -// -// This function is provided only for debugging tools. -// -// THIS API IS EXPERIMENTAL AND MAY CHANGE WITHOUT NOTICE. -func (fr *frame) Local(i int) Value { return fr.locals[i] } - -// DebugFrame is the debugger API for a frame of the interpreter's call stack. -// -// Most applications have no need for this API; use CallFrame instead. -// -// Clients must not retain a DebugFrame nor call any of its methods once -// the current built-in call has returned or execution has resumed -// after a breakpoint as this may have unpredictable effects, including -// but not limited to retention of object that would otherwise be garbage. -type DebugFrame interface { - Callable() Callable // returns the frame's function - Local(i int) Value // returns the value of the (Starlark) frame's ith local variable - Position() syntax.Position // returns the current position of execution in this frame -} - -// DebugFrame returns the debugger interface for -// the specified frame of the interpreter's call stack. -// Frame numbering is as for Thread.CallFrame. -// -// This function is intended for use in debugging tools. -// Most applications should have no need for it; use CallFrame instead. -func (thread *Thread) DebugFrame(depth int) DebugFrame { return thread.frameAt(depth) } diff --git a/vendor/go.starlark.net/starlark/empty.s b/vendor/go.starlark.net/starlark/empty.s deleted file mode 100644 index 3b8216999..000000000 --- a/vendor/go.starlark.net/starlark/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// The presence of this file allows the package to use the -// "go:linkname" hack to call non-exported functions in the -// Go runtime, such as hardware-accelerated string hashing. diff --git a/vendor/go.starlark.net/starlark/eval.go b/vendor/go.starlark.net/starlark/eval.go deleted file mode 100644 index 6c11bc47d..000000000 --- a/vendor/go.starlark.net/starlark/eval.go +++ /dev/null @@ -1,1672 +0,0 @@ -// Copyright 2017 The Bazel 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 starlark - -import ( - "fmt" - "io" - "log" - "math/big" - "sort" - "strings" - "sync/atomic" - "time" - "unicode" - "unicode/utf8" - "unsafe" - - "go.starlark.net/internal/compile" - "go.starlark.net/internal/spell" - "go.starlark.net/resolve" - "go.starlark.net/syntax" -) - -// A Thread contains the state of a Starlark thread, -// such as its call stack and thread-local storage. -// The Thread is threaded throughout the evaluator. -type Thread struct { - // Name is an optional name that describes the thread, for debugging. - Name string - - // stack is the stack of (internal) call frames. - stack []*frame - - // Print is the client-supplied implementation of the Starlark - // 'print' function. If nil, fmt.Fprintln(os.Stderr, msg) is - // used instead. - Print func(thread *Thread, msg string) - - // Load is the client-supplied implementation of module loading. - // Repeated calls with the same module name must return the same - // module environment or error. - // The error message need not include the module name. - // - // See example_test.go for some example implementations of Load. - Load func(thread *Thread, module string) (StringDict, error) - - // OnMaxSteps is called when the thread reaches the limit set by SetMaxExecutionSteps. - // The default behavior is to call thread.Cancel("too many steps"). - OnMaxSteps func(thread *Thread) - - // Steps a count of abstract computation steps executed - // by this thread. It is incremented by the interpreter. It may be used - // as a measure of the approximate cost of Starlark execution, by - // computing the difference in its value before and after a computation. - // - // The precise meaning of "step" is not specified and may change. - Steps, maxSteps uint64 - - // cancelReason records the reason from the first call to Cancel. - cancelReason *string - - // locals holds arbitrary "thread-local" Go values belonging to the client. - // They are accessible to the client but not to any Starlark program. - locals map[string]interface{} - - // proftime holds the accumulated execution time since the last profile event. - proftime time.Duration -} - -// ExecutionSteps returns the current value of Steps. -func (thread *Thread) ExecutionSteps() uint64 { - return thread.Steps -} - -// SetMaxExecutionSteps sets a limit on the number of Starlark -// computation steps that may be executed by this thread. If the -// thread's step counter exceeds this limit, the interpreter calls -// the optional OnMaxSteps function or the default behavior -// of calling thread.Cancel("too many steps"). -func (thread *Thread) SetMaxExecutionSteps(max uint64) { - thread.maxSteps = max -} - -// Uncancel resets the cancellation state. -// -// Unlike most methods of Thread, it is safe to call Uncancel from any -// goroutine, even if the thread is actively executing. -func (thread *Thread) Uncancel() { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&thread.cancelReason)), nil) -} - -// Cancel causes execution of Starlark code in the specified thread to -// promptly fail with an EvalError that includes the specified reason. -// There may be a delay before the interpreter observes the cancellation -// if the thread is currently in a call to a built-in function. -// -// Call [Uncancel] to reset the cancellation state. -// -// Unlike most methods of Thread, it is safe to call Cancel from any -// goroutine, even if the thread is actively executing. -func (thread *Thread) Cancel(reason string) { - // Atomically set cancelReason, preserving earlier reason if any. - atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&thread.cancelReason)), nil, unsafe.Pointer(&reason)) -} - -// SetLocal sets the thread-local value associated with the specified key. -// It must not be called after execution begins. -func (thread *Thread) SetLocal(key string, value interface{}) { - if thread.locals == nil { - thread.locals = make(map[string]interface{}) - } - thread.locals[key] = value -} - -// Local returns the thread-local value associated with the specified key. -func (thread *Thread) Local(key string) interface{} { - return thread.locals[key] -} - -// CallFrame returns a copy of the specified frame of the callstack. -// It should only be used in built-ins called from Starlark code. -// Depth 0 means the frame of the built-in itself, 1 is its caller, and so on. -// -// It is equivalent to CallStack().At(depth), but more efficient. -func (thread *Thread) CallFrame(depth int) CallFrame { - return thread.frameAt(depth).asCallFrame() -} - -func (thread *Thread) frameAt(depth int) *frame { - return thread.stack[len(thread.stack)-1-depth] -} - -// CallStack returns a new slice containing the thread's stack of call frames. -func (thread *Thread) CallStack() CallStack { - frames := make([]CallFrame, len(thread.stack)) - for i, fr := range thread.stack { - frames[i] = fr.asCallFrame() - } - return frames -} - -// CallStackDepth returns the number of frames in the current call stack. -func (thread *Thread) CallStackDepth() int { return len(thread.stack) } - -// A StringDict is a mapping from names to values, and represents -// an environment such as the global variables of a module. -// It is not a true starlark.Value. -type StringDict map[string]Value - -// Keys returns a new sorted slice of d's keys. -func (d StringDict) Keys() []string { - names := make([]string, 0, len(d)) - for name := range d { - names = append(names, name) - } - sort.Strings(names) - return names -} - -func (d StringDict) String() string { - buf := new(strings.Builder) - buf.WriteByte('{') - sep := "" - for _, name := range d.Keys() { - buf.WriteString(sep) - buf.WriteString(name) - buf.WriteString(": ") - writeValue(buf, d[name], nil) - sep = ", " - } - buf.WriteByte('}') - return buf.String() -} - -func (d StringDict) Freeze() { - for _, v := range d { - v.Freeze() - } -} - -// Has reports whether the dictionary contains the specified key. -func (d StringDict) Has(key string) bool { _, ok := d[key]; return ok } - -// A frame records a call to a Starlark function (including module toplevel) -// or a built-in function or method. -type frame struct { - callable Callable // current function (or toplevel) or built-in - pc uint32 // program counter (Starlark frames only) - locals []Value // local variables (Starlark frames only) - spanStart int64 // start time of current profiler span -} - -// Position returns the source position of the current point of execution in this frame. -func (fr *frame) Position() syntax.Position { - switch c := fr.callable.(type) { - case *Function: - // Starlark function - return c.funcode.Position(fr.pc) - case callableWithPosition: - // If a built-in Callable defines - // a Position method, use it. - return c.Position() - } - return syntax.MakePosition(&builtinFilename, 0, 0) -} - -var builtinFilename = "" - -// Function returns the frame's function or built-in. -func (fr *frame) Callable() Callable { return fr.callable } - -// A CallStack is a stack of call frames, outermost first. -type CallStack []CallFrame - -// At returns a copy of the frame at depth i. -// At(0) returns the topmost frame. -func (stack CallStack) At(i int) CallFrame { return stack[len(stack)-1-i] } - -// Pop removes and returns the topmost frame. -func (stack *CallStack) Pop() CallFrame { - last := len(*stack) - 1 - top := (*stack)[last] - *stack = (*stack)[:last] - return top -} - -// String returns a user-friendly description of the stack. -func (stack CallStack) String() string { - out := new(strings.Builder) - if len(stack) > 0 { - fmt.Fprintf(out, "Traceback (most recent call last):\n") - } - for _, fr := range stack { - fmt.Fprintf(out, " %s: in %s\n", fr.Pos, fr.Name) - } - return out.String() -} - -// An EvalError is a Starlark evaluation error and -// a copy of the thread's stack at the moment of the error. -type EvalError struct { - Msg string - CallStack CallStack - cause error -} - -// A CallFrame represents the function name and current -// position of execution of an enclosing call frame. -type CallFrame struct { - Name string - Pos syntax.Position -} - -func (fr *frame) asCallFrame() CallFrame { - return CallFrame{ - Name: fr.Callable().Name(), - Pos: fr.Position(), - } -} - -func (thread *Thread) evalError(err error) *EvalError { - return &EvalError{ - Msg: err.Error(), - CallStack: thread.CallStack(), - cause: err, - } -} - -func (e *EvalError) Error() string { return e.Msg } - -// Backtrace returns a user-friendly error message describing the stack -// of calls that led to this error. -func (e *EvalError) Backtrace() string { - // If the topmost stack frame is a built-in function, - // remove it from the stack and add print "Error in fn:". - stack := e.CallStack - suffix := "" - if last := len(stack) - 1; last >= 0 && stack[last].Pos.Filename() == builtinFilename { - suffix = " in " + stack[last].Name - stack = stack[:last] - } - return fmt.Sprintf("%sError%s: %s", stack, suffix, e.Msg) -} - -func (e *EvalError) Unwrap() error { return e.cause } - -// A Program is a compiled Starlark program. -// -// Programs are immutable, and contain no Values. -// A Program may be created by parsing a source file (see SourceProgram) -// or by loading a previously saved compiled program (see CompiledProgram). -type Program struct { - compiled *compile.Program -} - -// CompilerVersion is the version number of the protocol for compiled -// files. Applications must not run programs compiled by one version -// with an interpreter at another version, and should thus incorporate -// the compiler version into the cache key when reusing compiled code. -const CompilerVersion = compile.Version - -// Filename returns the name of the file from which this program was loaded. -func (prog *Program) Filename() string { return prog.compiled.Toplevel.Pos.Filename() } - -func (prog *Program) String() string { return prog.Filename() } - -// NumLoads returns the number of load statements in the compiled program. -func (prog *Program) NumLoads() int { return len(prog.compiled.Loads) } - -// Load(i) returns the name and position of the i'th module directly -// loaded by this one, where 0 <= i < NumLoads(). -// The name is unresolved---exactly as it appears in the source. -func (prog *Program) Load(i int) (string, syntax.Position) { - id := prog.compiled.Loads[i] - return id.Name, id.Pos -} - -// WriteTo writes the compiled module to the specified output stream. -func (prog *Program) Write(out io.Writer) error { - data := prog.compiled.Encode() - _, err := out.Write(data) - return err -} - -// ExecFile calls [ExecFileOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func ExecFile(thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error) { - return ExecFileOptions(syntax.LegacyFileOptions(), thread, filename, src, predeclared) -} - -// ExecFileOptions parses, resolves, and executes a Starlark file in the -// specified global environment, which may be modified during execution. -// -// Thread is the state associated with the Starlark thread. -// -// The filename and src parameters are as for syntax.Parse: -// filename is the name of the file to execute, -// and the name that appears in error messages; -// src is an optional source of bytes to use -// instead of filename. -// -// predeclared defines the predeclared names specific to this module. -// Execution does not modify this dictionary, though it may mutate -// its values. -// -// If ExecFileOptions fails during evaluation, it returns an *EvalError -// containing a backtrace. -func ExecFileOptions(opts *syntax.FileOptions, thread *Thread, filename string, src interface{}, predeclared StringDict) (StringDict, error) { - // Parse, resolve, and compile a Starlark source file. - _, mod, err := SourceProgramOptions(opts, filename, src, predeclared.Has) - if err != nil { - return nil, err - } - - g, err := mod.Init(thread, predeclared) - g.Freeze() - return g, err -} - -// SourceProgram calls [SourceProgramOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func SourceProgram(filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error) { - return SourceProgramOptions(syntax.LegacyFileOptions(), filename, src, isPredeclared) -} - -// SourceProgramOptions produces a new program by parsing, resolving, -// and compiling a Starlark source file. -// On success, it returns the parsed file and the compiled program. -// The filename and src parameters are as for syntax.Parse. -// -// The isPredeclared predicate reports whether a name is -// a pre-declared identifier of the current module. -// Its typical value is predeclared.Has, -// where predeclared is a StringDict of pre-declared values. -func SourceProgramOptions(opts *syntax.FileOptions, filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error) { - f, err := opts.Parse(filename, src, 0) - if err != nil { - return nil, nil, err - } - prog, err := FileProgram(f, isPredeclared) - return f, prog, err -} - -// FileProgram produces a new program by resolving, -// and compiling the Starlark source file syntax tree. -// On success, it returns the compiled program. -// -// Resolving a syntax tree mutates it. -// Do not call FileProgram more than once on the same file. -// -// The isPredeclared predicate reports whether a name is -// a pre-declared identifier of the current module. -// Its typical value is predeclared.Has, -// where predeclared is a StringDict of pre-declared values. -func FileProgram(f *syntax.File, isPredeclared func(string) bool) (*Program, error) { - if err := resolve.File(f, isPredeclared, Universe.Has); err != nil { - return nil, err - } - - var pos syntax.Position - if len(f.Stmts) > 0 { - pos = syntax.Start(f.Stmts[0]) - } else { - pos = syntax.MakePosition(&f.Path, 1, 1) - } - - module := f.Module.(*resolve.Module) - compiled := compile.File(f.Options, f.Stmts, pos, "", module.Locals, module.Globals) - - return &Program{compiled}, nil -} - -// CompiledProgram produces a new program from the representation -// of a compiled program previously saved by Program.Write. -func CompiledProgram(in io.Reader) (*Program, error) { - data, err := io.ReadAll(in) - if err != nil { - return nil, err - } - compiled, err := compile.DecodeProgram(data) - if err != nil { - return nil, err - } - return &Program{compiled}, nil -} - -// Init creates a set of global variables for the program, -// executes the toplevel code of the specified program, -// and returns a new, unfrozen dictionary of the globals. -func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) { - toplevel := makeToplevelFunction(prog.compiled, predeclared) - - _, err := Call(thread, toplevel, nil, nil) - - // Convert the global environment to a map. - // We return a (partial) map even in case of error. - return toplevel.Globals(), err -} - -// ExecREPLChunk compiles and executes file f in the specified thread -// and global environment. This is a variant of ExecFile specialized to -// the needs of a REPL, in which a sequence of input chunks, each -// syntactically a File, manipulates the same set of module globals, -// which are not frozen after execution. -// -// This function is intended to support only go.starlark.net/repl. -// Its API stability is not guaranteed. -func ExecREPLChunk(f *syntax.File, thread *Thread, globals StringDict) error { - var predeclared StringDict - - // -- variant of FileProgram -- - - if err := resolve.REPLChunk(f, globals.Has, predeclared.Has, Universe.Has); err != nil { - return err - } - - var pos syntax.Position - if len(f.Stmts) > 0 { - pos = syntax.Start(f.Stmts[0]) - } else { - pos = syntax.MakePosition(&f.Path, 1, 1) - } - - module := f.Module.(*resolve.Module) - compiled := compile.File(f.Options, f.Stmts, pos, "", module.Locals, module.Globals) - prog := &Program{compiled} - - // -- variant of Program.Init -- - - toplevel := makeToplevelFunction(prog.compiled, predeclared) - - // Initialize module globals from parameter. - for i, id := range prog.compiled.Globals { - if v := globals[id.Name]; v != nil { - toplevel.module.globals[i] = v - } - } - - _, err := Call(thread, toplevel, nil, nil) - - // Reflect changes to globals back to parameter, even after an error. - for i, id := range prog.compiled.Globals { - if v := toplevel.module.globals[i]; v != nil { - globals[id.Name] = v - } - } - - return err -} - -func makeToplevelFunction(prog *compile.Program, predeclared StringDict) *Function { - // Create the Starlark value denoted by each program constant c. - constants := make([]Value, len(prog.Constants)) - for i, c := range prog.Constants { - var v Value - switch c := c.(type) { - case int64: - v = MakeInt64(c) - case *big.Int: - v = MakeBigInt(c) - case string: - v = String(c) - case compile.Bytes: - v = Bytes(c) - case float64: - v = Float(c) - default: - log.Panicf("unexpected constant %T: %v", c, c) - } - constants[i] = v - } - - return &Function{ - funcode: prog.Toplevel, - module: &module{ - program: prog, - predeclared: predeclared, - globals: make([]Value, len(prog.Globals)), - constants: constants, - }, - } -} - -// Eval calls [EvalOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func Eval(thread *Thread, filename string, src interface{}, env StringDict) (Value, error) { - return EvalOptions(syntax.LegacyFileOptions(), thread, filename, src, env) -} - -// EvalOptions parses, resolves, and evaluates an expression within the -// specified (predeclared) environment. -// -// Evaluation cannot mutate the environment dictionary itself, -// though it may modify variables reachable from the dictionary. -// -// The filename and src parameters are as for syntax.Parse. -// -// If EvalOptions fails during evaluation, it returns an *EvalError -// containing a backtrace. -func EvalOptions(opts *syntax.FileOptions, thread *Thread, filename string, src interface{}, env StringDict) (Value, error) { - expr, err := opts.ParseExpr(filename, src, 0) - if err != nil { - return nil, err - } - f, err := makeExprFunc(opts, expr, env) - if err != nil { - return nil, err - } - return Call(thread, f, nil, nil) -} - -// EvalExpr calls [EvalExprOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func EvalExpr(thread *Thread, expr syntax.Expr, env StringDict) (Value, error) { - return EvalExprOptions(syntax.LegacyFileOptions(), thread, expr, env) -} - -// EvalExprOptions resolves and evaluates an expression within the -// specified (predeclared) environment. -// Evaluating a comma-separated list of expressions yields a tuple value. -// -// Resolving an expression mutates it. -// Do not call EvalExprOptions more than once for the same expression. -// -// Evaluation cannot mutate the environment dictionary itself, -// though it may modify variables reachable from the dictionary. -// -// If EvalExprOptions fails during evaluation, it returns an *EvalError -// containing a backtrace. -func EvalExprOptions(opts *syntax.FileOptions, thread *Thread, expr syntax.Expr, env StringDict) (Value, error) { - fn, err := makeExprFunc(opts, expr, env) - if err != nil { - return nil, err - } - return Call(thread, fn, nil, nil) -} - -// ExprFunc calls [ExprFuncOptions] using [syntax.LegacyFileOptions]. -// Deprecated: relies on legacy global variables. -func ExprFunc(filename string, src interface{}, env StringDict) (*Function, error) { - return ExprFuncOptions(syntax.LegacyFileOptions(), filename, src, env) -} - -// ExprFunc returns a no-argument function -// that evaluates the expression whose source is src. -func ExprFuncOptions(options *syntax.FileOptions, filename string, src interface{}, env StringDict) (*Function, error) { - expr, err := options.ParseExpr(filename, src, 0) - if err != nil { - return nil, err - } - return makeExprFunc(options, expr, env) -} - -// makeExprFunc returns a no-argument function whose body is expr. -// The options must be consistent with those used when parsing expr. -func makeExprFunc(opts *syntax.FileOptions, expr syntax.Expr, env StringDict) (*Function, error) { - locals, err := resolve.ExprOptions(opts, expr, env.Has, Universe.Has) - if err != nil { - return nil, err - } - - return makeToplevelFunction(compile.Expr(opts, expr, "", locals), env), nil -} - -// The following functions are primitive operations of the byte code interpreter. - -// list += iterable -func listExtend(x *List, y Iterable) { - if ylist, ok := y.(*List); ok { - // fast path: list += list - x.elems = append(x.elems, ylist.elems...) - } else { - iter := y.Iterate() - defer iter.Done() - var z Value - for iter.Next(&z) { - x.elems = append(x.elems, z) - } - } -} - -// getAttr implements x.dot. -func getAttr(x Value, name string) (Value, error) { - hasAttr, ok := x.(HasAttrs) - if !ok { - return nil, fmt.Errorf("%s has no .%s field or method", x.Type(), name) - } - - var errmsg string - v, err := hasAttr.Attr(name) - if err == nil { - if v != nil { - return v, nil // success - } - // (nil, nil) => generic error - errmsg = fmt.Sprintf("%s has no .%s field or method", x.Type(), name) - } else if nsa, ok := err.(NoSuchAttrError); ok { - errmsg = string(nsa) - } else { - return nil, err // return error as is - } - - // add spelling hint - if n := spell.Nearest(name, hasAttr.AttrNames()); n != "" { - errmsg = fmt.Sprintf("%s (did you mean .%s?)", errmsg, n) - } - - return nil, fmt.Errorf("%s", errmsg) -} - -// setField implements x.name = y. -func setField(x Value, name string, y Value) error { - if x, ok := x.(HasSetField); ok { - err := x.SetField(name, y) - if _, ok := err.(NoSuchAttrError); ok { - // No such field: check spelling. - if n := spell.Nearest(name, x.AttrNames()); n != "" { - err = fmt.Errorf("%s (did you mean .%s?)", err, n) - } - } - return err - } - - return fmt.Errorf("can't assign to .%s field of %s", name, x.Type()) -} - -// getIndex implements x[y]. -func getIndex(x, y Value) (Value, error) { - switch x := x.(type) { - case Mapping: // dict - z, found, err := x.Get(y) - if err != nil { - return nil, err - } - if !found { - return nil, fmt.Errorf("key %v not in %s", y, x.Type()) - } - return z, nil - - case Indexable: // string, list, tuple - n := x.Len() - i, err := AsInt32(y) - if err != nil { - return nil, fmt.Errorf("%s index: %s", x.Type(), err) - } - origI := i - if i < 0 { - i += n - } - if i < 0 || i >= n { - return nil, outOfRange(origI, n, x) - } - return x.Index(i), nil - } - return nil, fmt.Errorf("unhandled index operation %s[%s]", x.Type(), y.Type()) -} - -func outOfRange(i, n int, x Value) error { - if n == 0 { - return fmt.Errorf("index %d out of range: empty %s", i, x.Type()) - } else { - return fmt.Errorf("%s index %d out of range [%d:%d]", x.Type(), i, -n, n-1) - } -} - -// setIndex implements x[y] = z. -func setIndex(x, y, z Value) error { - switch x := x.(type) { - case HasSetKey: - if err := x.SetKey(y, z); err != nil { - return err - } - - case HasSetIndex: - n := x.Len() - i, err := AsInt32(y) - if err != nil { - return err - } - origI := i - if i < 0 { - i += n - } - if i < 0 || i >= n { - return outOfRange(origI, n, x) - } - return x.SetIndex(i, z) - - default: - return fmt.Errorf("%s value does not support item assignment", x.Type()) - } - return nil -} - -// Unary applies a unary operator (+, -, ~, not) to its operand. -func Unary(op syntax.Token, x Value) (Value, error) { - // The NOT operator is not customizable. - if op == syntax.NOT { - return !x.Truth(), nil - } - - // Int, Float, and user-defined types - if x, ok := x.(HasUnary); ok { - // (nil, nil) => unhandled - y, err := x.Unary(op) - if y != nil || err != nil { - return y, err - } - } - - return nil, fmt.Errorf("unknown unary op: %s %s", op, x.Type()) -} - -// Binary applies a strict binary operator (not AND or OR) to its operands. -// For equality tests or ordered comparisons, use Compare instead. -func Binary(op syntax.Token, x, y Value) (Value, error) { - switch op { - case syntax.PLUS: - switch x := x.(type) { - case String: - if y, ok := y.(String); ok { - return x + y, nil - } - case Int: - switch y := y.(type) { - case Int: - return x.Add(y), nil - case Float: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - return xf + y, nil - } - case Float: - switch y := y.(type) { - case Float: - return x + y, nil - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - return x + yf, nil - } - case *List: - if y, ok := y.(*List); ok { - z := make([]Value, 0, x.Len()+y.Len()) - z = append(z, x.elems...) - z = append(z, y.elems...) - return NewList(z), nil - } - case Tuple: - if y, ok := y.(Tuple); ok { - z := make(Tuple, 0, len(x)+len(y)) - z = append(z, x...) - z = append(z, y...) - return z, nil - } - } - - case syntax.MINUS: - switch x := x.(type) { - case Int: - switch y := y.(type) { - case Int: - return x.Sub(y), nil - case Float: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - return xf - y, nil - } - case Float: - switch y := y.(type) { - case Float: - return x - y, nil - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - return x - yf, nil - } - case *Set: // difference - if y, ok := y.(*Set); ok { - iter := y.Iterate() - defer iter.Done() - return x.Difference(iter) - } - } - - case syntax.STAR: - switch x := x.(type) { - case Int: - switch y := y.(type) { - case Int: - return x.Mul(y), nil - case Float: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - return xf * y, nil - case String: - return stringRepeat(y, x) - case Bytes: - return bytesRepeat(y, x) - case *List: - elems, err := tupleRepeat(Tuple(y.elems), x) - if err != nil { - return nil, err - } - return NewList(elems), nil - case Tuple: - return tupleRepeat(y, x) - } - case Float: - switch y := y.(type) { - case Float: - return x * y, nil - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - return x * yf, nil - } - case String: - if y, ok := y.(Int); ok { - return stringRepeat(x, y) - } - case Bytes: - if y, ok := y.(Int); ok { - return bytesRepeat(x, y) - } - case *List: - if y, ok := y.(Int); ok { - elems, err := tupleRepeat(Tuple(x.elems), y) - if err != nil { - return nil, err - } - return NewList(elems), nil - } - case Tuple: - if y, ok := y.(Int); ok { - return tupleRepeat(x, y) - } - - } - - case syntax.SLASH: - switch x := x.(type) { - case Int: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - switch y := y.(type) { - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - if yf == 0.0 { - return nil, fmt.Errorf("floating-point division by zero") - } - return xf / yf, nil - case Float: - if y == 0.0 { - return nil, fmt.Errorf("floating-point division by zero") - } - return xf / y, nil - } - case Float: - switch y := y.(type) { - case Float: - if y == 0.0 { - return nil, fmt.Errorf("floating-point division by zero") - } - return x / y, nil - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - if yf == 0.0 { - return nil, fmt.Errorf("floating-point division by zero") - } - return x / yf, nil - } - } - - case syntax.SLASHSLASH: - switch x := x.(type) { - case Int: - switch y := y.(type) { - case Int: - if y.Sign() == 0 { - return nil, fmt.Errorf("floored division by zero") - } - return x.Div(y), nil - case Float: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - if y == 0.0 { - return nil, fmt.Errorf("floored division by zero") - } - return floor(xf / y), nil - } - case Float: - switch y := y.(type) { - case Float: - if y == 0.0 { - return nil, fmt.Errorf("floored division by zero") - } - return floor(x / y), nil - case Int: - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - if yf == 0.0 { - return nil, fmt.Errorf("floored division by zero") - } - return floor(x / yf), nil - } - } - - case syntax.PERCENT: - switch x := x.(type) { - case Int: - switch y := y.(type) { - case Int: - if y.Sign() == 0 { - return nil, fmt.Errorf("integer modulo by zero") - } - return x.Mod(y), nil - case Float: - xf, err := x.finiteFloat() - if err != nil { - return nil, err - } - if y == 0 { - return nil, fmt.Errorf("floating-point modulo by zero") - } - return xf.Mod(y), nil - } - case Float: - switch y := y.(type) { - case Float: - if y == 0.0 { - return nil, fmt.Errorf("floating-point modulo by zero") - } - return x.Mod(y), nil - case Int: - if y.Sign() == 0 { - return nil, fmt.Errorf("floating-point modulo by zero") - } - yf, err := y.finiteFloat() - if err != nil { - return nil, err - } - return x.Mod(yf), nil - } - case String: - return interpolate(string(x), y) - } - - case syntax.NOT_IN: - z, err := Binary(syntax.IN, x, y) - if err != nil { - return nil, err - } - return !z.Truth(), nil - - case syntax.IN: - switch y := y.(type) { - case *List: - for _, elem := range y.elems { - if eq, err := Equal(elem, x); err != nil { - return nil, err - } else if eq { - return True, nil - } - } - return False, nil - case Tuple: - for _, elem := range y { - if eq, err := Equal(elem, x); err != nil { - return nil, err - } else if eq { - return True, nil - } - } - return False, nil - case Mapping: // e.g. dict - // Ignore error from Get as we cannot distinguish true - // errors (value cycle, type error) from "key not found". - _, found, _ := y.Get(x) - return Bool(found), nil - case *Set: - ok, err := y.Has(x) - return Bool(ok), err - case String: - needle, ok := x.(String) - if !ok { - return nil, fmt.Errorf("'in ' requires string as left operand, not %s", x.Type()) - } - return Bool(strings.Contains(string(y), string(needle))), nil - case Bytes: - switch needle := x.(type) { - case Bytes: - return Bool(strings.Contains(string(y), string(needle))), nil - case Int: - var b byte - if err := AsInt(needle, &b); err != nil { - return nil, fmt.Errorf("int in bytes: %s", err) - } - return Bool(strings.IndexByte(string(y), b) >= 0), nil - default: - return nil, fmt.Errorf("'in bytes' requires bytes or int as left operand, not %s", x.Type()) - } - case rangeValue: - i, err := NumberToInt(x) - if err != nil { - return nil, fmt.Errorf("'in ' requires integer as left operand, not %s", x.Type()) - } - return Bool(y.contains(i)), nil - } - - case syntax.PIPE: - switch x := x.(type) { - case Int: - if y, ok := y.(Int); ok { - return x.Or(y), nil - } - - case *Dict: // union - if y, ok := y.(*Dict); ok { - return x.Union(y), nil - } - - case *Set: // union - if y, ok := y.(*Set); ok { - iter := Iterate(y) - defer iter.Done() - return x.Union(iter) - } - } - - case syntax.AMP: - switch x := x.(type) { - case Int: - if y, ok := y.(Int); ok { - return x.And(y), nil - } - case *Set: // intersection - if y, ok := y.(*Set); ok { - iter := y.Iterate() - defer iter.Done() - return x.Intersection(iter) - } - } - - case syntax.CIRCUMFLEX: - switch x := x.(type) { - case Int: - if y, ok := y.(Int); ok { - return x.Xor(y), nil - } - case *Set: // symmetric difference - if y, ok := y.(*Set); ok { - iter := y.Iterate() - defer iter.Done() - return x.SymmetricDifference(iter) - } - } - - case syntax.LTLT, syntax.GTGT: - if x, ok := x.(Int); ok { - y, err := AsInt32(y) - if err != nil { - return nil, err - } - if y < 0 { - return nil, fmt.Errorf("negative shift count: %v", y) - } - if op == syntax.LTLT { - if y >= 512 { - return nil, fmt.Errorf("shift count too large: %v", y) - } - return x.Lsh(uint(y)), nil - } else { - return x.Rsh(uint(y)), nil - } - } - - default: - // unknown operator - goto unknown - } - - // user-defined types - // (nil, nil) => unhandled - if x, ok := x.(HasBinary); ok { - z, err := x.Binary(op, y, Left) - if z != nil || err != nil { - return z, err - } - } - if y, ok := y.(HasBinary); ok { - z, err := y.Binary(op, x, Right) - if z != nil || err != nil { - return z, err - } - } - - // unsupported operand types -unknown: - return nil, fmt.Errorf("unknown binary op: %s %s %s", x.Type(), op, y.Type()) -} - -// It's always possible to overeat in small bites but we'll -// try to stop someone swallowing the world in one gulp. -const maxAlloc = 1 << 30 - -func tupleRepeat(elems Tuple, n Int) (Tuple, error) { - if len(elems) == 0 { - return nil, nil - } - i, err := AsInt32(n) - if err != nil { - return nil, fmt.Errorf("repeat count %s too large", n) - } - if i < 1 { - return nil, nil - } - // Inv: i > 0, len > 0 - sz := len(elems) * i - if sz < 0 || sz >= maxAlloc { // sz < 0 => overflow - // Don't print sz. - return nil, fmt.Errorf("excessive repeat (%d * %d elements)", len(elems), i) - } - res := make([]Value, sz) - // copy elems into res, doubling each time - x := copy(res, elems) - for x < len(res) { - copy(res[x:], res[:x]) - x *= 2 - } - return res, nil -} - -func bytesRepeat(b Bytes, n Int) (Bytes, error) { - res, err := stringRepeat(String(b), n) - return Bytes(res), err -} - -func stringRepeat(s String, n Int) (String, error) { - if s == "" { - return "", nil - } - i, err := AsInt32(n) - if err != nil { - return "", fmt.Errorf("repeat count %s too large", n) - } - if i < 1 { - return "", nil - } - // Inv: i > 0, len > 0 - sz := len(s) * i - if sz < 0 || sz >= maxAlloc { // sz < 0 => overflow - // Don't print sz. - return "", fmt.Errorf("excessive repeat (%d * %d elements)", len(s), i) - } - return String(strings.Repeat(string(s), i)), nil -} - -// Call calls the function fn with the specified positional and keyword arguments. -func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) { - c, ok := fn.(Callable) - if !ok { - return nil, fmt.Errorf("invalid call of non-function (%s)", fn.Type()) - } - - // Allocate and push a new frame. - var fr *frame - // Optimization: use slack portion of thread.stack - // slice as a freelist of empty frames. - if n := len(thread.stack); n < cap(thread.stack) { - fr = thread.stack[n : n+1][0] - } - if fr == nil { - fr = new(frame) - } - - if thread.stack == nil { - // one-time initialization of thread - if thread.maxSteps == 0 { - thread.maxSteps-- // (MaxUint64) - } - } - - thread.stack = append(thread.stack, fr) // push - - fr.callable = c - - thread.beginProfSpan() - - // Use defer to ensure that panics from built-ins - // pass through the interpreter without leaving - // it in a bad state. - defer func() { - thread.endProfSpan() - - // clear out any references - // TODO(adonovan): opt: zero fr.Locals and - // reuse it if it is large enough. - *fr = frame{} - - thread.stack = thread.stack[:len(thread.stack)-1] // pop - }() - - result, err := c.CallInternal(thread, args, kwargs) - - // Sanity check: nil is not a valid Starlark value. - if result == nil && err == nil { - err = fmt.Errorf("internal error: nil (not None) returned from %s", fn) - } - - // Always return an EvalError with an accurate frame. - if err != nil { - if _, ok := err.(*EvalError); !ok { - err = thread.evalError(err) - } - } - - return result, err -} - -func slice(x, lo, hi, step_ Value) (Value, error) { - sliceable, ok := x.(Sliceable) - if !ok { - return nil, fmt.Errorf("invalid slice operand %s", x.Type()) - } - - n := sliceable.Len() - step := 1 - if step_ != None { - var err error - step, err = AsInt32(step_) - if err != nil { - return nil, fmt.Errorf("invalid slice step: %s", err) - } - if step == 0 { - return nil, fmt.Errorf("zero is not a valid slice step") - } - } - - // TODO(adonovan): opt: preallocate result array. - - var start, end int - if step > 0 { - // positive stride - // default indices are [0:n]. - var err error - start, end, err = indices(lo, hi, n) - if err != nil { - return nil, err - } - - if end < start { - end = start // => empty result - } - } else { - // negative stride - // default indices are effectively [n-1:-1], though to - // get this effect using explicit indices requires - // [n-1:-1-n:-1] because of the treatment of -ve values. - start = n - 1 - if err := asIndex(lo, n, &start); err != nil { - return nil, fmt.Errorf("invalid start index: %s", err) - } - if start >= n { - start = n - 1 - } - - end = -1 - if err := asIndex(hi, n, &end); err != nil { - return nil, fmt.Errorf("invalid end index: %s", err) - } - if end < -1 { - end = -1 - } - - if start < end { - start = end // => empty result - } - } - - return sliceable.Slice(start, end, step), nil -} - -// From Hacker's Delight, section 2.8. -func signum64(x int64) int { return int(uint64(x>>63) | uint64(-x)>>63) } -func signum(x int) int { return signum64(int64(x)) } - -// indices converts start_ and end_ to indices in the range [0:len]. -// The start index defaults to 0 and the end index defaults to len. -// An index -len < i < 0 is treated like i+len. -// All other indices outside the range are clamped to the nearest value in the range. -// Beware: start may be greater than end. -// This function is suitable only for slices with positive strides. -func indices(start_, end_ Value, len int) (start, end int, err error) { - start = 0 - if err := asIndex(start_, len, &start); err != nil { - return 0, 0, fmt.Errorf("invalid start index: %s", err) - } - // Clamp to [0:len]. - if start < 0 { - start = 0 - } else if start > len { - start = len - } - - end = len - if err := asIndex(end_, len, &end); err != nil { - return 0, 0, fmt.Errorf("invalid end index: %s", err) - } - // Clamp to [0:len]. - if end < 0 { - end = 0 - } else if end > len { - end = len - } - - return start, end, nil -} - -// asIndex sets *result to the integer value of v, adding len to it -// if it is negative. If v is nil or None, *result is unchanged. -func asIndex(v Value, len int, result *int) error { - if v != nil && v != None { - var err error - *result, err = AsInt32(v) - if err != nil { - return err - } - if *result < 0 { - *result += len - } - } - return nil -} - -// setArgs sets the values of the formal parameters of function fn in -// based on the actual parameter values in args and kwargs. -func setArgs(locals []Value, fn *Function, args Tuple, kwargs []Tuple) error { - - // This is the general schema of a function: - // - // def f(p1, p2=dp2, p3=dp3, *args, k1, k2=dk2, k3, **kwargs) - // - // The p parameters are non-kwonly, and may be specified positionally. - // The k parameters are kwonly, and must be specified by name. - // The defaults tuple is (dp2, dp3, mandatory, dk2, mandatory). - // - // Arguments are processed as follows: - // - positional arguments are bound to a prefix of [p1, p2, p3]. - // - surplus positional arguments are bound to *args. - // - keyword arguments are bound to any of {p1, p2, p3, k1, k2, k3}; - // duplicate bindings are rejected. - // - surplus keyword arguments are bound to **kwargs. - // - defaults are bound to each parameter from p2 to k3 if no value was set. - // default values come from the tuple above. - // It is an error if the tuple entry for an unset parameter is 'mandatory'. - - // Nullary function? - if fn.NumParams() == 0 { - if nactual := len(args) + len(kwargs); nactual > 0 { - return fmt.Errorf("function %s accepts no arguments (%d given)", fn.Name(), nactual) - } - return nil - } - - cond := func(x bool, y, z interface{}) interface{} { - if x { - return y - } - return z - } - - // nparams is the number of ordinary parameters (sans *args and **kwargs). - nparams := fn.NumParams() - var kwdict *Dict - if fn.HasKwargs() { - nparams-- - kwdict = new(Dict) - locals[nparams] = kwdict - } - if fn.HasVarargs() { - nparams-- - } - - // nonkwonly is the number of non-kwonly parameters. - nonkwonly := nparams - fn.NumKwonlyParams() - - // Too many positional args? - n := len(args) - if len(args) > nonkwonly { - if !fn.HasVarargs() { - return fmt.Errorf("function %s accepts %s%d positional argument%s (%d given)", - fn.Name(), - cond(len(fn.defaults) > fn.NumKwonlyParams(), "at most ", ""), - nonkwonly, - cond(nonkwonly == 1, "", "s"), - len(args)) - } - n = nonkwonly - } - - // Bind positional arguments to non-kwonly parameters. - for i := 0; i < n; i++ { - locals[i] = args[i] - } - - // Bind surplus positional arguments to *args parameter. - if fn.HasVarargs() { - tuple := make(Tuple, len(args)-n) - for i := n; i < len(args); i++ { - tuple[i-n] = args[i] - } - locals[nparams] = tuple - } - - // Bind keyword arguments to parameters. - paramIdents := fn.funcode.Locals[:nparams] - for _, pair := range kwargs { - k, v := pair[0].(String), pair[1] - if i := findParam(paramIdents, string(k)); i >= 0 { - if locals[i] != nil { - return fmt.Errorf("function %s got multiple values for parameter %s", fn.Name(), k) - } - locals[i] = v - continue - } - if kwdict == nil { - return fmt.Errorf("function %s got an unexpected keyword argument %s", fn.Name(), k) - } - oldlen := kwdict.Len() - kwdict.SetKey(k, v) - if kwdict.Len() == oldlen { - return fmt.Errorf("function %s got multiple values for parameter %s", fn.Name(), k) - } - } - - // Are defaults required? - if n < nparams || fn.NumKwonlyParams() > 0 { - m := nparams - len(fn.defaults) // first default - - // Report errors for missing required arguments. - var missing []string - var i int - for i = n; i < m; i++ { - if locals[i] == nil { - missing = append(missing, paramIdents[i].Name) - } - } - - // Bind default values to parameters. - for ; i < nparams; i++ { - if locals[i] == nil { - dflt := fn.defaults[i-m] - if _, ok := dflt.(mandatory); ok { - missing = append(missing, paramIdents[i].Name) - continue - } - locals[i] = dflt - } - } - - if missing != nil { - return fmt.Errorf("function %s missing %d argument%s (%s)", - fn.Name(), len(missing), cond(len(missing) > 1, "s", ""), strings.Join(missing, ", ")) - } - } - return nil -} - -func findParam(params []compile.Binding, name string) int { - for i, param := range params { - if param.Name == name { - return i - } - } - return -1 -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string-interpolation -func interpolate(format string, x Value) (Value, error) { - buf := new(strings.Builder) - index := 0 - nargs := 1 - if tuple, ok := x.(Tuple); ok { - nargs = len(tuple) - } - for { - i := strings.IndexByte(format, '%') - if i < 0 { - buf.WriteString(format) - break - } - buf.WriteString(format[:i]) - format = format[i+1:] - - if format != "" && format[0] == '%' { - buf.WriteByte('%') - format = format[1:] - continue - } - - var arg Value - if format != "" && format[0] == '(' { - // keyword argument: %(name)s. - format = format[1:] - j := strings.IndexByte(format, ')') - if j < 0 { - return nil, fmt.Errorf("incomplete format key") - } - key := format[:j] - if dict, ok := x.(Mapping); !ok { - return nil, fmt.Errorf("format requires a mapping") - } else if v, found, _ := dict.Get(String(key)); found { - arg = v - } else { - return nil, fmt.Errorf("key not found: %s", key) - } - format = format[j+1:] - } else { - // positional argument: %s. - if index >= nargs { - return nil, fmt.Errorf("not enough arguments for format string") - } - if tuple, ok := x.(Tuple); ok { - arg = tuple[index] - } else { - arg = x - } - } - - // NOTE: Starlark does not support any of these optional Python features: - // - optional conversion flags: [#0- +], etc. - // - optional minimum field width (number or *). - // - optional precision (.123 or *) - // - optional length modifier - - // conversion type - if format == "" { - return nil, fmt.Errorf("incomplete format") - } - switch c := format[0]; c { - case 's', 'r': - if str, ok := AsString(arg); ok && c == 's' { - buf.WriteString(str) - } else { - writeValue(buf, arg, nil) - } - case 'd', 'i', 'o', 'x', 'X': - i, err := NumberToInt(arg) - if err != nil { - return nil, fmt.Errorf("%%%c format requires integer: %v", c, err) - } - switch c { - case 'd', 'i': - fmt.Fprintf(buf, "%d", i) - case 'o': - fmt.Fprintf(buf, "%o", i) - case 'x': - fmt.Fprintf(buf, "%x", i) - case 'X': - fmt.Fprintf(buf, "%X", i) - } - case 'e', 'f', 'g', 'E', 'F', 'G': - f, ok := AsFloat(arg) - if !ok { - return nil, fmt.Errorf("%%%c format requires float, not %s", c, arg.Type()) - } - Float(f).format(buf, c) - case 'c': - switch arg := arg.(type) { - case Int: - // chr(int) - r, err := AsInt32(arg) - if err != nil || r < 0 || r > unicode.MaxRune { - return nil, fmt.Errorf("%%c format requires a valid Unicode code point, got %s", arg) - } - buf.WriteRune(rune(r)) - case String: - r, size := utf8.DecodeRuneInString(string(arg)) - if size != len(arg) || len(arg) == 0 { - return nil, fmt.Errorf("%%c format requires a single-character string") - } - buf.WriteRune(r) - default: - return nil, fmt.Errorf("%%c format requires int or single-character string, not %s", arg.Type()) - } - case '%': - buf.WriteByte('%') - default: - return nil, fmt.Errorf("unknown conversion %%%c", c) - } - format = format[1:] - index++ - } - - if index < nargs && !is[Mapping](x) { - return nil, fmt.Errorf("too many arguments for format string") - } - - return String(buf.String()), nil -} - -func is[T any](x any) bool { - _, ok := x.(T) - return ok -} diff --git a/vendor/go.starlark.net/starlark/hashtable.go b/vendor/go.starlark.net/starlark/hashtable.go deleted file mode 100644 index 40f72bb63..000000000 --- a/vendor/go.starlark.net/starlark/hashtable.go +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2017 The Bazel 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 starlark - -import ( - "fmt" - "math/big" - _ "unsafe" // for go:linkname hack -) - -// hashtable is used to represent Starlark dict and set values. -// It is a hash table whose key/value entries form a doubly-linked list -// in the order the entries were inserted. -// -// Initialized instances of hashtable must not be copied. -type hashtable struct { - table []bucket // len is zero or a power of two - bucket0 [1]bucket // inline allocation for small maps. - len uint32 - itercount uint32 // number of active iterators (ignored if frozen) - head *entry // insertion order doubly-linked list; may be nil - tailLink **entry // address of nil link at end of list (perhaps &head) - frozen bool - - _ noCopy // triggers vet copylock check on this type. -} - -// noCopy is zero-sized type that triggers vet's copylock check. -// See https://github.com/golang/go/issues/8005#issuecomment-190753527. -type noCopy struct{} - -func (*noCopy) Lock() {} -func (*noCopy) Unlock() {} - -const bucketSize = 8 - -type bucket struct { - entries [bucketSize]entry - next *bucket // linked list of buckets -} - -type entry struct { - hash uint32 // nonzero => in use - key, value Value - next *entry // insertion order doubly-linked list; may be nil - prevLink **entry // address of link to this entry (perhaps &head) -} - -func (ht *hashtable) init(size int) { - if size < 0 { - panic("size < 0") - } - nb := 1 - for overloaded(size, nb) { - nb = nb << 1 - } - if nb < 2 { - ht.table = ht.bucket0[:1] - } else { - ht.table = make([]bucket, nb) - } - ht.tailLink = &ht.head -} - -func (ht *hashtable) freeze() { - if !ht.frozen { - ht.frozen = true - for e := ht.head; e != nil; e = e.next { - e.key.Freeze() - e.value.Freeze() - } - } -} - -func (ht *hashtable) insert(k, v Value) error { - if err := ht.checkMutable("insert into"); err != nil { - return err - } - if ht.table == nil { - ht.init(1) - } - h, err := k.Hash() - if err != nil { - return err - } - if h == 0 { - h = 1 // zero is reserved - } - -retry: - var insert *entry - - // Inspect each bucket in the bucket list. - p := &ht.table[h&(uint32(len(ht.table)-1))] - for { - for i := range p.entries { - e := &p.entries[i] - if e.hash != h { - if e.hash == 0 { - // Found empty entry; make a note. - insert = e - } - continue - } - if eq, err := Equal(k, e.key); err != nil { - return err // e.g. excessively recursive tuple - } else if !eq { - continue - } - // Key already present; update value. - e.value = v - return nil - } - if p.next == nil { - break - } - p = p.next - } - - // Key not found. p points to the last bucket. - - // Does the number of elements exceed the buckets' load factor? - if overloaded(int(ht.len), len(ht.table)) { - ht.grow() - goto retry - } - - if insert == nil { - // No space in existing buckets. Add a new one to the bucket list. - b := new(bucket) - p.next = b - insert = &b.entries[0] - } - - // Insert key/value pair. - insert.hash = h - insert.key = k - insert.value = v - - // Append entry to doubly-linked list. - insert.prevLink = ht.tailLink - *ht.tailLink = insert - ht.tailLink = &insert.next - - ht.len++ - - return nil -} - -func overloaded(elems, buckets int) bool { - const loadFactor = 6.5 // just a guess - return elems >= bucketSize && float64(elems) >= loadFactor*float64(buckets) -} - -func (ht *hashtable) grow() { - // Double the number of buckets and rehash. - // - // Even though this makes reentrant calls to ht.insert, - // calls Equals unnecessarily (since there can't be duplicate keys), - // and recomputes the hash unnecessarily, the gains from - // avoiding these steps were found to be too small to justify - // the extra logic: -2% on hashtable benchmark. - ht.table = make([]bucket, len(ht.table)<<1) - oldhead := ht.head - ht.head = nil - ht.tailLink = &ht.head - ht.len = 0 - for e := oldhead; e != nil; e = e.next { - ht.insert(e.key, e.value) - } - ht.bucket0[0] = bucket{} // clear out unused initial bucket -} - -func (ht *hashtable) lookup(k Value) (v Value, found bool, err error) { - h, err := k.Hash() - if err != nil { - return nil, false, err // unhashable - } - if h == 0 { - h = 1 // zero is reserved - } - if ht.table == nil { - return None, false, nil // empty - } - - // Inspect each bucket in the bucket list. - for p := &ht.table[h&(uint32(len(ht.table)-1))]; p != nil; p = p.next { - for i := range p.entries { - e := &p.entries[i] - if e.hash == h { - if eq, err := Equal(k, e.key); err != nil { - return nil, false, err // e.g. excessively recursive tuple - } else if eq { - return e.value, true, nil // found - } - } - } - } - return None, false, nil // not found -} - -// count returns the number of distinct elements of iter that are elements of ht. -func (ht *hashtable) count(iter Iterator) (int, error) { - if ht.table == nil { - return 0, nil // empty - } - - var k Value - count := 0 - - // Use a bitset per table entry to record seen elements of ht. - // Elements are identified by their bucket number and index within the bucket. - // Each bitset gets one word initially, but may grow. - storage := make([]big.Word, len(ht.table)) - bitsets := make([]big.Int, len(ht.table)) - for i := range bitsets { - bitsets[i].SetBits(storage[i : i+1 : i+1]) - } - for iter.Next(&k) && count != int(ht.len) { - h, err := k.Hash() - if err != nil { - return 0, err // unhashable - } - if h == 0 { - h = 1 // zero is reserved - } - - // Inspect each bucket in the bucket list. - bucketId := h & (uint32(len(ht.table) - 1)) - i := 0 - for p := &ht.table[bucketId]; p != nil; p = p.next { - for j := range p.entries { - e := &p.entries[j] - if e.hash == h { - if eq, err := Equal(k, e.key); err != nil { - return 0, err - } else if eq { - bitIndex := i<<3 + j - if bitsets[bucketId].Bit(bitIndex) == 0 { - bitsets[bucketId].SetBit(&bitsets[bucketId], bitIndex, 1) - count++ - } - } - } - } - i++ - } - } - - return count, nil -} - -// Items returns all the items in the map (as key/value pairs) in insertion order. -func (ht *hashtable) items() []Tuple { - items := make([]Tuple, 0, ht.len) - array := make([]Value, ht.len*2) // allocate a single backing array - for e := ht.head; e != nil; e = e.next { - pair := Tuple(array[:2:2]) - array = array[2:] - pair[0] = e.key - pair[1] = e.value - items = append(items, pair) - } - return items -} - -func (ht *hashtable) first() (Value, bool) { - if ht.head != nil { - return ht.head.key, true - } - return None, false -} - -func (ht *hashtable) keys() []Value { - keys := make([]Value, 0, ht.len) - for e := ht.head; e != nil; e = e.next { - keys = append(keys, e.key) - } - return keys -} - -func (ht *hashtable) delete(k Value) (v Value, found bool, err error) { - if err := ht.checkMutable("delete from"); err != nil { - return nil, false, err - } - if ht.table == nil { - return None, false, nil // empty - } - h, err := k.Hash() - if err != nil { - return nil, false, err // unhashable - } - if h == 0 { - h = 1 // zero is reserved - } - - // Inspect each bucket in the bucket list. - for p := &ht.table[h&(uint32(len(ht.table)-1))]; p != nil; p = p.next { - for i := range p.entries { - e := &p.entries[i] - if e.hash == h { - if eq, err := Equal(k, e.key); err != nil { - return nil, false, err - } else if eq { - // Remove e from doubly-linked list. - *e.prevLink = e.next - if e.next == nil { - ht.tailLink = e.prevLink // deletion of last entry - } else { - e.next.prevLink = e.prevLink - } - - v := e.value - *e = entry{} - ht.len-- - return v, true, nil // found - } - } - } - } - - // TODO(adonovan): opt: remove completely empty bucket from bucket list. - - return None, false, nil // not found -} - -// checkMutable reports an error if the hash table should not be mutated. -// verb+" dict" should describe the operation. -func (ht *hashtable) checkMutable(verb string) error { - if ht.frozen { - return fmt.Errorf("cannot %s frozen hash table", verb) - } - if ht.itercount > 0 { - return fmt.Errorf("cannot %s hash table during iteration", verb) - } - return nil -} - -func (ht *hashtable) clear() error { - if err := ht.checkMutable("clear"); err != nil { - return err - } - if ht.table != nil { - for i := range ht.table { - ht.table[i] = bucket{} - } - } - ht.head = nil - ht.tailLink = &ht.head - ht.len = 0 - return nil -} - -func (ht *hashtable) addAll(other *hashtable) error { - for e := other.head; e != nil; e = e.next { - if err := ht.insert(e.key, e.value); err != nil { - return err - } - } - return nil -} - -// dump is provided as an aid to debugging. -func (ht *hashtable) dump() { - fmt.Printf("hashtable %p len=%d head=%p tailLink=%p", - ht, ht.len, ht.head, ht.tailLink) - if ht.tailLink != nil { - fmt.Printf(" *tailLink=%p", *ht.tailLink) - } - fmt.Println() - for j := range ht.table { - fmt.Printf("bucket chain %d\n", j) - for p := &ht.table[j]; p != nil; p = p.next { - fmt.Printf("bucket %p\n", p) - for i := range p.entries { - e := &p.entries[i] - fmt.Printf("\tentry %d @ %p hash=%d key=%v value=%v\n", - i, e, e.hash, e.key, e.value) - fmt.Printf("\t\tnext=%p &next=%p prev=%p", - e.next, &e.next, e.prevLink) - if e.prevLink != nil { - fmt.Printf(" *prev=%p", *e.prevLink) - } - fmt.Println() - } - } - } -} - -func (ht *hashtable) iterate() *keyIterator { - if !ht.frozen { - ht.itercount++ - } - return &keyIterator{ht: ht, e: ht.head} -} - -type keyIterator struct { - ht *hashtable - e *entry -} - -func (it *keyIterator) Next(k *Value) bool { - if it.e != nil { - *k = it.e.key - it.e = it.e.next - return true - } - return false -} - -func (it *keyIterator) Done() { - if !it.ht.frozen { - it.ht.itercount-- - } -} - -// TODO(adonovan): use go1.19's maphash.String. - -// hashString computes the hash of s. -func hashString(s string) uint32 { - if len(s) >= 12 { - // Call the Go runtime's optimized hash implementation, - // which uses the AESENC instruction on amd64 machines. - return uint32(goStringHash(s, 0)) - } - return softHashString(s) -} - -//go:linkname goStringHash runtime.stringHash -func goStringHash(s string, seed uintptr) uintptr - -// softHashString computes the 32-bit FNV-1a hash of s in software. -func softHashString(s string) uint32 { - var h uint32 = 2166136261 - for i := 0; i < len(s); i++ { - h ^= uint32(s[i]) - h *= 16777619 - } - return h -} diff --git a/vendor/go.starlark.net/starlark/int.go b/vendor/go.starlark.net/starlark/int.go deleted file mode 100644 index 8f2b279c7..000000000 --- a/vendor/go.starlark.net/starlark/int.go +++ /dev/null @@ -1,459 +0,0 @@ -// Copyright 2017 The Bazel 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 starlark - -import ( - "fmt" - "math" - "math/big" - "reflect" - "strconv" - - "go.starlark.net/syntax" -) - -// Int is the type of a Starlark int. -// -// The zero value is not a legal value; use MakeInt(0). -type Int struct{ impl intImpl } - -// --- high-level accessors --- - -// MakeInt returns a Starlark int for the specified signed integer. -func MakeInt(x int) Int { return MakeInt64(int64(x)) } - -// MakeInt64 returns a Starlark int for the specified int64. -func MakeInt64(x int64) Int { - if math.MinInt32 <= x && x <= math.MaxInt32 { - return makeSmallInt(x) - } - return makeBigInt(big.NewInt(x)) -} - -// MakeUint returns a Starlark int for the specified unsigned integer. -func MakeUint(x uint) Int { return MakeUint64(uint64(x)) } - -// MakeUint64 returns a Starlark int for the specified uint64. -func MakeUint64(x uint64) Int { - if x <= math.MaxInt32 { - return makeSmallInt(int64(x)) - } - return makeBigInt(new(big.Int).SetUint64(x)) -} - -// MakeBigInt returns a Starlark int for the specified big.Int. -// The new Int value will contain a copy of x. The caller is safe to modify x. -func MakeBigInt(x *big.Int) Int { - if isSmall(x) { - return makeSmallInt(x.Int64()) - } - z := new(big.Int).Set(x) - return makeBigInt(z) -} - -func isSmall(x *big.Int) bool { - n := x.BitLen() - return n < 32 || n == 32 && x.Int64() == math.MinInt32 -} - -var ( - zero, one = makeSmallInt(0), makeSmallInt(1) - oneBig = big.NewInt(1) - - _ HasUnary = Int{} -) - -// Unary implements the operations +int, -int, and ~int. -func (i Int) Unary(op syntax.Token) (Value, error) { - switch op { - case syntax.MINUS: - return zero.Sub(i), nil - case syntax.PLUS: - return i, nil - case syntax.TILDE: - return i.Not(), nil - } - return nil, nil -} - -// Int64 returns the value as an int64. -// If it is not exactly representable the result is undefined and ok is false. -func (i Int) Int64() (_ int64, ok bool) { - iSmall, iBig := i.get() - if iBig != nil { - x, acc := bigintToInt64(iBig) - if acc != big.Exact { - return // inexact - } - return x, true - } - return iSmall, true -} - -// BigInt returns a new big.Int with the same value as the Int. -func (i Int) BigInt() *big.Int { - iSmall, iBig := i.get() - if iBig != nil { - return new(big.Int).Set(iBig) - } - return big.NewInt(iSmall) -} - -// bigInt returns the value as a big.Int. -// It differs from BigInt in that this method returns the actual -// reference and any modification will change the state of i. -func (i Int) bigInt() *big.Int { - iSmall, iBig := i.get() - if iBig != nil { - return iBig - } - return big.NewInt(iSmall) -} - -// Uint64 returns the value as a uint64. -// If it is not exactly representable the result is undefined and ok is false. -func (i Int) Uint64() (_ uint64, ok bool) { - iSmall, iBig := i.get() - if iBig != nil { - x, acc := bigintToUint64(iBig) - if acc != big.Exact { - return // inexact - } - return x, true - } - if iSmall < 0 { - return // inexact - } - return uint64(iSmall), true -} - -// The math/big API should provide this function. -func bigintToInt64(i *big.Int) (int64, big.Accuracy) { - sign := i.Sign() - if sign > 0 { - if i.Cmp(maxint64) > 0 { - return math.MaxInt64, big.Below - } - } else if sign < 0 { - if i.Cmp(minint64) < 0 { - return math.MinInt64, big.Above - } - } - return i.Int64(), big.Exact -} - -// The math/big API should provide this function. -func bigintToUint64(i *big.Int) (uint64, big.Accuracy) { - sign := i.Sign() - if sign > 0 { - if i.BitLen() > 64 { - return math.MaxUint64, big.Below - } - } else if sign < 0 { - return 0, big.Above - } - return i.Uint64(), big.Exact -} - -var ( - minint64 = new(big.Int).SetInt64(math.MinInt64) - maxint64 = new(big.Int).SetInt64(math.MaxInt64) -) - -func (i Int) Format(s fmt.State, ch rune) { - iSmall, iBig := i.get() - if iBig != nil { - iBig.Format(s, ch) - return - } - big.NewInt(iSmall).Format(s, ch) -} -func (i Int) String() string { - iSmall, iBig := i.get() - if iBig != nil { - return iBig.Text(10) - } - return strconv.FormatInt(iSmall, 10) -} -func (i Int) Type() string { return "int" } -func (i Int) Freeze() {} // immutable -func (i Int) Truth() Bool { return i.Sign() != 0 } -func (i Int) Hash() (uint32, error) { - iSmall, iBig := i.get() - var lo big.Word - if iBig != nil { - lo = iBig.Bits()[0] - } else { - lo = big.Word(iSmall) - } - return 12582917 * uint32(lo+3), nil -} - -// Cmp implements comparison of two Int values. -// Required by the TotallyOrdered interface. -func (i Int) Cmp(v Value, depth int) (int, error) { - j := v.(Int) - iSmall, iBig := i.get() - jSmall, jBig := j.get() - if iBig != nil || jBig != nil { - return i.bigInt().Cmp(j.bigInt()), nil - } - return signum64(iSmall - jSmall), nil // safe: int32 operands -} - -// Float returns the float value nearest i. -func (i Int) Float() Float { - iSmall, iBig := i.get() - if iBig != nil { - // Fast path for hardware int-to-float conversions. - if iBig.IsUint64() { - return Float(iBig.Uint64()) - } else if iBig.IsInt64() { - return Float(iBig.Int64()) - } else { - // Fast path for very big ints. - const maxFiniteLen = 1023 + 1 // max exponent value + implicit mantissa bit - if iBig.BitLen() > maxFiniteLen { - return Float(math.Inf(iBig.Sign())) - } - } - - f, _ := new(big.Float).SetInt(iBig).Float64() - return Float(f) - } - return Float(iSmall) -} - -// finiteFloat returns the finite float value nearest i, -// or an error if the magnitude is too large. -func (i Int) finiteFloat() (Float, error) { - f := i.Float() - if math.IsInf(float64(f), 0) { - return 0, fmt.Errorf("int too large to convert to float") - } - return f, nil -} - -func (x Int) Sign() int { - xSmall, xBig := x.get() - if xBig != nil { - return xBig.Sign() - } - return signum64(xSmall) -} - -func (x Int) Add(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).Add(x.bigInt(), y.bigInt())) - } - return MakeInt64(xSmall + ySmall) -} -func (x Int) Sub(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).Sub(x.bigInt(), y.bigInt())) - } - return MakeInt64(xSmall - ySmall) -} -func (x Int) Mul(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).Mul(x.bigInt(), y.bigInt())) - } - return MakeInt64(xSmall * ySmall) -} -func (x Int) Or(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).Or(x.bigInt(), y.bigInt())) - } - return makeSmallInt(xSmall | ySmall) -} -func (x Int) And(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).And(x.bigInt(), y.bigInt())) - } - return makeSmallInt(xSmall & ySmall) -} -func (x Int) Xor(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - return MakeBigInt(new(big.Int).Xor(x.bigInt(), y.bigInt())) - } - return makeSmallInt(xSmall ^ ySmall) -} -func (x Int) Not() Int { - xSmall, xBig := x.get() - if xBig != nil { - return MakeBigInt(new(big.Int).Not(xBig)) - } - return makeSmallInt(^xSmall) -} -func (x Int) Lsh(y uint) Int { return MakeBigInt(new(big.Int).Lsh(x.bigInt(), y)) } -func (x Int) Rsh(y uint) Int { return MakeBigInt(new(big.Int).Rsh(x.bigInt(), y)) } - -// Precondition: y is nonzero. -func (x Int) Div(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - // http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html - if xBig != nil || yBig != nil { - xb, yb := x.bigInt(), y.bigInt() - - var quo, rem big.Int - quo.QuoRem(xb, yb, &rem) - if (xb.Sign() < 0) != (yb.Sign() < 0) && rem.Sign() != 0 { - quo.Sub(&quo, oneBig) - } - return MakeBigInt(&quo) - } - quo := xSmall / ySmall - rem := xSmall % ySmall - if (xSmall < 0) != (ySmall < 0) && rem != 0 { - quo -= 1 - } - return MakeInt64(quo) -} - -// Precondition: y is nonzero. -func (x Int) Mod(y Int) Int { - xSmall, xBig := x.get() - ySmall, yBig := y.get() - if xBig != nil || yBig != nil { - xb, yb := x.bigInt(), y.bigInt() - - var quo, rem big.Int - quo.QuoRem(xb, yb, &rem) - if (xb.Sign() < 0) != (yb.Sign() < 0) && rem.Sign() != 0 { - rem.Add(&rem, yb) - } - return MakeBigInt(&rem) - } - rem := xSmall % ySmall - if (xSmall < 0) != (ySmall < 0) && rem != 0 { - rem += ySmall - } - return makeSmallInt(rem) -} - -func (i Int) rational() *big.Rat { - iSmall, iBig := i.get() - if iBig != nil { - return new(big.Rat).SetInt(iBig) - } - return new(big.Rat).SetInt64(iSmall) -} - -// AsInt32 returns the value of x if is representable as an int32. -func AsInt32(x Value) (int, error) { - i, ok := x.(Int) - if !ok { - return 0, fmt.Errorf("got %s, want int", x.Type()) - } - iSmall, iBig := i.get() - if iBig != nil { - return 0, fmt.Errorf("%s out of range", i) - } - return int(iSmall), nil -} - -// AsInt sets *ptr to the value of Starlark int x, if it is exactly representable, -// otherwise it returns an error. -// The type of ptr must be one of the pointer types *int, *int8, *int16, *int32, or *int64, -// or one of their unsigned counterparts including *uintptr. -func AsInt(x Value, ptr interface{}) error { - xint, ok := x.(Int) - if !ok { - return fmt.Errorf("got %s, want int", x.Type()) - } - - bits := reflect.TypeOf(ptr).Elem().Size() * 8 - switch ptr.(type) { - case *int, *int8, *int16, *int32, *int64: - i, ok := xint.Int64() - if !ok || bits < 64 && !(-1<<(bits-1) <= i && i < 1<<(bits-1)) { - return fmt.Errorf("%s out of range (want value in signed %d-bit range)", xint, bits) - } - switch ptr := ptr.(type) { - case *int: - *ptr = int(i) - case *int8: - *ptr = int8(i) - case *int16: - *ptr = int16(i) - case *int32: - *ptr = int32(i) - case *int64: - *ptr = int64(i) - } - - case *uint, *uint8, *uint16, *uint32, *uint64, *uintptr: - i, ok := xint.Uint64() - if !ok || bits < 64 && i >= 1< value is not representable as int32 -} - -// --- low-level accessors --- - -// get returns the small and big components of the Int. -// small is defined only if big is nil. -// small is sign-extended to 64 bits for ease of subsequent arithmetic. -func (i Int) get() (small int64, big *big.Int) { - return i.impl.small_, i.impl.big_ -} - -// Precondition: math.MinInt32 <= x && x <= math.MaxInt32 -func makeSmallInt(x int64) Int { - return Int{intImpl{small_: x}} -} - -// Precondition: x cannot be represented as int32. -func makeBigInt(x *big.Int) Int { - return Int{intImpl{big_: x}} -} diff --git a/vendor/go.starlark.net/starlark/int_posix64.go b/vendor/go.starlark.net/starlark/int_posix64.go deleted file mode 100644 index 70c949efc..000000000 --- a/vendor/go.starlark.net/starlark/int_posix64.go +++ /dev/null @@ -1,89 +0,0 @@ -//go:build (linux || darwin || dragonfly || freebsd || netbsd || solaris) && (amd64 || arm64 || mips64x || ppc64 || ppc64le || loong64 || s390x) - -package starlark - -// This file defines an optimized Int implementation for 64-bit machines -// running POSIX. It reserves a 4GB portion of the address space using -// mmap and represents int32 values as addresses within that range. This -// disambiguates int32 values from *big.Int pointers, letting all Int -// values be represented as an unsafe.Pointer, so that Int-to-Value -// interface conversion need not allocate. - -// Although iOS (which, like macOS, appears as darwin/arm64) is -// POSIX-compliant, it limits each process to about 700MB of virtual -// address space, which defeats the optimization. Similarly, -// OpenBSD's default ulimit for virtual memory is a measly GB or so. -// On both those platforms the attempted optimization will fail and -// fall back to the slow implementation. - -// An alternative approach to this optimization would be to embed the -// int32 values in pointers using odd values, which can be distinguished -// from (even) *big.Int pointers. However, the Go runtime does not allow -// user programs to manufacture pointers to arbitrary locations such as -// within the zero page, or non-span, non-mmap, non-stack locations, -// and it may panic if it encounters them; see Issue #382. - -import ( - "log" - "math" - "math/big" - "unsafe" - - "golang.org/x/sys/unix" -) - -// intImpl represents a union of (int32, *big.Int) in a single pointer, -// so that Int-to-Value conversions need not allocate. -// -// The pointer is either a *big.Int, if the value is big, or a pointer into a -// reserved portion of the address space (smallints), if the value is small -// and the address space allocation succeeded. -// -// See int_generic.go for the basic representation concepts. -type intImpl unsafe.Pointer - -// get returns the (small, big) arms of the union. -func (i Int) get() (int64, *big.Int) { - if smallints == 0 { - // optimization disabled - if x := (*big.Int)(i.impl); isSmall(x) { - return x.Int64(), nil - } else { - return 0, x - } - } - - if ptr := uintptr(i.impl); ptr >= smallints && ptr < smallints+1<<32 { - return math.MinInt32 + int64(ptr-smallints), nil - } - return 0, (*big.Int)(i.impl) -} - -// Precondition: math.MinInt32 <= x && x <= math.MaxInt32 -func makeSmallInt(x int64) Int { - if smallints == 0 { - // optimization disabled - return Int{intImpl(big.NewInt(x))} - } - - return Int{intImpl(uintptr(x-math.MinInt32) + smallints)} -} - -// Precondition: x cannot be represented as int32. -func makeBigInt(x *big.Int) Int { return Int{intImpl(x)} } - -// smallints is the base address of a 2^32 byte memory region. -// Pointers to addresses in this region represent int32 values. -// We assume smallints is not at the very top of the address space. -// -// Zero means the optimization is disabled and all Ints allocate a big.Int. -var smallints = reserveAddresses(1 << 32) - -func reserveAddresses(len int) uintptr { - b, err := unix.Mmap(-1, 0, len, unix.PROT_READ, unix.MAP_PRIVATE|unix.MAP_ANON) - if err != nil { - log.Printf("Starlark failed to allocate 4GB address space: %v. Integer performance may suffer.", err) - return 0 // optimization disabled - } - return uintptr(unsafe.Pointer(&b[0])) -} diff --git a/vendor/go.starlark.net/starlark/interp.go b/vendor/go.starlark.net/starlark/interp.go deleted file mode 100644 index d29e52530..000000000 --- a/vendor/go.starlark.net/starlark/interp.go +++ /dev/null @@ -1,704 +0,0 @@ -package starlark - -// This file defines the bytecode interpreter. - -import ( - "fmt" - "os" - "sync/atomic" - "unsafe" - - "go.starlark.net/internal/compile" - "go.starlark.net/internal/spell" - "go.starlark.net/syntax" -) - -const vmdebug = false // TODO(adonovan): use a bitfield of specific kinds of error. - -// TODO(adonovan): -// - optimize position table. -// - opt: record MaxIterStack during compilation and preallocate the stack. - -func (fn *Function) CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) { - // Postcondition: args is not mutated. This is stricter than required by Callable, - // but allows CALL to avoid a copy. - - f := fn.funcode - if !f.Prog.Recursion { - // detect recursion - for _, fr := range thread.stack[:len(thread.stack)-1] { - // We look for the same function code, - // not function value, otherwise the user could - // defeat the check by writing the Y combinator. - if frfn, ok := fr.Callable().(*Function); ok && frfn.funcode == f { - return nil, fmt.Errorf("function %s called recursively", fn.Name()) - } - } - } - - fr := thread.frameAt(0) - - // Allocate space for stack and locals. - // Logically these do not escape from this frame - // (See https://github.com/golang/go/issues/20533.) - // - // This heap allocation looks expensive, but I was unable to get - // more than 1% real time improvement in a large alloc-heavy - // benchmark (in which this alloc was 8% of alloc-bytes) - // by allocating space for 8 Values in each frame, or - // by allocating stack by slicing an array held by the Thread - // that is expanded in chunks of min(k, nspace), for k=256 or 1024. - nlocals := len(f.Locals) - nspace := nlocals + f.MaxStack - space := make([]Value, nspace) - locals := space[:nlocals:nlocals] // local variables, starting with parameters - stack := space[nlocals:] // operand stack - - // Digest arguments and set parameters. - err := setArgs(locals, fn, args, kwargs) - if err != nil { - return nil, thread.evalError(err) - } - - fr.locals = locals - - if vmdebug { - fmt.Printf("Entering %s @ %s\n", f.Name, f.Position(0)) - fmt.Printf("%d stack, %d locals\n", len(stack), len(locals)) - defer fmt.Println("Leaving ", f.Name) - } - - // Spill indicated locals to cells. - // Each cell is a separate alloc to avoid spurious liveness. - for _, index := range f.Cells { - locals[index] = &cell{locals[index]} - } - - // TODO(adonovan): add static check that beneath this point - // - there is exactly one return statement - // - there is no redefinition of 'err'. - - var iterstack []Iterator // stack of active iterators - - // Use defer so that application panics can pass through - // interpreter without leaving thread in a bad state. - defer func() { - // ITERPOP the rest of the iterator stack. - for _, iter := range iterstack { - iter.Done() - } - - fr.locals = nil - }() - - sp := 0 - var pc uint32 - var result Value - code := f.Code -loop: - for { - thread.Steps++ - if thread.Steps >= thread.maxSteps { - if thread.OnMaxSteps != nil { - thread.OnMaxSteps(thread) - } else { - thread.Cancel("too many steps") - } - } - if reason := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&thread.cancelReason))); reason != nil { - err = fmt.Errorf("Starlark computation cancelled: %s", *(*string)(reason)) - break loop - } - - fr.pc = pc - - op := compile.Opcode(code[pc]) - pc++ - var arg uint32 - if op >= compile.OpcodeArgMin { - // TODO(adonovan): opt: profile this. - // Perhaps compiling big endian would be less work to decode? - for s := uint(0); ; s += 7 { - b := code[pc] - pc++ - arg |= uint32(b&0x7f) << s - if b < 0x80 { - break - } - } - } - if vmdebug { - fmt.Fprintln(os.Stderr, stack[:sp]) // very verbose! - compile.PrintOp(f, fr.pc, op, arg) - } - - switch op { - case compile.NOP: - // nop - - case compile.DUP: - stack[sp] = stack[sp-1] - sp++ - - case compile.DUP2: - stack[sp] = stack[sp-2] - stack[sp+1] = stack[sp-1] - sp += 2 - - case compile.POP: - sp-- - - case compile.EXCH: - stack[sp-2], stack[sp-1] = stack[sp-1], stack[sp-2] - - case compile.EQL, compile.NEQ, compile.GT, compile.LT, compile.LE, compile.GE: - op := syntax.Token(op-compile.EQL) + syntax.EQL - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - ok, err2 := Compare(op, x, y) - if err2 != nil { - err = err2 - break loop - } - stack[sp] = Bool(ok) - sp++ - - case compile.PLUS, - compile.MINUS, - compile.STAR, - compile.SLASH, - compile.SLASHSLASH, - compile.PERCENT, - compile.AMP, - compile.PIPE, - compile.CIRCUMFLEX, - compile.LTLT, - compile.GTGT, - compile.IN: - binop := syntax.Token(op-compile.PLUS) + syntax.PLUS - if op == compile.IN { - binop = syntax.IN // IN token is out of order - } - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - z, err2 := Binary(binop, x, y) - if err2 != nil { - err = err2 - break loop - } - stack[sp] = z - sp++ - - case compile.UPLUS, compile.UMINUS, compile.TILDE: - var unop syntax.Token - if op == compile.TILDE { - unop = syntax.TILDE - } else { - unop = syntax.Token(op-compile.UPLUS) + syntax.PLUS - } - x := stack[sp-1] - y, err2 := Unary(unop, x) - if err2 != nil { - err = err2 - break loop - } - stack[sp-1] = y - - case compile.INPLACE_ADD: - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - - // It's possible that y is not Iterable but - // nonetheless defines x+y, in which case we - // should fall back to the general case. - var z Value - if xlist, ok := x.(*List); ok { - if yiter, ok := y.(Iterable); ok { - if err = xlist.checkMutable("apply += to"); err != nil { - break loop - } - listExtend(xlist, yiter) - z = xlist - } - } - if z == nil { - z, err = Binary(syntax.PLUS, x, y) - if err != nil { - break loop - } - } - - stack[sp] = z - sp++ - - case compile.INPLACE_PIPE: - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - - // It's possible that y is not Dict but - // nonetheless defines x|y, in which case we - // should fall back to the general case. - var z Value - if xdict, ok := x.(*Dict); ok { - if ydict, ok := y.(*Dict); ok { - if err = xdict.ht.checkMutable("apply |= to"); err != nil { - break loop - } - xdict.ht.addAll(&ydict.ht) // can't fail - z = xdict - } - } - if z == nil { - z, err = Binary(syntax.PIPE, x, y) - if err != nil { - break loop - } - } - - stack[sp] = z - sp++ - - case compile.NONE: - stack[sp] = None - sp++ - - case compile.TRUE: - stack[sp] = True - sp++ - - case compile.FALSE: - stack[sp] = False - sp++ - - case compile.MANDATORY: - stack[sp] = mandatory{} - sp++ - - case compile.JMP: - pc = arg - - case compile.CALL, compile.CALL_VAR, compile.CALL_KW, compile.CALL_VAR_KW: - var kwargs Value - if op == compile.CALL_KW || op == compile.CALL_VAR_KW { - kwargs = stack[sp-1] - sp-- - } - - var args Value - if op == compile.CALL_VAR || op == compile.CALL_VAR_KW { - args = stack[sp-1] - sp-- - } - - // named args (pairs) - var kvpairs []Tuple - if nkvpairs := int(arg & 0xff); nkvpairs > 0 { - kvpairs = make([]Tuple, 0, nkvpairs) - kvpairsAlloc := make(Tuple, 2*nkvpairs) // allocate a single backing array - sp -= 2 * nkvpairs - for i := 0; i < nkvpairs; i++ { - pair := kvpairsAlloc[:2:2] - kvpairsAlloc = kvpairsAlloc[2:] - pair[0] = stack[sp+2*i] // name - pair[1] = stack[sp+2*i+1] // value - kvpairs = append(kvpairs, pair) - } - } - if kwargs != nil { - // Add key/value items from **kwargs dictionary. - dict, ok := kwargs.(IterableMapping) - if !ok { - err = fmt.Errorf("argument after ** must be a mapping, not %s", kwargs.Type()) - break loop - } - items := dict.Items() - for _, item := range items { - if _, ok := item[0].(String); !ok { - err = fmt.Errorf("keywords must be strings, not %s", item[0].Type()) - break loop - } - } - if len(kvpairs) == 0 { - kvpairs = items - } else { - kvpairs = append(kvpairs, items...) - } - } - - // positional args - var positional Tuple - if npos := int(arg >> 8); npos > 0 { - positional = stack[sp-npos : sp] - sp -= npos - - // Copy positional arguments into a new array, - // unless the callee is another Starlark function, - // in which case it can be trusted not to mutate them. - if _, ok := stack[sp-1].(*Function); !ok || args != nil { - positional = append(Tuple(nil), positional...) - } - } - if args != nil { - // Add elements from *args sequence. - iter := Iterate(args) - if iter == nil { - err = fmt.Errorf("argument after * must be iterable, not %s", args.Type()) - break loop - } - var elem Value - for iter.Next(&elem) { - positional = append(positional, elem) - } - iter.Done() - } - - function := stack[sp-1] - - if vmdebug { - fmt.Printf("VM call %s args=%s kwargs=%s @%s\n", - function, positional, kvpairs, f.Position(fr.pc)) - } - - thread.endProfSpan() - z, err2 := Call(thread, function, positional, kvpairs) - thread.beginProfSpan() - if err2 != nil { - err = err2 - break loop - } - if vmdebug { - fmt.Printf("Resuming %s @ %s\n", f.Name, f.Position(0)) - } - stack[sp-1] = z - - case compile.ITERPUSH: - x := stack[sp-1] - sp-- - iter := Iterate(x) - if iter == nil { - err = fmt.Errorf("%s value is not iterable", x.Type()) - break loop - } - iterstack = append(iterstack, iter) - - case compile.ITERJMP: - iter := iterstack[len(iterstack)-1] - if iter.Next(&stack[sp]) { - sp++ - } else { - pc = arg - } - - case compile.ITERPOP: - n := len(iterstack) - 1 - iterstack[n].Done() - iterstack = iterstack[:n] - - case compile.NOT: - stack[sp-1] = !stack[sp-1].Truth() - - case compile.RETURN: - result = stack[sp-1] - break loop - - case compile.SETINDEX: - z := stack[sp-1] - y := stack[sp-2] - x := stack[sp-3] - sp -= 3 - err = setIndex(x, y, z) - if err != nil { - break loop - } - - case compile.INDEX: - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - z, err2 := getIndex(x, y) - if err2 != nil { - err = err2 - break loop - } - stack[sp] = z - sp++ - - case compile.ATTR: - x := stack[sp-1] - name := f.Prog.Names[arg] - y, err2 := getAttr(x, name) - if err2 != nil { - err = err2 - break loop - } - stack[sp-1] = y - - case compile.SETFIELD: - y := stack[sp-1] - x := stack[sp-2] - sp -= 2 - name := f.Prog.Names[arg] - if err2 := setField(x, name, y); err2 != nil { - err = err2 - break loop - } - - case compile.MAKEDICT: - stack[sp] = new(Dict) - sp++ - - case compile.SETDICT, compile.SETDICTUNIQ: - dict := stack[sp-3].(*Dict) - k := stack[sp-2] - v := stack[sp-1] - sp -= 3 - oldlen := dict.Len() - if err2 := dict.SetKey(k, v); err2 != nil { - err = err2 - break loop - } - if op == compile.SETDICTUNIQ && dict.Len() == oldlen { - err = fmt.Errorf("duplicate key: %v", k) - break loop - } - - case compile.APPEND: - elem := stack[sp-1] - list := stack[sp-2].(*List) - sp -= 2 - list.elems = append(list.elems, elem) - - case compile.SLICE: - x := stack[sp-4] - lo := stack[sp-3] - hi := stack[sp-2] - step := stack[sp-1] - sp -= 4 - res, err2 := slice(x, lo, hi, step) - if err2 != nil { - err = err2 - break loop - } - stack[sp] = res - sp++ - - case compile.UNPACK: - n := int(arg) - iterable := stack[sp-1] - sp-- - iter := Iterate(iterable) - if iter == nil { - err = fmt.Errorf("got %s in sequence assignment", iterable.Type()) - break loop - } - i := 0 - sp += n - for i < n && iter.Next(&stack[sp-1-i]) { - i++ - } - var dummy Value - if iter.Next(&dummy) { - // NB: Len may return -1 here in obscure cases. - err = fmt.Errorf("too many values to unpack (got %d, want %d)", Len(iterable), n) - break loop - } - iter.Done() - if i < n { - err = fmt.Errorf("too few values to unpack (got %d, want %d)", i, n) - break loop - } - - case compile.CJMP: - if stack[sp-1].Truth() { - pc = arg - } - sp-- - - case compile.CONSTANT: - stack[sp] = fn.module.constants[arg] - sp++ - - case compile.MAKETUPLE: - n := int(arg) - tuple := make(Tuple, n) - sp -= n - copy(tuple, stack[sp:]) - stack[sp] = tuple - sp++ - - case compile.MAKELIST: - n := int(arg) - elems := make([]Value, n) - sp -= n - copy(elems, stack[sp:]) - stack[sp] = NewList(elems) - sp++ - - case compile.MAKEFUNC: - funcode := f.Prog.Functions[arg] - tuple := stack[sp-1].(Tuple) - n := len(tuple) - len(funcode.Freevars) - defaults := tuple[:n:n] - freevars := tuple[n:] - stack[sp-1] = &Function{ - funcode: funcode, - module: fn.module, - defaults: defaults, - freevars: freevars, - } - - case compile.LOAD: - n := int(arg) - module := string(stack[sp-1].(String)) - sp-- - - if thread.Load == nil { - err = fmt.Errorf("load not implemented by this application") - break loop - } - - thread.endProfSpan() - dict, err2 := thread.Load(thread, module) - thread.beginProfSpan() - if err2 != nil { - err = wrappedError{ - msg: fmt.Sprintf("cannot load %s: %v", module, err2), - cause: err2, - } - break loop - } - - for i := 0; i < n; i++ { - from := string(stack[sp-1-i].(String)) - v, ok := dict[from] - if !ok { - err = fmt.Errorf("load: name %s not found in module %s", from, module) - if n := spell.Nearest(from, dict.Keys()); n != "" { - err = fmt.Errorf("%s (did you mean %s?)", err, n) - } - break loop - } - stack[sp-1-i] = v - } - - case compile.SETLOCAL: - locals[arg] = stack[sp-1] - sp-- - - case compile.SETLOCALCELL: - locals[arg].(*cell).v = stack[sp-1] - sp-- - - case compile.SETGLOBAL: - fn.module.globals[arg] = stack[sp-1] - sp-- - - case compile.LOCAL: - x := locals[arg] - if x == nil { - err = fmt.Errorf("local variable %s referenced before assignment", f.Locals[arg].Name) - break loop - } - stack[sp] = x - sp++ - - case compile.FREE: - stack[sp] = fn.freevars[arg] - sp++ - - case compile.LOCALCELL: - v := locals[arg].(*cell).v - if v == nil { - err = fmt.Errorf("local variable %s referenced before assignment", f.Locals[arg].Name) - break loop - } - stack[sp] = v - sp++ - - case compile.FREECELL: - v := fn.freevars[arg].(*cell).v - if v == nil { - err = fmt.Errorf("local variable %s referenced before assignment", f.Freevars[arg].Name) - break loop - } - stack[sp] = v - sp++ - - case compile.GLOBAL: - x := fn.module.globals[arg] - if x == nil { - err = fmt.Errorf("global variable %s referenced before assignment", f.Prog.Globals[arg].Name) - break loop - } - stack[sp] = x - sp++ - - case compile.PREDECLARED: - name := f.Prog.Names[arg] - x := fn.module.predeclared[name] - if x == nil { - err = fmt.Errorf("internal error: predeclared variable %s is uninitialized", name) - break loop - } - stack[sp] = x - sp++ - - case compile.UNIVERSAL: - stack[sp] = Universe[f.Prog.Names[arg]] - sp++ - - default: - err = fmt.Errorf("unimplemented: %s", op) - break loop - } - } - // (deferred cleanup runs here) - return result, err -} - -type wrappedError struct { - msg string - cause error -} - -func (e wrappedError) Error() string { - return e.msg -} - -// Implements the xerrors.Wrapper interface -// https://godoc.org/golang.org/x/xerrors#Wrapper -func (e wrappedError) Unwrap() error { - return e.cause -} - -// mandatory is a sentinel value used in a function's defaults tuple -// to indicate that a (keyword-only) parameter is mandatory. -type mandatory struct{} - -func (mandatory) String() string { return "mandatory" } -func (mandatory) Type() string { return "mandatory" } -func (mandatory) Freeze() {} // immutable -func (mandatory) Truth() Bool { return False } -func (mandatory) Hash() (uint32, error) { return 0, nil } - -// A cell is a box containing a Value. -// Local variables marked as cells hold their value indirectly -// so that they may be shared by outer and inner nested functions. -// Cells are always accessed using indirect {FREE,LOCAL,SETLOCAL}CELL instructions. -// The FreeVars tuple contains only cells. -// The FREE instruction always yields a cell. -type cell struct{ v Value } - -func (c *cell) String() string { return "cell" } -func (c *cell) Type() string { return "cell" } -func (c *cell) Freeze() { - if c.v != nil { - c.v.Freeze() - } -} -func (c *cell) Truth() Bool { panic("unreachable") } -func (c *cell) Hash() (uint32, error) { panic("unreachable") } diff --git a/vendor/go.starlark.net/starlark/library.go b/vendor/go.starlark.net/starlark/library.go deleted file mode 100644 index 4e73a40ba..000000000 --- a/vendor/go.starlark.net/starlark/library.go +++ /dev/null @@ -1,2455 +0,0 @@ -// Copyright 2017 The Bazel 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 starlark - -// This file defines the library of built-ins. -// -// Built-ins must explicitly check the "frozen" flag before updating -// mutable types such as lists and dicts. - -import ( - "errors" - "fmt" - "math" - "math/big" - "os" - "sort" - "strconv" - "strings" - "unicode" - "unicode/utf16" - "unicode/utf8" - - "go.starlark.net/syntax" -) - -// Universe defines the set of universal built-ins, such as None, True, and len. -// -// The Go application may add or remove items from the -// universe dictionary before Starlark evaluation begins. -// All values in the dictionary must be immutable. -// Starlark programs cannot modify the dictionary. -var Universe StringDict - -func init() { - // https://github.com/google/starlark-go/blob/master/doc/spec.md#built-in-constants-and-functions - Universe = StringDict{ - "None": None, - "True": True, - "False": False, - "abs": NewBuiltin("abs", abs), - "any": NewBuiltin("any", any_), - "all": NewBuiltin("all", all), - "bool": NewBuiltin("bool", bool_), - "bytes": NewBuiltin("bytes", bytes_), - "chr": NewBuiltin("chr", chr), - "dict": NewBuiltin("dict", dict), - "dir": NewBuiltin("dir", dir), - "enumerate": NewBuiltin("enumerate", enumerate), - "fail": NewBuiltin("fail", fail), - "float": NewBuiltin("float", float), - "getattr": NewBuiltin("getattr", getattr), - "hasattr": NewBuiltin("hasattr", hasattr), - "hash": NewBuiltin("hash", hash), - "int": NewBuiltin("int", int_), - "len": NewBuiltin("len", len_), - "list": NewBuiltin("list", list), - "max": NewBuiltin("max", minmax), - "min": NewBuiltin("min", minmax), - "ord": NewBuiltin("ord", ord), - "print": NewBuiltin("print", print), - "range": NewBuiltin("range", range_), - "repr": NewBuiltin("repr", repr), - "reversed": NewBuiltin("reversed", reversed), - "set": NewBuiltin("set", set), // requires resolve.AllowSet - "sorted": NewBuiltin("sorted", sorted), - "str": NewBuiltin("str", str), - "tuple": NewBuiltin("tuple", tuple), - "type": NewBuiltin("type", type_), - "zip": NewBuiltin("zip", zip), - } -} - -// methods of built-in types -// https://github.com/google/starlark-go/blob/master/doc/spec.md#built-in-methods -var ( - bytesMethods = map[string]*Builtin{ - "elems": NewBuiltin("elems", bytes_elems), - } - - dictMethods = map[string]*Builtin{ - "clear": NewBuiltin("clear", dict_clear), - "get": NewBuiltin("get", dict_get), - "items": NewBuiltin("items", dict_items), - "keys": NewBuiltin("keys", dict_keys), - "pop": NewBuiltin("pop", dict_pop), - "popitem": NewBuiltin("popitem", dict_popitem), - "setdefault": NewBuiltin("setdefault", dict_setdefault), - "update": NewBuiltin("update", dict_update), - "values": NewBuiltin("values", dict_values), - } - - listMethods = map[string]*Builtin{ - "append": NewBuiltin("append", list_append), - "clear": NewBuiltin("clear", list_clear), - "extend": NewBuiltin("extend", list_extend), - "index": NewBuiltin("index", list_index), - "insert": NewBuiltin("insert", list_insert), - "pop": NewBuiltin("pop", list_pop), - "remove": NewBuiltin("remove", list_remove), - } - - stringMethods = map[string]*Builtin{ - "capitalize": NewBuiltin("capitalize", string_capitalize), - "codepoint_ords": NewBuiltin("codepoint_ords", string_iterable), - "codepoints": NewBuiltin("codepoints", string_iterable), // sic - "count": NewBuiltin("count", string_count), - "elem_ords": NewBuiltin("elem_ords", string_iterable), - "elems": NewBuiltin("elems", string_iterable), // sic - "endswith": NewBuiltin("endswith", string_startswith), // sic - "find": NewBuiltin("find", string_find), - "format": NewBuiltin("format", string_format), - "index": NewBuiltin("index", string_index), - "isalnum": NewBuiltin("isalnum", string_isalnum), - "isalpha": NewBuiltin("isalpha", string_isalpha), - "isdigit": NewBuiltin("isdigit", string_isdigit), - "islower": NewBuiltin("islower", string_islower), - "isspace": NewBuiltin("isspace", string_isspace), - "istitle": NewBuiltin("istitle", string_istitle), - "isupper": NewBuiltin("isupper", string_isupper), - "join": NewBuiltin("join", string_join), - "lower": NewBuiltin("lower", string_lower), - "lstrip": NewBuiltin("lstrip", string_strip), // sic - "partition": NewBuiltin("partition", string_partition), - "removeprefix": NewBuiltin("removeprefix", string_removefix), - "removesuffix": NewBuiltin("removesuffix", string_removefix), - "replace": NewBuiltin("replace", string_replace), - "rfind": NewBuiltin("rfind", string_rfind), - "rindex": NewBuiltin("rindex", string_rindex), - "rpartition": NewBuiltin("rpartition", string_partition), // sic - "rsplit": NewBuiltin("rsplit", string_split), // sic - "rstrip": NewBuiltin("rstrip", string_strip), // sic - "split": NewBuiltin("split", string_split), - "splitlines": NewBuiltin("splitlines", string_splitlines), - "startswith": NewBuiltin("startswith", string_startswith), - "strip": NewBuiltin("strip", string_strip), - "title": NewBuiltin("title", string_title), - "upper": NewBuiltin("upper", string_upper), - } - - setMethods = map[string]*Builtin{ - "add": NewBuiltin("add", set_add), - "clear": NewBuiltin("clear", set_clear), - "difference": NewBuiltin("difference", set_difference), - "discard": NewBuiltin("discard", set_discard), - "intersection": NewBuiltin("intersection", set_intersection), - "issubset": NewBuiltin("issubset", set_issubset), - "issuperset": NewBuiltin("issuperset", set_issuperset), - "pop": NewBuiltin("pop", set_pop), - "remove": NewBuiltin("remove", set_remove), - "symmetric_difference": NewBuiltin("symmetric_difference", set_symmetric_difference), - "union": NewBuiltin("union", set_union), - } -) - -func builtinAttr(recv Value, name string, methods map[string]*Builtin) (Value, error) { - b := methods[name] - if b == nil { - return nil, nil // no such method - } - return b.BindReceiver(recv), nil -} - -func builtinAttrNames(methods map[string]*Builtin) []string { - names := make([]string, 0, len(methods)) - for name := range methods { - names = append(names, name) - } - sort.Strings(names) - return names -} - -// ---- built-in functions ---- - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#abs -func abs(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value - if err := UnpackPositionalArgs("abs", args, kwargs, 1, &x); err != nil { - return nil, err - } - switch x := x.(type) { - case Float: - return Float(math.Abs(float64(x))), nil - case Int: - if x.Sign() >= 0 { - return x, nil - } - return zero.Sub(x), nil - default: - return nil, fmt.Errorf("got %s, want int or float", x.Type()) - } -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#all -func all(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("all", args, kwargs, 1, &iterable); err != nil { - return nil, err - } - iter := iterable.Iterate() - defer iter.Done() - var x Value - for iter.Next(&x) { - if !x.Truth() { - return False, nil - } - } - return True, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#any -func any_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("any", args, kwargs, 1, &iterable); err != nil { - return nil, err - } - iter := iterable.Iterate() - defer iter.Done() - var x Value - for iter.Next(&x) { - if x.Truth() { - return True, nil - } - } - return False, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#bool -func bool_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value = False - if err := UnpackPositionalArgs("bool", args, kwargs, 0, &x); err != nil { - return nil, err - } - return x.Truth(), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#bytes -func bytes_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("bytes does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("bytes: got %d arguments, want exactly 1", len(args)) - } - switch x := args[0].(type) { - case Bytes: - return x, nil - case String: - // Invalid encodings are replaced by that of U+FFFD. - return Bytes(utf8Transcode(string(x))), nil - case Iterable: - // iterable of numeric byte values - var buf strings.Builder - if n := Len(x); n >= 0 { - // common case: known length - buf.Grow(n) - } - iter := x.Iterate() - defer iter.Done() - var elem Value - var b byte - for i := 0; iter.Next(&elem); i++ { - if err := AsInt(elem, &b); err != nil { - return nil, fmt.Errorf("bytes: at index %d, %s", i, err) - } - buf.WriteByte(b) - } - return Bytes(buf.String()), nil - - default: - // Unlike string(foo), which stringifies it, bytes(foo) is an error. - return nil, fmt.Errorf("bytes: got %s, want string, bytes, or iterable of ints", x.Type()) - } -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#chr -func chr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("chr does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("chr: got %d arguments, want 1", len(args)) - } - i, err := AsInt32(args[0]) - if err != nil { - return nil, fmt.Errorf("chr: %s", err) - } - if i < 0 { - return nil, fmt.Errorf("chr: Unicode code point %d out of range (<0)", i) - } - if i > unicode.MaxRune { - return nil, fmt.Errorf("chr: Unicode code point U+%X out of range (>0x10FFFF)", i) - } - return String(string(rune(i))), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict -func dict(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(args) > 1 { - return nil, fmt.Errorf("dict: got %d arguments, want at most 1", len(args)) - } - dict := new(Dict) - if err := updateDict(dict, args, kwargs); err != nil { - return nil, fmt.Errorf("dict: %v", err) - } - return dict, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dir -func dir(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("dir does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("dir: got %d arguments, want 1", len(args)) - } - - var names []string - if x, ok := args[0].(HasAttrs); ok { - names = x.AttrNames() - } - sort.Strings(names) - elems := make([]Value, len(names)) - for i, name := range names { - elems[i] = String(name) - } - return NewList(elems), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#enumerate -func enumerate(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - var start int - if err := UnpackPositionalArgs("enumerate", args, kwargs, 1, &iterable, &start); err != nil { - return nil, err - } - - iter := iterable.Iterate() - defer iter.Done() - - var pairs []Value - var x Value - - if n := Len(iterable); n >= 0 { - // common case: known length - pairs = make([]Value, 0, n) - array := make(Tuple, 2*n) // allocate a single backing array - for i := 0; iter.Next(&x); i++ { - pair := array[:2:2] - array = array[2:] - pair[0] = MakeInt(start + i) - pair[1] = x - pairs = append(pairs, pair) - } - } else { - // non-sequence (unknown length) - for i := 0; iter.Next(&x); i++ { - pair := Tuple{MakeInt(start + i), x} - pairs = append(pairs, pair) - } - } - - return NewList(pairs), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#fail -func fail(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - sep := " " - if err := UnpackArgs("fail", nil, kwargs, "sep?", &sep); err != nil { - return nil, err - } - buf := new(strings.Builder) - buf.WriteString("fail: ") - for i, v := range args { - if i > 0 { - buf.WriteString(sep) - } - if s, ok := AsString(v); ok { - buf.WriteString(s) - } else { - writeValue(buf, v, nil) - } - } - - return nil, errors.New(buf.String()) -} - -func float(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("float does not accept keyword arguments") - } - if len(args) == 0 { - return Float(0.0), nil - } - if len(args) != 1 { - return nil, fmt.Errorf("float got %d arguments, wants 1", len(args)) - } - switch x := args[0].(type) { - case Bool: - if x { - return Float(1.0), nil - } else { - return Float(0.0), nil - } - case Int: - return x.finiteFloat() - case Float: - return x, nil - case String: - if x == "" { - return nil, fmt.Errorf("float: empty string") - } - // +/- NaN or Inf or Infinity (case insensitive)? - s := string(x) - switch x[len(x)-1] { - case 'y', 'Y': - if strings.EqualFold(s, "infinity") || strings.EqualFold(s, "+infinity") { - return inf, nil - } else if strings.EqualFold(s, "-infinity") { - return neginf, nil - } - case 'f', 'F': - if strings.EqualFold(s, "inf") || strings.EqualFold(s, "+inf") { - return inf, nil - } else if strings.EqualFold(s, "-inf") { - return neginf, nil - } - case 'n', 'N': - if strings.EqualFold(s, "nan") || strings.EqualFold(s, "+nan") || strings.EqualFold(s, "-nan") { - return nan, nil - } - } - f, err := strconv.ParseFloat(s, 64) - if math.IsInf(f, 0) { - return nil, fmt.Errorf("floating-point number too large") - } - if err != nil { - return nil, fmt.Errorf("invalid float literal: %s", s) - } - return Float(f), nil - default: - return nil, fmt.Errorf("float got %s, want number or string", x.Type()) - } -} - -var ( - inf = Float(math.Inf(+1)) - neginf = Float(math.Inf(-1)) - nan = Float(math.NaN()) -) - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#getattr -func getattr(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var object, dflt Value - var name string - if err := UnpackPositionalArgs("getattr", args, kwargs, 2, &object, &name, &dflt); err != nil { - return nil, err - } - if object, ok := object.(HasAttrs); ok { - v, err := object.Attr(name) - if err != nil { - // An error could mean the field doesn't exist, - // or it exists but could not be computed. - if dflt != nil { - return dflt, nil - } - return nil, nameErr(b, err) - } - if v != nil { - return v, nil - } - // (nil, nil) => no such field - } - if dflt != nil { - return dflt, nil - } - return nil, fmt.Errorf("getattr: %s has no .%s field or method", object.Type(), name) -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#hasattr -func hasattr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var object Value - var name string - if err := UnpackPositionalArgs("hasattr", args, kwargs, 2, &object, &name); err != nil { - return nil, err - } - if object, ok := object.(HasAttrs); ok { - v, err := object.Attr(name) - if err == nil { - return Bool(v != nil), nil - } - - // An error does not conclusively indicate presence or - // absence of a field: it could occur while computing - // the value of a present attribute, or it could be a - // "no such attribute" error with details. - for _, x := range object.AttrNames() { - if x == name { - return True, nil - } - } - } - return False, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#hash -func hash(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value - if err := UnpackPositionalArgs("hash", args, kwargs, 1, &x); err != nil { - return nil, err - } - - var h int64 - switch x := x.(type) { - case String: - // The Starlark spec requires that the hash function be - // deterministic across all runs, motivated by the need - // for reproducibility of builds. Thus we cannot call - // String.Hash, which uses the fastest implementation - // available, because as varies across process restarts, - // and may evolve with the implementation. - h = int64(javaStringHash(string(x))) - case Bytes: - h = int64(softHashString(string(x))) // FNV32 - default: - return nil, fmt.Errorf("hash: got %s, want string or bytes", x.Type()) - } - return MakeInt64(h), nil -} - -// javaStringHash returns the same hash as would be produced by -// java.lang.String.hashCode. This requires transcoding the string to -// UTF-16; transcoding may introduce Unicode replacement characters -// U+FFFD if s does not contain valid UTF-8. -func javaStringHash(s string) (h int32) { - for _, r := range s { - if utf16.IsSurrogate(r) { - c1, c2 := utf16.EncodeRune(r) - h = 31*h + c1 - h = 31*h + c2 - } else { - h = 31*h + r // r may be U+FFFD - } - } - return h -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#int -func int_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value = zero - var base Value - if err := UnpackArgs("int", args, kwargs, "x", &x, "base?", &base); err != nil { - return nil, err - } - - if s, ok := AsString(x); ok { - b := 10 - if base != nil { - var err error - b, err = AsInt32(base) - if err != nil { - return nil, fmt.Errorf("int: for base, got %s, want int", base.Type()) - } - if b != 0 && (b < 2 || b > 36) { - return nil, fmt.Errorf("int: base must be an integer >= 2 && <= 36") - } - } - res := parseInt(s, b) - if res == nil { - return nil, fmt.Errorf("int: invalid literal with base %d: %s", b, s) - } - return res, nil - } - - if base != nil { - return nil, fmt.Errorf("int: can't convert non-string with explicit base") - } - - if b, ok := x.(Bool); ok { - if b { - return one, nil - } else { - return zero, nil - } - } - - i, err := NumberToInt(x) - if err != nil { - return nil, fmt.Errorf("int: %s", err) - } - return i, nil -} - -// parseInt defines the behavior of int(string, base=int). It returns nil on error. -func parseInt(s string, base int) Value { - // remove sign - var neg bool - if s != "" { - if s[0] == '+' { - s = s[1:] - } else if s[0] == '-' { - neg = true - s = s[1:] - } - } - - // remove optional base prefix - baseprefix := 0 - if len(s) > 1 && s[0] == '0' { - if len(s) > 2 { - switch s[1] { - case 'o', 'O': - baseprefix = 8 - case 'x', 'X': - baseprefix = 16 - case 'b', 'B': - baseprefix = 2 - } - } - if baseprefix != 0 { - // Remove the base prefix if it matches - // the explicit base, or if base=0. - if base == 0 || baseprefix == base { - base = baseprefix - s = s[2:] - } - } else { - // For automatic base detection, - // a string starting with zero - // must be all zeros. - // Thus we reject int("0755", 0). - if base == 0 { - for i := 1; i < len(s); i++ { - if s[i] != '0' { - return nil - } - } - return zero - } - } - } - if base == 0 { - base = 10 - } - - // we explicitly handled sign above. - // if a sign remains, it is invalid. - if s != "" && (s[0] == '-' || s[0] == '+') { - return nil - } - - // s has no sign or base prefix. - if i, ok := new(big.Int).SetString(s, base); ok { - res := MakeBigInt(i) - if neg { - res = zero.Sub(res) - } - return res - } - - return nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#len -func len_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value - if err := UnpackPositionalArgs("len", args, kwargs, 1, &x); err != nil { - return nil, err - } - len := Len(x) - if len < 0 { - return nil, fmt.Errorf("len: value of type %s has no len", x.Type()) - } - return MakeInt(len), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list -func list(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("list", args, kwargs, 0, &iterable); err != nil { - return nil, err - } - var elems []Value - if iterable != nil { - iter := iterable.Iterate() - defer iter.Done() - if n := Len(iterable); n > 0 { - elems = make([]Value, 0, n) // preallocate if length known - } - var x Value - for iter.Next(&x) { - elems = append(elems, x) - } - } - return NewList(elems), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#min -func minmax(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(args) == 0 { - return nil, fmt.Errorf("%s requires at least one positional argument", b.Name()) - } - var keyFunc Callable - if err := UnpackArgs(b.Name(), nil, kwargs, "key?", &keyFunc); err != nil { - return nil, err - } - var op syntax.Token - if b.Name() == "max" { - op = syntax.GT - } else { - op = syntax.LT - } - var iterable Value - if len(args) == 1 { - iterable = args[0] - } else { - iterable = args - } - iter := Iterate(iterable) - if iter == nil { - return nil, fmt.Errorf("%s: %s value is not iterable", b.Name(), iterable.Type()) - } - defer iter.Done() - var extremum Value - if !iter.Next(&extremum) { - return nil, nameErr(b, "argument is an empty sequence") - } - - var extremeKey Value - var keyargs Tuple - if keyFunc == nil { - extremeKey = extremum - } else { - keyargs = Tuple{extremum} - res, err := Call(thread, keyFunc, keyargs, nil) - if err != nil { - return nil, err // to preserve backtrace, don't modify error - } - extremeKey = res - } - - var x Value - for iter.Next(&x) { - var key Value - if keyFunc == nil { - key = x - } else { - keyargs[0] = x - res, err := Call(thread, keyFunc, keyargs, nil) - if err != nil { - return nil, err // to preserve backtrace, don't modify error - } - key = res - } - - if ok, err := Compare(op, key, extremeKey); err != nil { - return nil, nameErr(b, err) - } else if ok { - extremum = x - extremeKey = key - } - } - return extremum, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#ord -func ord(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("ord does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("ord: got %d arguments, want 1", len(args)) - } - switch x := args[0].(type) { - case String: - // ord(string) returns int value of sole rune. - s := string(x) - r, sz := utf8.DecodeRuneInString(s) - if sz == 0 || sz != len(s) { - n := utf8.RuneCountInString(s) - return nil, fmt.Errorf("ord: string encodes %d Unicode code points, want 1", n) - } - return MakeInt(int(r)), nil - - case Bytes: - // ord(bytes) returns int value of sole byte. - if len(x) != 1 { - return nil, fmt.Errorf("ord: bytes has length %d, want 1", len(x)) - } - return MakeInt(int(x[0])), nil - default: - return nil, fmt.Errorf("ord: got %s, want string or bytes", x.Type()) - } -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#print -func print(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - sep := " " - if err := UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil { - return nil, err - } - buf := new(strings.Builder) - for i, v := range args { - if i > 0 { - buf.WriteString(sep) - } - if s, ok := AsString(v); ok { - buf.WriteString(s) - } else if b, ok := v.(Bytes); ok { - buf.WriteString(string(b)) - } else { - writeValue(buf, v, nil) - } - } - - s := buf.String() - if thread.Print != nil { - thread.Print(thread, s) - } else { - fmt.Fprintln(os.Stderr, s) - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#range -func range_(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var start, stop, step int - step = 1 - if err := UnpackPositionalArgs("range", args, kwargs, 1, &start, &stop, &step); err != nil { - return nil, err - } - - if len(args) == 1 { - // range(stop) - start, stop = 0, start - } - if step == 0 { - // we were given range(start, stop, 0) - return nil, nameErr(b, "step argument must not be zero") - } - - return rangeValue{start: start, stop: stop, step: step, len: rangeLen(start, stop, step)}, nil -} - -// A rangeValue is a comparable, immutable, indexable sequence of integers -// defined by the three parameters to a range(...) call. -// Invariant: step != 0. -type rangeValue struct{ start, stop, step, len int } - -var ( - _ Indexable = rangeValue{} - _ Sequence = rangeValue{} - _ Comparable = rangeValue{} - _ Sliceable = rangeValue{} -) - -func (r rangeValue) Len() int { return r.len } -func (r rangeValue) Index(i int) Value { return MakeInt(r.start + i*r.step) } -func (r rangeValue) Iterate() Iterator { return &rangeIterator{r, 0} } - -// rangeLen calculates the length of a range with the provided start, stop, and step. -// caller must ensure that step is non-zero. -func rangeLen(start, stop, step int) int { - switch { - case step > 0: - if stop > start { - return (stop-1-start)/step + 1 - } - case step < 0: - if start > stop { - return (start-1-stop)/-step + 1 - } - default: - panic("rangeLen: zero step") - } - return 0 -} - -func (r rangeValue) Slice(start, end, step int) Value { - newStart := r.start + r.step*start - newStop := r.start + r.step*end - newStep := r.step * step - return rangeValue{ - start: newStart, - stop: newStop, - step: newStep, - len: rangeLen(newStart, newStop, newStep), - } -} - -func (r rangeValue) Freeze() {} // immutable -func (r rangeValue) String() string { - if r.step != 1 { - return fmt.Sprintf("range(%d, %d, %d)", r.start, r.stop, r.step) - } else if r.start != 0 { - return fmt.Sprintf("range(%d, %d)", r.start, r.stop) - } else { - return fmt.Sprintf("range(%d)", r.stop) - } -} -func (r rangeValue) Type() string { return "range" } -func (r rangeValue) Truth() Bool { return r.len > 0 } -func (r rangeValue) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: range") } - -func (x rangeValue) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(rangeValue) - switch op { - case syntax.EQL: - return rangeEqual(x, y), nil - case syntax.NEQ: - return !rangeEqual(x, y), nil - default: - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) - } -} - -func rangeEqual(x, y rangeValue) bool { - // Two ranges compare equal if they denote the same sequence. - if x.len != y.len { - return false // sequences differ in length - } - if x.len == 0 { - return true // both sequences are empty - } - if x.start != y.start { - return false // first element differs - } - return x.len == 1 || x.step == y.step -} - -func (r rangeValue) contains(x Int) bool { - x32, err := AsInt32(x) - if err != nil { - return false // out of range - } - delta := x32 - r.start - quo, rem := delta/r.step, delta%r.step - return rem == 0 && 0 <= quo && quo < r.len -} - -type rangeIterator struct { - r rangeValue - i int -} - -func (it *rangeIterator) Next(p *Value) bool { - if it.i < it.r.len { - *p = it.r.Index(it.i) - it.i++ - return true - } - return false -} -func (*rangeIterator) Done() {} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#repr -func repr(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value - if err := UnpackPositionalArgs("repr", args, kwargs, 1, &x); err != nil { - return nil, err - } - return String(x.String()), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#reversed -func reversed(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("reversed", args, kwargs, 1, &iterable); err != nil { - return nil, err - } - iter := iterable.Iterate() - defer iter.Done() - var elems []Value - if n := Len(args[0]); n >= 0 { - elems = make([]Value, 0, n) // preallocate if length known - } - var x Value - for iter.Next(&x) { - elems = append(elems, x) - } - n := len(elems) - for i := 0; i < n>>1; i++ { - elems[i], elems[n-1-i] = elems[n-1-i], elems[i] - } - return NewList(elems), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set -func set(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("set", args, kwargs, 0, &iterable); err != nil { - return nil, err - } - set := new(Set) - if iterable != nil { - iter := iterable.Iterate() - defer iter.Done() - var x Value - for iter.Next(&x) { - if err := set.Insert(x); err != nil { - return nil, nameErr(b, err) - } - } - } - return set, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#sorted -func sorted(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - // Oddly, Python's sorted permits all arguments to be positional, thus so do we. - var iterable Iterable - var key Callable - var reverse bool - if err := UnpackArgs("sorted", args, kwargs, - "iterable", &iterable, - "key?", &key, - "reverse?", &reverse, - ); err != nil { - return nil, err - } - - iter := iterable.Iterate() - defer iter.Done() - var values []Value - if n := Len(iterable); n > 0 { - values = make(Tuple, 0, n) // preallocate if length is known - } - var x Value - for iter.Next(&x) { - values = append(values, x) - } - - // Derive keys from values by applying key function. - var keys []Value - if key != nil { - keys = make([]Value, len(values)) - for i, v := range values { - k, err := Call(thread, key, Tuple{v}, nil) - if err != nil { - return nil, err // to preserve backtrace, don't modify error - } - keys[i] = k - } - } - - slice := &sortSlice{keys: keys, values: values} - if reverse { - sort.Stable(sort.Reverse(slice)) - } else { - sort.Stable(slice) - } - return NewList(slice.values), slice.err -} - -type sortSlice struct { - keys []Value // nil => values[i] is key - values []Value - err error -} - -func (s *sortSlice) Len() int { return len(s.values) } -func (s *sortSlice) Less(i, j int) bool { - keys := s.keys - if s.keys == nil { - keys = s.values - } - ok, err := Compare(syntax.LT, keys[i], keys[j]) - if err != nil { - s.err = err - } - return ok -} -func (s *sortSlice) Swap(i, j int) { - if s.keys != nil { - s.keys[i], s.keys[j] = s.keys[j], s.keys[i] - } - s.values[i], s.values[j] = s.values[j], s.values[i] -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#str -func str(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("str does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("str: got %d arguments, want exactly 1", len(args)) - } - switch x := args[0].(type) { - case String: - return x, nil - case Bytes: - // Invalid encodings are replaced by that of U+FFFD. - return String(utf8Transcode(string(x))), nil - default: - return String(x.String()), nil - } -} - -// utf8Transcode returns the UTF-8-to-UTF-8 transcoding of s. -// The effect is that each code unit that is part of an -// invalid sequence is replaced by U+FFFD. -func utf8Transcode(s string) string { - if utf8.ValidString(s) { - return s - } - var out strings.Builder - for _, r := range s { - out.WriteRune(r) - } - return out.String() -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#tuple -func tuple(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs("tuple", args, kwargs, 0, &iterable); err != nil { - return nil, err - } - if len(args) == 0 { - return Tuple(nil), nil - } - iter := iterable.Iterate() - defer iter.Done() - var elems Tuple - if n := Len(iterable); n > 0 { - elems = make(Tuple, 0, n) // preallocate if length is known - } - var x Value - for iter.Next(&x) { - elems = append(elems, x) - } - return elems, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#type -func type_(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("type does not accept keyword arguments") - } - if len(args) != 1 { - return nil, fmt.Errorf("type: got %d arguments, want exactly 1", len(args)) - } - return String(args[0].Type()), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#zip -func zip(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(kwargs) > 0 { - return nil, fmt.Errorf("zip does not accept keyword arguments") - } - rows, cols := 0, len(args) - iters := make([]Iterator, cols) - defer func() { - for _, iter := range iters { - if iter != nil { - iter.Done() - } - } - }() - for i, seq := range args { - it := Iterate(seq) - if it == nil { - return nil, fmt.Errorf("zip: argument #%d is not iterable: %s", i+1, seq.Type()) - } - iters[i] = it - n := Len(seq) - if i == 0 || n < rows { - rows = n // possibly -1 - } - } - var result []Value - if rows >= 0 { - // length known - result = make([]Value, rows) - array := make(Tuple, cols*rows) // allocate a single backing array - for i := 0; i < rows; i++ { - tuple := array[:cols:cols] - array = array[cols:] - for j, iter := range iters { - iter.Next(&tuple[j]) - } - result[i] = tuple - } - } else { - // length not known - outer: - for { - tuple := make(Tuple, cols) - for i, iter := range iters { - if !iter.Next(&tuple[i]) { - break outer - } - } - result = append(result, tuple) - } - } - return NewList(result), nil -} - -// ---- methods of built-in types --- - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·get -func dict_get(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var key, dflt Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &key, &dflt); err != nil { - return nil, err - } - if v, ok, err := b.Receiver().(*Dict).Get(key); err != nil { - return nil, nameErr(b, err) - } else if ok { - return v, nil - } else if dflt != nil { - return dflt, nil - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·clear -func dict_clear(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - return None, b.Receiver().(*Dict).Clear() -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·items -func dict_items(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - items := b.Receiver().(*Dict).Items() - res := make([]Value, len(items)) - for i, item := range items { - res[i] = item // convert [2]Value to Value - } - return NewList(res), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·keys -func dict_keys(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - return NewList(b.Receiver().(*Dict).Keys()), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·pop -func dict_pop(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var k, d Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &k, &d); err != nil { - return nil, err - } - if v, found, err := b.Receiver().(*Dict).Delete(k); err != nil { - return nil, nameErr(b, err) // dict is frozen or key is unhashable - } else if found { - return v, nil - } else if d != nil { - return d, nil - } - return nil, nameErr(b, "missing key") -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·popitem -func dict_popitem(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := b.Receiver().(*Dict) - k, ok := recv.ht.first() - if !ok { - return nil, nameErr(b, "empty dict") - } - v, _, err := recv.Delete(k) - if err != nil { - return nil, nameErr(b, err) // dict is frozen - } - return Tuple{k, v}, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·setdefault -func dict_setdefault(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var key, dflt Value = nil, None - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &key, &dflt); err != nil { - return nil, err - } - dict := b.Receiver().(*Dict) - if v, ok, err := dict.Get(key); err != nil { - return nil, nameErr(b, err) - } else if ok { - return v, nil - } else if err := dict.SetKey(key, dflt); err != nil { - return nil, nameErr(b, err) - } else { - return dflt, nil - } -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·update -func dict_update(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if len(args) > 1 { - return nil, fmt.Errorf("update: got %d arguments, want at most 1", len(args)) - } - if err := updateDict(b.Receiver().(*Dict), args, kwargs); err != nil { - return nil, fmt.Errorf("update: %v", err) - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·update -func dict_values(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - items := b.Receiver().(*Dict).Items() - res := make([]Value, len(items)) - for i, item := range items { - res[i] = item[1] - } - return NewList(res), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·append -func list_append(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var object Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &object); err != nil { - return nil, err - } - recv := b.Receiver().(*List) - if err := recv.checkMutable("append to"); err != nil { - return nil, nameErr(b, err) - } - recv.elems = append(recv.elems, object) - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·clear -func list_clear(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - if err := b.Receiver().(*List).Clear(); err != nil { - return nil, nameErr(b, err) - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·extend -func list_extend(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := b.Receiver().(*List) - var iterable Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &iterable); err != nil { - return nil, err - } - if err := recv.checkMutable("extend"); err != nil { - return nil, nameErr(b, err) - } - listExtend(recv, iterable) - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·index -func list_index(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var value, start_, end_ Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &value, &start_, &end_); err != nil { - return nil, err - } - - recv := b.Receiver().(*List) - start, end, err := indices(start_, end_, recv.Len()) - if err != nil { - return nil, nameErr(b, err) - } - - for i := start; i < end; i++ { - if eq, err := Equal(recv.elems[i], value); err != nil { - return nil, nameErr(b, err) - } else if eq { - return MakeInt(i), nil - } - } - return nil, nameErr(b, "value not in list") -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·insert -func list_insert(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := b.Receiver().(*List) - var index int - var object Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 2, &index, &object); err != nil { - return nil, err - } - if err := recv.checkMutable("insert into"); err != nil { - return nil, nameErr(b, err) - } - - if index < 0 { - index += recv.Len() - } - - if index >= recv.Len() { - // end - recv.elems = append(recv.elems, object) - } else { - if index < 0 { - index = 0 // start - } - recv.elems = append(recv.elems, nil) - copy(recv.elems[index+1:], recv.elems[index:]) // slide up one - recv.elems[index] = object - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·remove -func list_remove(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := b.Receiver().(*List) - var value Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &value); err != nil { - return nil, err - } - if err := recv.checkMutable("remove from"); err != nil { - return nil, nameErr(b, err) - } - for i, elem := range recv.elems { - if eq, err := Equal(elem, value); err != nil { - return nil, fmt.Errorf("remove: %v", err) - } else if eq { - recv.elems = append(recv.elems[:i], recv.elems[i+1:]...) - return None, nil - } - } - return nil, fmt.Errorf("remove: element not found") -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#list·pop -func list_pop(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := b.Receiver() - list := recv.(*List) - n := list.Len() - i := n - 1 - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &i); err != nil { - return nil, err - } - origI := i - if i < 0 { - i += n - } - if i < 0 || i >= n { - return nil, nameErr(b, outOfRange(origI, n, list)) - } - if err := list.checkMutable("pop from"); err != nil { - return nil, nameErr(b, err) - } - res := list.elems[i] - list.elems = append(list.elems[:i], list.elems[i+1:]...) - return res, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·capitalize -func string_capitalize(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - s := string(b.Receiver().(String)) - res := new(strings.Builder) - res.Grow(len(s)) - for i, r := range s { - if i == 0 { - r = unicode.ToTitle(r) - } else { - r = unicode.ToLower(r) - } - res.WriteRune(r) - } - return String(res.String()), nil -} - -// string_iterable returns an unspecified iterable value whose iterator yields: -// - elems: successive 1-byte substrings -// - codepoints: successive substrings that encode a single Unicode code point. -// - elem_ords: numeric values of successive bytes -// - codepoint_ords: numeric values of successive Unicode code points -func string_iterable(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - s := b.Receiver().(String) - ords := b.Name()[len(b.Name())-2] == 'd' - codepoints := b.Name()[0] == 'c' - if codepoints { - return stringCodepoints{s, ords}, nil - } else { - return stringElems{s, ords}, nil - } -} - -// bytes_elems returns an unspecified iterable value whose -// iterator yields the int values of successive elements. -func bytes_elems(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - return bytesIterable{b.Receiver().(Bytes)}, nil -} - -// A bytesIterable is an iterable returned by bytes.elems(), -// whose iterator yields a sequence of numeric bytes values. -type bytesIterable struct{ bytes Bytes } - -var _ Iterable = (*bytesIterable)(nil) - -func (bi bytesIterable) String() string { return bi.bytes.String() + ".elems()" } -func (bi bytesIterable) Type() string { return "bytes.elems" } -func (bi bytesIterable) Freeze() {} // immutable -func (bi bytesIterable) Truth() Bool { return True } -func (bi bytesIterable) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", bi.Type()) } -func (bi bytesIterable) Iterate() Iterator { return &bytesIterator{bi.bytes} } - -type bytesIterator struct{ bytes Bytes } - -func (it *bytesIterator) Next(p *Value) bool { - if it.bytes == "" { - return false - } - *p = MakeInt(int(it.bytes[0])) - it.bytes = it.bytes[1:] - return true -} - -func (*bytesIterator) Done() {} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·count -func string_count(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var sub string - var start_, end_ Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &sub, &start_, &end_); err != nil { - return nil, err - } - - recv := string(b.Receiver().(String)) - start, end, err := indices(start_, end_, len(recv)) - if err != nil { - return nil, nameErr(b, err) - } - - var slice string - if start < end { - slice = recv[start:end] - } - return MakeInt(strings.Count(slice, sub)), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·isalnum -func string_isalnum(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - for _, r := range recv { - if !unicode.IsLetter(r) && !unicode.IsDigit(r) { - return False, nil - } - } - return Bool(recv != ""), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·isalpha -func string_isalpha(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - for _, r := range recv { - if !unicode.IsLetter(r) { - return False, nil - } - } - return Bool(recv != ""), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·isdigit -func string_isdigit(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - for _, r := range recv { - if !unicode.IsDigit(r) { - return False, nil - } - } - return Bool(recv != ""), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·islower -func string_islower(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - return Bool(isCasedString(recv) && recv == strings.ToLower(recv)), nil -} - -// isCasedString reports whether its argument contains any cased code points. -func isCasedString(s string) bool { - for _, r := range s { - if isCasedRune(r) { - return true - } - } - return false -} - -func isCasedRune(r rune) bool { - // It's unclear what the correct behavior is for a rune such as 'ffi', - // a lowercase letter with no upper or title case and no SimpleFold. - return 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || unicode.SimpleFold(r) != r -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·isspace -func string_isspace(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - for _, r := range recv { - if !unicode.IsSpace(r) { - return False, nil - } - } - return Bool(recv != ""), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·istitle -func string_istitle(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - - // Python semantics differ from x==strings.{To,}Title(x) in Go: - // "uppercase characters may only follow uncased characters and - // lowercase characters only cased ones." - var cased, prevCased bool - for _, r := range recv { - if 'A' <= r && r <= 'Z' || unicode.IsTitle(r) { // e.g. "Dž" - if prevCased { - return False, nil - } - prevCased = true - cased = true - } else if unicode.IsLower(r) { - if !prevCased { - return False, nil - } - prevCased = true - cased = true - } else if unicode.IsUpper(r) { - return False, nil - } else { - prevCased = false - } - } - return Bool(cased), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·isupper -func string_isupper(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - return Bool(isCasedString(recv) && recv == strings.ToUpper(recv)), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·find -func string_find(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - return string_find_impl(b, args, kwargs, true, false) -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·format -func string_format(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - format := string(b.Receiver().(String)) - var auto, manual bool // kinds of positional indexing used - buf := new(strings.Builder) - index := 0 - for { - literal := format - i := strings.IndexByte(format, '{') - if i >= 0 { - literal = format[:i] - } - - // Replace "}}" with "}" in non-field portion, rejecting a lone '}'. - for { - j := strings.IndexByte(literal, '}') - if j < 0 { - buf.WriteString(literal) - break - } - if len(literal) == j+1 || literal[j+1] != '}' { - return nil, fmt.Errorf("format: single '}' in format") - } - buf.WriteString(literal[:j+1]) - literal = literal[j+2:] - } - - if i < 0 { - break // end of format string - } - - if i+1 < len(format) && format[i+1] == '{' { - // "{{" means a literal '{' - buf.WriteByte('{') - format = format[i+2:] - continue - } - - format = format[i+1:] - i = strings.IndexByte(format, '}') - if i < 0 { - return nil, fmt.Errorf("format: unmatched '{' in format") - } - - var arg Value - conv := "s" - var spec string - - field := format[:i] - format = format[i+1:] - - var name string - if i := strings.IndexByte(field, '!'); i < 0 { - // "name" or "name:spec" - if i := strings.IndexByte(field, ':'); i < 0 { - name = field - } else { - name = field[:i] - spec = field[i+1:] - } - } else { - // "name!conv" or "name!conv:spec" - name = field[:i] - field = field[i+1:] - // "conv" or "conv:spec" - if i := strings.IndexByte(field, ':'); i < 0 { - conv = field - } else { - conv = field[:i] - spec = field[i+1:] - } - } - - if name == "" { - // "{}": automatic indexing - if manual { - return nil, fmt.Errorf("format: cannot switch from manual field specification to automatic field numbering") - } - auto = true - if index >= len(args) { - return nil, fmt.Errorf("format: tuple index out of range") - } - arg = args[index] - index++ - } else if num, ok := decimal(name); ok { - // positional argument - if auto { - return nil, fmt.Errorf("format: cannot switch from automatic field numbering to manual field specification") - } - manual = true - if num >= len(args) { - return nil, fmt.Errorf("format: tuple index out of range") - } else { - arg = args[num] - } - } else { - // keyword argument - for _, kv := range kwargs { - if string(kv[0].(String)) == name { - arg = kv[1] - break - } - } - if arg == nil { - // Starlark does not support Python's x.y or a[i] syntaxes, - // or nested use of {...}. - if strings.Contains(name, ".") { - return nil, fmt.Errorf("format: attribute syntax x.y is not supported in replacement fields: %s", name) - } - if strings.Contains(name, "[") { - return nil, fmt.Errorf("format: element syntax a[i] is not supported in replacement fields: %s", name) - } - if strings.Contains(name, "{") { - return nil, fmt.Errorf("format: nested replacement fields not supported") - } - return nil, fmt.Errorf("format: keyword %s not found", name) - } - } - - if spec != "" { - // Starlark does not support Python's format_spec features. - return nil, fmt.Errorf("format spec features not supported in replacement fields: %s", spec) - } - - switch conv { - case "s": - if str, ok := AsString(arg); ok { - buf.WriteString(str) - } else { - writeValue(buf, arg, nil) - } - case "r": - writeValue(buf, arg, nil) - default: - return nil, fmt.Errorf("format: unknown conversion %q", conv) - } - } - return String(buf.String()), nil -} - -// decimal interprets s as a sequence of decimal digits. -func decimal(s string) (x int, ok bool) { - n := len(s) - for i := 0; i < n; i++ { - digit := s[i] - '0' - if digit > 9 { - return 0, false - } - x = x*10 + int(digit) - if x < 0 { - return 0, false // underflow - } - } - return x, true -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·index -func string_index(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - return string_find_impl(b, args, kwargs, false, false) -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·join -func string_join(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := string(b.Receiver().(String)) - var iterable Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &iterable); err != nil { - return nil, err - } - iter := iterable.Iterate() - defer iter.Done() - buf := new(strings.Builder) - var x Value - for i := 0; iter.Next(&x); i++ { - if i > 0 { - buf.WriteString(recv) - } - s, ok := AsString(x) - if !ok { - return nil, fmt.Errorf("join: in list, want string, got %s", x.Type()) - } - buf.WriteString(s) - } - return String(buf.String()), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·lower -func string_lower(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - return String(strings.ToLower(string(b.Receiver().(String)))), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·partition -func string_partition(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := string(b.Receiver().(String)) - var sep string - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &sep); err != nil { - return nil, err - } - if sep == "" { - return nil, nameErr(b, "empty separator") - } - var i int - if b.Name()[0] == 'p' { - i = strings.Index(recv, sep) // partition - } else { - i = strings.LastIndex(recv, sep) // rpartition - } - tuple := make(Tuple, 0, 3) - if i < 0 { - if b.Name()[0] == 'p' { - tuple = append(tuple, String(recv), String(""), String("")) - } else { - tuple = append(tuple, String(""), String(""), String(recv)) - } - } else { - tuple = append(tuple, String(recv[:i]), String(sep), String(recv[i+len(sep):])) - } - return tuple, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·removeprefix -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·removesuffix -func string_removefix(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := string(b.Receiver().(String)) - var fix string - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &fix); err != nil { - return nil, err - } - if b.name[len("remove")] == 'p' { - recv = strings.TrimPrefix(recv, fix) - } else { - recv = strings.TrimSuffix(recv, fix) - } - return String(recv), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·replace -func string_replace(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := string(b.Receiver().(String)) - var old, new string - count := -1 - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 2, &old, &new, &count); err != nil { - return nil, err - } - return String(strings.Replace(recv, old, new, count)), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·rfind -func string_rfind(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - return string_find_impl(b, args, kwargs, true, true) -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·rindex -func string_rindex(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - return string_find_impl(b, args, kwargs, false, true) -} - -// https://github.com/google/starlark-go/starlark/blob/master/doc/spec.md#string·startswith -// https://github.com/google/starlark-go/starlark/blob/master/doc/spec.md#string·endswith -func string_startswith(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var x Value - var start, end Value = None, None - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &x, &start, &end); err != nil { - return nil, err - } - - // compute effective substring. - s := string(b.Receiver().(String)) - if start, end, err := indices(start, end, len(s)); err != nil { - return nil, nameErr(b, err) - } else { - if end < start { - end = start // => empty result - } - s = s[start:end] - } - - f := strings.HasPrefix - if b.Name()[0] == 'e' { // endswith - f = strings.HasSuffix - } - - switch x := x.(type) { - case Tuple: - for i, x := range x { - prefix, ok := AsString(x) - if !ok { - return nil, fmt.Errorf("%s: want string, got %s, for element %d", - b.Name(), x.Type(), i) - } - if f(s, prefix) { - return True, nil - } - } - return False, nil - case String: - return Bool(f(s, string(x))), nil - } - return nil, fmt.Errorf("%s: got %s, want string or tuple of string", b.Name(), x.Type()) -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·strip -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·lstrip -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·rstrip -func string_strip(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var chars string - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &chars); err != nil { - return nil, err - } - recv := string(b.Receiver().(String)) - var s string - switch b.Name()[0] { - case 's': // strip - if chars != "" { - s = strings.Trim(recv, chars) - } else { - s = strings.TrimSpace(recv) - } - case 'l': // lstrip - if chars != "" { - s = strings.TrimLeft(recv, chars) - } else { - s = strings.TrimLeftFunc(recv, unicode.IsSpace) - } - case 'r': // rstrip - if chars != "" { - s = strings.TrimRight(recv, chars) - } else { - s = strings.TrimRightFunc(recv, unicode.IsSpace) - } - } - return String(s), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·title -func string_title(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - - s := string(b.Receiver().(String)) - - // Python semantics differ from x==strings.{To,}Title(x) in Go: - // "uppercase characters may only follow uncased characters and - // lowercase characters only cased ones." - buf := new(strings.Builder) - buf.Grow(len(s)) - var prevCased bool - for _, r := range s { - if prevCased { - r = unicode.ToLower(r) - } else { - r = unicode.ToTitle(r) - } - prevCased = isCasedRune(r) - buf.WriteRune(r) - } - return String(buf.String()), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·upper -func string_upper(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - return String(strings.ToUpper(string(b.Receiver().(String)))), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·split -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·rsplit -func string_split(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - recv := string(b.Receiver().(String)) - var sep_ Value - maxsplit := -1 - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &sep_, &maxsplit); err != nil { - return nil, err - } - - var res []string - - if sep_ == nil || sep_ == None { - // special case: split on whitespace - if maxsplit < 0 { - res = strings.Fields(recv) - } else if b.Name() == "split" { - res = splitspace(recv, maxsplit) - } else { // rsplit - res = rsplitspace(recv, maxsplit) - } - - } else if sep, ok := AsString(sep_); ok { - if sep == "" { - return nil, fmt.Errorf("split: empty separator") - } - // usual case: split on non-empty separator - if maxsplit < 0 { - res = strings.Split(recv, sep) - } else if b.Name() == "split" { - res = strings.SplitN(recv, sep, maxsplit+1) - } else { // rsplit - res = strings.Split(recv, sep) - if excess := len(res) - maxsplit; excess > 0 { - res[0] = strings.Join(res[:excess], sep) - res = append(res[:1], res[excess:]...) - } - } - - } else { - return nil, fmt.Errorf("split: got %s for separator, want string", sep_.Type()) - } - - list := make([]Value, len(res)) - for i, x := range res { - list[i] = String(x) - } - return NewList(list), nil -} - -// Precondition: max >= 0. -func rsplitspace(s string, max int) []string { - res := make([]string, 0, max+1) - end := -1 // index of field end, or -1 in a region of spaces. - for i := len(s); i > 0; { - r, sz := utf8.DecodeLastRuneInString(s[:i]) - if unicode.IsSpace(r) { - if end >= 0 { - if len(res) == max { - break // let this field run to the start - } - res = append(res, s[i:end]) - end = -1 - } - } else if end < 0 { - end = i - } - i -= sz - } - if end >= 0 { - res = append(res, s[:end]) - } - - resLen := len(res) - for i := 0; i < resLen/2; i++ { - res[i], res[resLen-1-i] = res[resLen-1-i], res[i] - } - - return res -} - -// Precondition: max >= 0. -func splitspace(s string, max int) []string { - var res []string - start := -1 // index of field start, or -1 in a region of spaces - for i, r := range s { - if unicode.IsSpace(r) { - if start >= 0 { - if len(res) == max { - break // let this field run to the end - } - res = append(res, s[start:i]) - start = -1 - } - } else if start == -1 { - start = i - } - } - if start >= 0 { - res = append(res, s[start:]) - } - return res -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·splitlines -func string_splitlines(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var keepends bool - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &keepends); err != nil { - return nil, err - } - var lines []string - if s := string(b.Receiver().(String)); s != "" { - // TODO(adonovan): handle CRLF correctly. - if keepends { - lines = strings.SplitAfter(s, "\n") - } else { - lines = strings.Split(s, "\n") - } - if strings.HasSuffix(s, "\n") { - lines = lines[:len(lines)-1] - } - } - list := make([]Value, len(lines)) - for i, x := range lines { - list[i] = String(x) - } - return NewList(list), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·add. -func set_add(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var elem Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &elem); err != nil { - return nil, err - } - if found, err := b.Receiver().(*Set).Has(elem); err != nil { - return nil, nameErr(b, err) - } else if found { - return None, nil - } - err := b.Receiver().(*Set).Insert(elem) - if err != nil { - return nil, nameErr(b, err) - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·clear. -func set_clear(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - if b.Receiver().(*Set).Len() > 0 { - if err := b.Receiver().(*Set).Clear(); err != nil { - return nil, nameErr(b, err) - } - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·difference. -func set_difference(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - // TODO: support multiple others: s.difference(*others) - var other Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &other); err != nil { - return nil, err - } - iter := other.Iterate() - defer iter.Done() - diff, err := b.Receiver().(*Set).Difference(iter) - if err != nil { - return nil, nameErr(b, err) - } - return diff, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set_intersection. -func set_intersection(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - // TODO: support multiple others: s.difference(*others) - var other Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &other); err != nil { - return nil, err - } - iter := other.Iterate() - defer iter.Done() - diff, err := b.Receiver().(*Set).Intersection(iter) - if err != nil { - return nil, nameErr(b, err) - } - return diff, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set_issubset. -func set_issubset(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var other Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &other); err != nil { - return nil, err - } - iter := other.Iterate() - defer iter.Done() - diff, err := b.Receiver().(*Set).IsSubset(iter) - if err != nil { - return nil, nameErr(b, err) - } - return Bool(diff), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set_issuperset. -func set_issuperset(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var other Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &other); err != nil { - return nil, err - } - iter := other.Iterate() - defer iter.Done() - diff, err := b.Receiver().(*Set).IsSuperset(iter) - if err != nil { - return nil, nameErr(b, err) - } - return Bool(diff), nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·discard. -func set_discard(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var k Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &k); err != nil { - return nil, err - } - if found, err := b.Receiver().(*Set).Has(k); err != nil { - return nil, nameErr(b, err) - } else if !found { - return None, nil - } - if _, err := b.Receiver().(*Set).Delete(k); err != nil { - return nil, nameErr(b, err) // set is frozen - } - return None, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·pop. -func set_pop(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0); err != nil { - return nil, err - } - recv := b.Receiver().(*Set) - k, ok := recv.ht.first() - if !ok { - return nil, nameErr(b, "empty set") - } - _, err := recv.Delete(k) - if err != nil { - return nil, nameErr(b, err) // set is frozen - } - return k, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·remove. -func set_remove(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var k Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &k); err != nil { - return nil, err - } - if found, err := b.Receiver().(*Set).Delete(k); err != nil { - return nil, nameErr(b, err) // dict is frozen or key is unhashable - } else if found { - return None, nil - } - return nil, nameErr(b, "missing key") -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·symmetric_difference. -func set_symmetric_difference(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var other Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &other); err != nil { - return nil, err - } - iter := other.Iterate() - defer iter.Done() - diff, err := b.Receiver().(*Set).SymmetricDifference(iter) - if err != nil { - return nil, nameErr(b, err) - } - return diff, nil -} - -// https://github.com/google/starlark-go/blob/master/doc/spec.md#set·union. -func set_union(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { - var iterable Iterable - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &iterable); err != nil { - return nil, err - } - iter := iterable.Iterate() - defer iter.Done() - union, err := b.Receiver().(*Set).Union(iter) - if err != nil { - return nil, nameErr(b, err) - } - return union, nil -} - -// Common implementation of string_{r}{find,index}. -func string_find_impl(b *Builtin, args Tuple, kwargs []Tuple, allowError, last bool) (Value, error) { - var sub string - var start_, end_ Value - if err := UnpackPositionalArgs(b.Name(), args, kwargs, 1, &sub, &start_, &end_); err != nil { - return nil, err - } - - s := string(b.Receiver().(String)) - start, end, err := indices(start_, end_, len(s)) - if err != nil { - return nil, nameErr(b, err) - } - var slice string - if start < end { - slice = s[start:end] - } - - var i int - if last { - i = strings.LastIndex(slice, sub) - } else { - i = strings.Index(slice, sub) - } - if i < 0 { - if !allowError { - return nil, nameErr(b, "substring not found") - } - return MakeInt(-1), nil - } - return MakeInt(i + start), nil -} - -// Common implementation of builtin dict function and dict.update method. -// Precondition: len(updates) == 0 or 1. -func updateDict(dict *Dict, updates Tuple, kwargs []Tuple) error { - if len(updates) == 1 { - switch updates := updates[0].(type) { - case IterableMapping: - // Iterate over dict's key/value pairs, not just keys. - for _, item := range updates.Items() { - if err := dict.SetKey(item[0], item[1]); err != nil { - return err // dict is frozen - } - } - default: - // all other sequences - iter := Iterate(updates) - if iter == nil { - return fmt.Errorf("got %s, want iterable", updates.Type()) - } - defer iter.Done() - var pair Value - for i := 0; iter.Next(&pair); i++ { - iter2 := Iterate(pair) - if iter2 == nil { - return fmt.Errorf("dictionary update sequence element #%d is not iterable (%s)", i, pair.Type()) - - } - defer iter2.Done() - len := Len(pair) - if len < 0 { - return fmt.Errorf("dictionary update sequence element #%d has unknown length (%s)", i, pair.Type()) - } else if len != 2 { - return fmt.Errorf("dictionary update sequence element #%d has length %d, want 2", i, len) - } - var k, v Value - iter2.Next(&k) - iter2.Next(&v) - if err := dict.SetKey(k, v); err != nil { - return err - } - } - } - } - - // Then add the kwargs. - before := dict.Len() - for _, pair := range kwargs { - if err := dict.SetKey(pair[0], pair[1]); err != nil { - return err // dict is frozen - } - } - // In the common case, each kwarg will add another dict entry. - // If that's not so, check whether it is because there was a duplicate kwarg. - if dict.Len() < before+len(kwargs) { - keys := make(map[String]bool, len(kwargs)) - for _, kv := range kwargs { - k := kv[0].(String) - if keys[k] { - return fmt.Errorf("duplicate keyword arg: %v", k) - } - keys[k] = true - } - } - - return nil -} - -// nameErr returns an error message of the form "name: msg" -// where name is b.Name() and msg is a string or error. -func nameErr(b *Builtin, msg interface{}) error { - return fmt.Errorf("%s: %v", b.Name(), msg) -} diff --git a/vendor/go.starlark.net/starlark/profile.go b/vendor/go.starlark.net/starlark/profile.go deleted file mode 100644 index 590a4e2bb..000000000 --- a/vendor/go.starlark.net/starlark/profile.go +++ /dev/null @@ -1,449 +0,0 @@ -// Copyright 2019 The Bazel 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 starlark - -// This file defines a simple execution-time profiler for Starlark. -// It measures the wall time spent executing Starlark code, and emits a -// gzipped protocol message in pprof format (github.com/google/pprof). -// -// When profiling is enabled, the interpreter calls the profiler to -// indicate the start and end of each "span" or time interval. A leaf -// function (whether Go or Starlark) has a single span. A function that -// calls another function has spans for each interval in which it is the -// top of the stack. (A LOAD instruction also ends a span.) -// -// At the start of a span, the interpreter records the current time in -// the thread's topmost frame. At the end of the span, it obtains the -// time again and subtracts the span start time. The difference is added -// to an accumulator variable in the thread. If the accumulator exceeds -// some fixed quantum (10ms, say), the profiler records the current call -// stack and sends it to the profiler goroutine, along with the number -// of quanta, which are subtracted. For example, if the accumulator -// holds 3ms and then a completed span adds 25ms to it, its value is 28ms, -// which exceeeds 10ms. The profiler records a stack with the value 20ms -// (2 quanta), and the accumulator is left with 8ms. -// -// The profiler goroutine converts the stacks into the pprof format and -// emits a gzip-compressed protocol message to the designated output -// file. We use a hand-written streaming proto encoder to avoid -// dependencies on pprof and proto, and to avoid the need to -// materialize the profile data structure in memory. -// -// A limitation of this profiler is that it measures wall time, which -// does not necessarily correspond to CPU time. A CPU profiler requires -// that only running (not runnable) threads are sampled; this is -// commonly achieved by having the kernel deliver a (PROF) signal to an -// arbitrary running thread, through setitimer(2). The CPU profiler in the -// Go runtime uses this mechanism, but it is not possible for a Go -// application to register a SIGPROF handler, nor is it possible for a -// Go handler for some other signal to read the stack pointer of -// the interrupted thread. -// -// Two caveats: -// (1) it is tempting to send the leaf Frame directly to the profiler -// goroutine instead of making a copy of the stack, since a Frame is a -// spaghetti stack--a linked list. However, as soon as execution -// resumes, the stack's Frame.pc values may be mutated, so Frames are -// not safe to share with the asynchronous profiler goroutine. -// (2) it is tempting to use Callables as keys in a map when tabulating -// the pprof protocols's Function entities. However, we cannot assume -// that Callables are valid map keys, and furthermore we must not -// pin function values in memory indefinitely as this may cause lambda -// values to keep their free variables live much longer than necessary. - -// TODO(adonovan): -// - make Start/Stop fully thread-safe. -// - fix the pc hack. -// - experiment with other values of quantum. - -import ( - "bufio" - "bytes" - "compress/gzip" - "encoding/binary" - "fmt" - "io" - "log" - "reflect" - "sync/atomic" - "time" - "unsafe" - - "go.starlark.net/syntax" -) - -// StartProfile enables time profiling of all Starlark threads, -// and writes a profile in pprof format to w. -// It must be followed by a call to StopProfiler to stop -// the profiler and finalize the profile. -// -// StartProfile returns an error if profiling was already enabled. -// -// StartProfile must not be called concurrently with Starlark execution. -func StartProfile(w io.Writer) error { - if !atomic.CompareAndSwapUint32(&profiler.on, 0, 1) { - return fmt.Errorf("profiler already running") - } - - // TODO(adonovan): make the API fully concurrency-safe. - // The main challenge is racy reads/writes of profiler.events, - // and of send/close races on the channel it refers to. - // It's easy to solve them with a mutex but harder to do - // it efficiently. - - profiler.events = make(chan *profEvent, 1) - profiler.done = make(chan error) - - go profile(w) - - return nil -} - -// StopProfile stops the profiler started by a prior call to -// StartProfile and finalizes the profile. It returns an error if the -// profile could not be completed. -// -// StopProfile must not be called concurrently with Starlark execution. -func StopProfile() error { - // Terminate the profiler goroutine and get its result. - close(profiler.events) - err := <-profiler.done - - profiler.done = nil - profiler.events = nil - atomic.StoreUint32(&profiler.on, 0) - - return err -} - -// globals -var profiler struct { - on uint32 // nonzero => profiler running - events chan *profEvent // profile events from interpreter threads - done chan error // indicates profiler goroutine is ready -} - -func (thread *Thread) beginProfSpan() { - if profiler.events == nil { - return // profiling not enabled - } - - thread.frameAt(0).spanStart = nanotime() -} - -// TODO(adonovan): experiment with smaller values, -// which trade space and time for greater precision. -const quantum = 10 * time.Millisecond - -func (thread *Thread) endProfSpan() { - if profiler.events == nil { - return // profiling not enabled - } - - // Add the span to the thread's accumulator. - thread.proftime += time.Duration(nanotime() - thread.frameAt(0).spanStart) - if thread.proftime < quantum { - return - } - - // Only record complete quanta. - n := thread.proftime / quantum - thread.proftime -= n * quantum - - // Copy the stack. - // (We can't save thread.frame because its pc will change.) - ev := &profEvent{ - thread: thread, - time: n * quantum, - } - ev.stack = ev.stackSpace[:0] - for i := range thread.stack { - fr := thread.frameAt(i) - ev.stack = append(ev.stack, profFrame{ - pos: fr.Position(), - fn: fr.Callable(), - pc: fr.pc, - }) - } - - profiler.events <- ev -} - -type profEvent struct { - thread *Thread // currently unused - time time.Duration - stack []profFrame - stackSpace [8]profFrame // initial space for stack -} - -type profFrame struct { - fn Callable // don't hold this live for too long (prevents GC of lambdas) - pc uint32 // program counter (Starlark frames only) - pos syntax.Position // position of pc within this frame -} - -// profile is the profiler goroutine. -// It runs until StopProfiler is called. -func profile(w io.Writer) { - // Field numbers from pprof protocol. - // See https://github.com/google/pprof/blob/master/proto/profile.proto - const ( - Profile_sample_type = 1 // repeated ValueType - Profile_sample = 2 // repeated Sample - Profile_mapping = 3 // repeated Mapping - Profile_location = 4 // repeated Location - Profile_function = 5 // repeated Function - Profile_string_table = 6 // repeated string - Profile_time_nanos = 9 // int64 - Profile_duration_nanos = 10 // int64 - Profile_period_type = 11 // ValueType - Profile_period = 12 // int64 - - ValueType_type = 1 // int64 - ValueType_unit = 2 // int64 - - Sample_location_id = 1 // repeated uint64 - Sample_value = 2 // repeated int64 - Sample_label = 3 // repeated Label - - Label_key = 1 // int64 - Label_str = 2 // int64 - Label_num = 3 // int64 - Label_num_unit = 4 // int64 - - Location_id = 1 // uint64 - Location_mapping_id = 2 // uint64 - Location_address = 3 // uint64 - Location_line = 4 // repeated Line - - Line_function_id = 1 // uint64 - Line_line = 2 // int64 - - Function_id = 1 // uint64 - Function_name = 2 // int64 - Function_system_name = 3 // int64 - Function_filename = 4 // int64 - Function_start_line = 5 // int64 - ) - - bufw := bufio.NewWriter(w) // write file in 4KB (not 240B flate-sized) chunks - gz := gzip.NewWriter(bufw) - enc := protoEncoder{w: gz} - - // strings - stringIndex := make(map[string]int64) - str := func(s string) int64 { - i, ok := stringIndex[s] - if !ok { - i = int64(len(stringIndex)) - enc.string(Profile_string_table, s) - stringIndex[s] = i - } - return i - } - str("") // entry 0 - - // functions - // - // function returns the ID of a Callable for use in Line.FunctionId. - // The ID is the same as the function's logical address, - // which is supplied by the caller to avoid the need to recompute it. - functionId := make(map[uintptr]uint64) - function := func(fn Callable, addr uintptr) uint64 { - id, ok := functionId[addr] - if !ok { - id = uint64(addr) - - var pos syntax.Position - if fn, ok := fn.(callableWithPosition); ok { - pos = fn.Position() - } - - name := fn.Name() - if name == "" { - name = pos.Filename() - } - - nameIndex := str(name) - - fun := new(bytes.Buffer) - funenc := protoEncoder{w: fun} - funenc.uint(Function_id, id) - funenc.int(Function_name, nameIndex) - funenc.int(Function_system_name, nameIndex) - funenc.int(Function_filename, str(pos.Filename())) - funenc.int(Function_start_line, int64(pos.Line)) - enc.bytes(Profile_function, fun.Bytes()) - - functionId[addr] = id - } - return id - } - - // locations - // - // location returns the ID of the location denoted by fr. - // For Starlark frames, this is the Frame pc. - locationId := make(map[uintptr]uint64) - location := func(fr profFrame) uint64 { - fnAddr := profFuncAddr(fr.fn) - - // For Starlark functions, the frame position - // represents the current PC value. - // Mix it into the low bits of the address. - // This is super hacky and may result in collisions - // in large functions or if functions are numerous. - // TODO(adonovan): fix: try making this cleaner by treating - // each bytecode segment as a Profile.Mapping. - pcAddr := fnAddr - if _, ok := fr.fn.(*Function); ok { - pcAddr = (pcAddr << 16) ^ uintptr(fr.pc) - } - - id, ok := locationId[pcAddr] - if !ok { - id = uint64(pcAddr) - - line := new(bytes.Buffer) - lineenc := protoEncoder{w: line} - lineenc.uint(Line_function_id, function(fr.fn, fnAddr)) - lineenc.int(Line_line, int64(fr.pos.Line)) - loc := new(bytes.Buffer) - locenc := protoEncoder{w: loc} - locenc.uint(Location_id, id) - locenc.uint(Location_address, uint64(pcAddr)) - locenc.bytes(Location_line, line.Bytes()) - enc.bytes(Profile_location, loc.Bytes()) - - locationId[pcAddr] = id - } - return id - } - - wallNanos := new(bytes.Buffer) - wnenc := protoEncoder{w: wallNanos} - wnenc.int(ValueType_type, str("wall")) - wnenc.int(ValueType_unit, str("nanoseconds")) - - // informational fields of Profile - enc.bytes(Profile_sample_type, wallNanos.Bytes()) - enc.int(Profile_period, quantum.Nanoseconds()) // magnitude of sampling period - enc.bytes(Profile_period_type, wallNanos.Bytes()) // dimension and unit of period - enc.int(Profile_time_nanos, time.Now().UnixNano()) // start (real) time of profile - - startNano := nanotime() - - // Read profile events from the channel - // until it is closed by StopProfiler. - for e := range profiler.events { - sample := new(bytes.Buffer) - sampleenc := protoEncoder{w: sample} - sampleenc.int(Sample_value, e.time.Nanoseconds()) // wall nanoseconds - for _, fr := range e.stack { - sampleenc.uint(Sample_location_id, location(fr)) - } - enc.bytes(Profile_sample, sample.Bytes()) - } - - endNano := nanotime() - enc.int(Profile_duration_nanos, endNano-startNano) - - err := gz.Close() // Close reports any prior write error - if flushErr := bufw.Flush(); err == nil { - err = flushErr - } - profiler.done <- err -} - -// nanotime returns the time in nanoseconds since epoch. -// It is implemented by runtime.nanotime using the linkname hack; -// runtime.nanotime is defined for all OSs/ARCHS and uses the -// monotonic system clock, which there is no portable way to access. -// Should that function ever go away, these alternatives exist: -// -// // POSIX only. REALTIME not MONOTONIC. 17ns. -// var tv syscall.Timeval -// syscall.Gettimeofday(&tv) // can't fail -// return tv.Nano() -// -// // Portable. REALTIME not MONOTONIC. 46ns. -// return time.Now().Nanoseconds() -// -// // POSIX only. Adds a dependency. -// import "golang.org/x/sys/unix" -// var ts unix.Timespec -// unix.ClockGettime(CLOCK_MONOTONIC, &ts) // can't fail -// return unix.TimespecToNsec(ts) -// -//go:linkname nanotime runtime.nanotime -func nanotime() int64 - -// profFuncAddr returns the canonical "address" -// of a Callable for use by the profiler. -func profFuncAddr(fn Callable) uintptr { - switch fn := fn.(type) { - case *Builtin: - return reflect.ValueOf(fn.fn).Pointer() - case *Function: - return uintptr(unsafe.Pointer(fn.funcode)) - } - - // User-defined callable types are typically of - // of kind pointer-to-struct. Handle them specially. - if v := reflect.ValueOf(fn); v.Type().Kind() == reflect.Ptr { - return v.Pointer() - } - - // Address zero is reserved by the protocol. - // Use 1 for callables we don't recognize. - log.Printf("Starlark profiler: no address for Callable %T", fn) - return 1 -} - -// We encode the protocol message by hand to avoid making -// the interpreter depend on both github.com/google/pprof -// and github.com/golang/protobuf. -// -// This also avoids the need to materialize a protocol message object -// tree of unbounded size and serialize it all at the end. -// The pprof format appears to have been designed to -// permit streaming implementations such as this one. -// -// See https://developers.google.com/protocol-buffers/docs/encoding. -type protoEncoder struct { - w io.Writer // *bytes.Buffer or *gzip.Writer - tmp [binary.MaxVarintLen64]byte -} - -func (e *protoEncoder) uvarint(x uint64) { - n := binary.PutUvarint(e.tmp[:], x) - e.w.Write(e.tmp[:n]) -} - -func (e *protoEncoder) tag(field, wire uint) { - e.uvarint(uint64(field<<3 | wire)) -} - -func (e *protoEncoder) string(field uint, s string) { - e.tag(field, 2) // length-delimited - e.uvarint(uint64(len(s))) - io.WriteString(e.w, s) -} - -func (e *protoEncoder) bytes(field uint, b []byte) { - e.tag(field, 2) // length-delimited - e.uvarint(uint64(len(b))) - e.w.Write(b) -} - -func (e *protoEncoder) uint(field uint, x uint64) { - e.tag(field, 0) // varint - e.uvarint(x) -} - -func (e *protoEncoder) int(field uint, x int64) { - e.tag(field, 0) // varint - e.uvarint(uint64(x)) -} diff --git a/vendor/go.starlark.net/starlark/unpack.go b/vendor/go.starlark.net/starlark/unpack.go deleted file mode 100644 index 316858992..000000000 --- a/vendor/go.starlark.net/starlark/unpack.go +++ /dev/null @@ -1,355 +0,0 @@ -package starlark - -// This file defines the Unpack helper functions used by -// built-in functions to interpret their call arguments. - -import ( - "fmt" - "log" - "reflect" - "strings" - - "go.starlark.net/internal/spell" -) - -// An Unpacker defines custom argument unpacking behavior. -// See UnpackArgs. -type Unpacker interface { - Unpack(v Value) error -} - -// UnpackArgs unpacks the positional and keyword arguments into the -// supplied parameter variables. pairs is an alternating list of names -// and pointers to variables. -// -// If the variable is a bool, integer, string, *List, *Dict, Callable, -// Iterable, or user-defined implementation of Value, -// UnpackArgs performs the appropriate type check. -// Predeclared Go integer types uses the AsInt check. -// -// If the parameter name ends with "?", it is optional. -// -// If the parameter name ends with "??", it is optional and treats the None value -// as if the argument was absent. -// -// If a parameter is marked optional, then all following parameters are -// implicitly optional where or not they are marked. -// -// If the variable implements Unpacker, its Unpack argument -// is called with the argument value, allowing an application -// to define its own argument validation and conversion. -// -// If the variable implements Value, UnpackArgs may call -// its Type() method while constructing the error message. -// -// Examples: -// -// var ( -// a Value -// b = MakeInt(42) -// c Value = starlark.None -// ) -// -// // 1. mixed parameters, like def f(a, b=42, c=None). -// err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c) -// -// // 2. keyword parameters only, like def f(*, a, b, c=None). -// if len(args) > 0 { -// return fmt.Errorf("f: unexpected positional arguments") -// } -// err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c) -// -// // 3. positional parameters only, like def f(a, b=42, c=None, /) in Python 3.8. -// err := UnpackPositionalArgs("f", args, kwargs, 1, &a, &b, &c) -// -// More complex forms such as def f(a, b=42, *args, c, d=123, **kwargs) -// require additional logic, but their need in built-ins is exceedingly rare. -// -// In the examples above, the declaration of b with type Int causes UnpackArgs -// to require that b's argument value, if provided, is also an int. -// To allow arguments of any type, while retaining the default value of 42, -// declare b as a Value: -// -// var b Value = MakeInt(42) -// -// The zero value of a variable of type Value, such as 'a' in the -// examples above, is not a valid Starlark value, so if the parameter is -// optional, the caller must explicitly handle the default case by -// interpreting nil as None or some computed default. The same is true -// for the zero values of variables of type *List, *Dict, Callable, or -// Iterable. For example: -// -// // def myfunc(d=None, e=[], f={}) -// var ( -// d Value -// e *List -// f *Dict -// ) -// err := UnpackArgs("myfunc", args, kwargs, "d?", &d, "e?", &e, "f?", &f) -// if d == nil { d = None; } -// if e == nil { e = new(List); } -// if f == nil { f = new(Dict); } -// -func UnpackArgs(fnname string, args Tuple, kwargs []Tuple, pairs ...interface{}) error { - nparams := len(pairs) / 2 - var defined intset - defined.init(nparams) - - paramName := func(x interface{}) (name string, skipNone bool) { // (no free variables) - name = x.(string) - if strings.HasSuffix(name, "??") { - name = strings.TrimSuffix(name, "??") - skipNone = true - } else if name[len(name)-1] == '?' { - name = name[:len(name)-1] - } - - return name, skipNone - } - - // positional arguments - if len(args) > nparams { - return fmt.Errorf("%s: got %d arguments, want at most %d", - fnname, len(args), nparams) - } - for i, arg := range args { - defined.set(i) - name, skipNone := paramName(pairs[2*i]) - if skipNone { - if _, isNone := arg.(NoneType); isNone { - continue - } - } - if err := unpackOneArg(arg, pairs[2*i+1]); err != nil { - return fmt.Errorf("%s: for parameter %s: %s", fnname, name, err) - } - } - - // keyword arguments -kwloop: - for _, item := range kwargs { - name, arg := item[0].(String), item[1] - for i := 0; i < nparams; i++ { - pName, skipNone := paramName(pairs[2*i]) - if pName == string(name) { - // found it - if defined.set(i) { - return fmt.Errorf("%s: got multiple values for keyword argument %s", - fnname, name) - } - - if skipNone { - if _, isNone := arg.(NoneType); isNone { - continue kwloop - } - } - - ptr := pairs[2*i+1] - if err := unpackOneArg(arg, ptr); err != nil { - return fmt.Errorf("%s: for parameter %s: %s", fnname, name, err) - } - continue kwloop - } - } - err := fmt.Errorf("%s: unexpected keyword argument %s", fnname, name) - names := make([]string, 0, nparams) - for i := 0; i < nparams; i += 2 { - param, _ := paramName(pairs[i]) - names = append(names, param) - } - if n := spell.Nearest(string(name), names); n != "" { - err = fmt.Errorf("%s (did you mean %s?)", err.Error(), n) - } - return err - } - - // Check that all non-optional parameters are defined. - // (We needn't check the first len(args).) - for i := len(args); i < nparams; i++ { - name := pairs[2*i].(string) - if strings.HasSuffix(name, "?") { - break // optional - } - if !defined.get(i) { - return fmt.Errorf("%s: missing argument for %s", fnname, name) - } - } - - return nil -} - -// UnpackPositionalArgs unpacks the positional arguments into -// corresponding variables. Each element of vars is a pointer; see -// UnpackArgs for allowed types and conversions. -// -// UnpackPositionalArgs reports an error if the number of arguments is -// less than min or greater than len(vars), if kwargs is nonempty, or if -// any conversion fails. -// -// See UnpackArgs for general comments. -func UnpackPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min int, vars ...interface{}) error { - if len(kwargs) > 0 { - return fmt.Errorf("%s: unexpected keyword arguments", fnname) - } - max := len(vars) - if len(args) < min { - var atleast string - if min < max { - atleast = "at least " - } - return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atleast, min) - } - if len(args) > max { - var atmost string - if max > min { - atmost = "at most " - } - return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atmost, max) - } - for i, arg := range args { - if err := unpackOneArg(arg, vars[i]); err != nil { - return fmt.Errorf("%s: for parameter %d: %s", fnname, i+1, err) - } - } - return nil -} - -func unpackOneArg(v Value, ptr interface{}) error { - // On failure, don't clobber *ptr. - switch ptr := ptr.(type) { - case Unpacker: - return ptr.Unpack(v) - case *Value: - *ptr = v - case *string: - s, ok := AsString(v) - if !ok { - return fmt.Errorf("got %s, want string", v.Type()) - } - *ptr = s - case *bool: - b, ok := v.(Bool) - if !ok { - return fmt.Errorf("got %s, want bool", v.Type()) - } - *ptr = bool(b) - case *int, *int8, *int16, *int32, *int64, - *uint, *uint8, *uint16, *uint32, *uint64, *uintptr: - return AsInt(v, ptr) - case *float64: - f, ok := v.(Float) - if !ok { - return fmt.Errorf("got %s, want float", v.Type()) - } - *ptr = float64(f) - case **List: - list, ok := v.(*List) - if !ok { - return fmt.Errorf("got %s, want list", v.Type()) - } - *ptr = list - case **Dict: - dict, ok := v.(*Dict) - if !ok { - return fmt.Errorf("got %s, want dict", v.Type()) - } - *ptr = dict - case *Callable: - f, ok := v.(Callable) - if !ok { - return fmt.Errorf("got %s, want callable", v.Type()) - } - *ptr = f - case *Iterable: - it, ok := v.(Iterable) - if !ok { - return fmt.Errorf("got %s, want iterable", v.Type()) - } - *ptr = it - default: - // v must have type *V, where V is some subtype of starlark.Value. - ptrv := reflect.ValueOf(ptr) - if ptrv.Kind() != reflect.Ptr { - log.Panicf("internal error: not a pointer: %T", ptr) - } - paramVar := ptrv.Elem() - if !reflect.TypeOf(v).AssignableTo(paramVar.Type()) { - // The value is not assignable to the variable. - - // Detect a possible bug in the Go program that called Unpack: - // If the variable *ptr is not a subtype of Value, - // no value of v can possibly work. - if !paramVar.Type().AssignableTo(reflect.TypeOf(new(Value)).Elem()) { - log.Panicf("pointer element type does not implement Value: %T", ptr) - } - - // Report Starlark dynamic type error. - // - // We prefer the Starlark Value.Type name over - // its Go reflect.Type name, but calling the - // Value.Type method on the variable is not safe - // in general. If the variable is an interface, - // the call will fail. Even if the variable has - // a concrete type, it might not be safe to call - // Type() on a zero instance. Thus we must use - // recover. - - // Default to Go reflect.Type name - paramType := paramVar.Type().String() - - // Attempt to call Value.Type method. - func() { - defer func() { recover() }() - if typer, _ := paramVar.Interface().(interface{ Type() string }); typer != nil { - paramType = typer.Type() - } - }() - return fmt.Errorf("got %s, want %s", v.Type(), paramType) - } - paramVar.Set(reflect.ValueOf(v)) - } - return nil -} - -type intset struct { - small uint64 // bitset, used if n < 64 - large map[int]bool // set, used if n >= 64 -} - -func (is *intset) init(n int) { - if n >= 64 { - is.large = make(map[int]bool) - } -} - -func (is *intset) set(i int) (prev bool) { - if is.large == nil { - prev = is.small&(1< Hash(x) == Hash(y). - // Hash may fail if the value's type is not hashable, or if the value - // contains a non-hashable value. The hash is used only by dictionaries and - // is not exposed to the Starlark program. - Hash() (uint32, error) -} - -// A Comparable is a value that defines its own equivalence relation and -// perhaps ordered comparisons. -type Comparable interface { - Value - // CompareSameType compares one value to another of the same Type(). - // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. - // CompareSameType returns an error if an ordered comparison was - // requested for a type that does not support it. - // - // Implementations that recursively compare subcomponents of - // the value should use the CompareDepth function, not Compare, to - // avoid infinite recursion on cyclic structures. - // - // The depth parameter is used to bound comparisons of cyclic - // data structures. Implementations should decrement depth - // before calling CompareDepth and should return an error if depth - // < 1. - // - // Client code should not call this method. Instead, use the - // standalone Compare or Equals functions, which are defined for - // all pairs of operands. - CompareSameType(op syntax.Token, y Value, depth int) (bool, error) -} - -// A TotallyOrdered is a type whose values form a total order: -// if x and y are of the same TotallyOrdered type, then x must be less than y, -// greater than y, or equal to y. -// -// It is simpler than Comparable and should be preferred in new code, -// but if a type implements both interfaces, Comparable takes precedence. -type TotallyOrdered interface { - Value - // Cmp compares two values x and y of the same totally ordered type. - // It returns negative if x < y, positive if x > y, and zero if the values are equal. - // - // Implementations that recursively compare subcomponents of - // the value should use the CompareDepth function, not Cmp, to - // avoid infinite recursion on cyclic structures. - // - // The depth parameter is used to bound comparisons of cyclic - // data structures. Implementations should decrement depth - // before calling CompareDepth and should return an error if depth - // < 1. - // - // Client code should not call this method. Instead, use the - // standalone Compare or Equals functions, which are defined for - // all pairs of operands. - Cmp(y Value, depth int) (int, error) -} - -var ( - _ TotallyOrdered = Int{} - _ TotallyOrdered = Float(0) - _ Comparable = False - _ Comparable = String("") - _ Comparable = (*Dict)(nil) - _ Comparable = (*List)(nil) - _ Comparable = Tuple(nil) - _ Comparable = (*Set)(nil) -) - -// A Callable value f may be the operand of a function call, f(x). -// -// Clients should use the Call function, never the CallInternal method. -type Callable interface { - Value - Name() string - CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) -} - -type callableWithPosition interface { - Callable - Position() syntax.Position -} - -var ( - _ Callable = (*Builtin)(nil) - _ Callable = (*Function)(nil) - _ callableWithPosition = (*Function)(nil) -) - -// An Iterable abstracts a sequence of values. -// An iterable value may be iterated over by a 'for' loop or used where -// any other Starlark iterable is allowed. Unlike a Sequence, the length -// of an Iterable is not necessarily known in advance of iteration. -type Iterable interface { - Value - Iterate() Iterator // must be followed by call to Iterator.Done -} - -// A Sequence is a sequence of values of known length. -type Sequence interface { - Iterable - Len() int -} - -var ( - _ Sequence = (*Dict)(nil) - _ Sequence = (*Set)(nil) -) - -// An Indexable is a sequence of known length that supports efficient random access. -// It is not necessarily iterable. -type Indexable interface { - Value - Index(i int) Value // requires 0 <= i < Len() - Len() int -} - -// A Sliceable is a sequence that can be cut into pieces with the slice operator (x[i:j:step]). -// -// All native indexable objects are sliceable. -// This is a separate interface for backwards-compatibility. -type Sliceable interface { - Indexable - // For positive strides (step > 0), 0 <= start <= end <= n. - // For negative strides (step < 0), -1 <= end <= start < n. - // The caller must ensure that the start and end indices are valid - // and that step is non-zero. - Slice(start, end, step int) Value -} - -// A HasSetIndex is an Indexable value whose elements may be assigned (x[i] = y). -// -// The implementation should not add Len to a negative index as the -// evaluator does this before the call. -type HasSetIndex interface { - Indexable - SetIndex(index int, v Value) error -} - -var ( - _ HasSetIndex = (*List)(nil) - _ Indexable = Tuple(nil) - _ Indexable = String("") - _ Sliceable = Tuple(nil) - _ Sliceable = String("") - _ Sliceable = (*List)(nil) -) - -// An Iterator provides a sequence of values to the caller. -// -// The caller must call Done when the iterator is no longer needed. -// Operations that modify a sequence will fail if it has active iterators. -// -// Example usage: -// -// iter := iterable.Iterator() -// defer iter.Done() -// var x Value -// for iter.Next(&x) { -// ... -// } -type Iterator interface { - // If the iterator is exhausted, Next returns false. - // Otherwise it sets *p to the current element of the sequence, - // advances the iterator, and returns true. - Next(p *Value) bool - Done() -} - -// A Mapping is a mapping from keys to values, such as a dictionary. -// -// If a type satisfies both Mapping and Iterable, the iterator yields -// the keys of the mapping. -type Mapping interface { - Value - // Get returns the value corresponding to the specified key, - // or !found if the mapping does not contain the key. - // - // Get also defines the behavior of "v in mapping". - // The 'in' operator reports the 'found' component, ignoring errors. - Get(Value) (v Value, found bool, err error) -} - -// An IterableMapping is a mapping that supports key enumeration. -type IterableMapping interface { - Mapping - Iterate() Iterator // see Iterable interface - Items() []Tuple // a new slice containing all key/value pairs -} - -var _ IterableMapping = (*Dict)(nil) - -// A HasSetKey supports map update using x[k]=v syntax, like a dictionary. -type HasSetKey interface { - Mapping - SetKey(k, v Value) error -} - -var _ HasSetKey = (*Dict)(nil) - -// A HasBinary value may be used as either operand of these binary operators: -// + - * / // % in not in | & ^ << >> -// -// The Side argument indicates whether the receiver is the left or right operand. -// -// An implementation may decline to handle an operation by returning (nil, nil). -// For this reason, clients should always call the standalone Binary(op, x, y) -// function rather than calling the method directly. -type HasBinary interface { - Value - Binary(op syntax.Token, y Value, side Side) (Value, error) -} - -type Side bool - -const ( - Left Side = false - Right Side = true -) - -// A HasUnary value may be used as the operand of these unary operators: -// + - ~ -// -// An implementation may decline to handle an operation by returning (nil, nil). -// For this reason, clients should always call the standalone Unary(op, x) -// function rather than calling the method directly. -type HasUnary interface { - Value - Unary(op syntax.Token) (Value, error) -} - -// A HasAttrs value has fields or methods that may be read by a dot expression (y = x.f). -// Attribute names may be listed using the built-in 'dir' function. -// -// For implementation convenience, a result of (nil, nil) from Attr is -// interpreted as a "no such field or method" error. Implementations are -// free to return a more precise error. -type HasAttrs interface { - Value - Attr(name string) (Value, error) // returns (nil, nil) if attribute not present - AttrNames() []string // callers must not modify the result. -} - -var ( - _ HasAttrs = String("") - _ HasAttrs = new(List) - _ HasAttrs = new(Dict) - _ HasAttrs = new(Set) -) - -// A HasSetField value has fields that may be written by a dot expression (x.f = y). -// -// An implementation of SetField may return a NoSuchAttrError, -// in which case the runtime may augment the error message to -// warn of possible misspelling. -type HasSetField interface { - HasAttrs - SetField(name string, val Value) error -} - -// A NoSuchAttrError may be returned by an implementation of -// HasAttrs.Attr or HasSetField.SetField to indicate that no such field -// exists. In that case the runtime may augment the error message to -// warn of possible misspelling. -type NoSuchAttrError string - -func (e NoSuchAttrError) Error() string { return string(e) } - -// NoneType is the type of None. Its only legal value is None. -// (We represent it as a number, not struct{}, so that None may be constant.) -type NoneType byte - -const None = NoneType(0) - -func (NoneType) String() string { return "None" } -func (NoneType) Type() string { return "NoneType" } -func (NoneType) Freeze() {} // immutable -func (NoneType) Truth() Bool { return False } -func (NoneType) Hash() (uint32, error) { return 0, nil } - -// Bool is the type of a Starlark bool. -type Bool bool - -const ( - False Bool = false - True Bool = true -) - -func (b Bool) String() string { - if b { - return "True" - } else { - return "False" - } -} -func (b Bool) Type() string { return "bool" } -func (b Bool) Freeze() {} // immutable -func (b Bool) Truth() Bool { return b } -func (b Bool) Hash() (uint32, error) { return uint32(b2i(bool(b))), nil } -func (x Bool) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(Bool) - return threeway(op, b2i(bool(x))-b2i(bool(y))), nil -} - -// Float is the type of a Starlark float. -type Float float64 - -func (f Float) String() string { - var buf strings.Builder - f.format(&buf, 'g') - return buf.String() -} - -func (f Float) format(buf *strings.Builder, conv byte) { - ff := float64(f) - if !isFinite(ff) { - if math.IsInf(ff, +1) { - buf.WriteString("+inf") - } else if math.IsInf(ff, -1) { - buf.WriteString("-inf") - } else { - buf.WriteString("nan") - } - return - } - - // %g is the default format used by str. - // It uses the minimum precision to avoid ambiguity, - // and always includes a '.' or an 'e' so that the value - // is self-evidently a float, not an int. - if conv == 'g' || conv == 'G' { - s := strconv.FormatFloat(ff, conv, -1, 64) - buf.WriteString(s) - // Ensure result always has a decimal point if no exponent. - // "123" -> "123.0" - if strings.IndexByte(s, conv-'g'+'e') < 0 && strings.IndexByte(s, '.') < 0 { - buf.WriteString(".0") - } - return - } - - // %[eEfF] use 6-digit precision - buf.WriteString(strconv.FormatFloat(ff, conv, 6, 64)) -} - -func (f Float) Type() string { return "float" } -func (f Float) Freeze() {} // immutable -func (f Float) Truth() Bool { return f != 0.0 } -func (f Float) Hash() (uint32, error) { - // Equal float and int values must yield the same hash. - // TODO(adonovan): opt: if f is non-integral, and thus not equal - // to any Int, we can avoid the Int conversion and use a cheaper hash. - if isFinite(float64(f)) { - return finiteFloatToInt(f).Hash() - } - return 1618033, nil // NaN, +/-Inf -} - -func floor(f Float) Float { return Float(math.Floor(float64(f))) } - -// isFinite reports whether f represents a finite rational value. -// It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0). -func isFinite(f float64) bool { - return math.Abs(f) <= math.MaxFloat64 -} - -// Cmp implements comparison of two Float values. -// Required by the TotallyOrdered interface. -func (f Float) Cmp(v Value, depth int) (int, error) { - g := v.(Float) - return floatCmp(f, g), nil -} - -// floatCmp performs a three-valued comparison on floats, -// which are totally ordered with NaN > +Inf. -func floatCmp(x, y Float) int { - if x > y { - return +1 - } else if x < y { - return -1 - } else if x == y { - return 0 - } - - // At least one operand is NaN. - if x == x { - return -1 // y is NaN - } else if y == y { - return +1 // x is NaN - } - return 0 // both NaN -} - -func (f Float) rational() *big.Rat { return new(big.Rat).SetFloat64(float64(f)) } - -// AsFloat returns the float64 value closest to x. -// The f result is undefined if x is not a float or Int. -// The result may be infinite if x is a very large Int. -func AsFloat(x Value) (f float64, ok bool) { - switch x := x.(type) { - case Float: - return float64(x), true - case Int: - return float64(x.Float()), true - } - return 0, false -} - -func (x Float) Mod(y Float) Float { - z := Float(math.Mod(float64(x), float64(y))) - if (x < 0) != (y < 0) && z != 0 { - z += y - } - return z -} - -// Unary implements the operations +float and -float. -func (f Float) Unary(op syntax.Token) (Value, error) { - switch op { - case syntax.MINUS: - return -f, nil - case syntax.PLUS: - return +f, nil - } - return nil, nil -} - -// String is the type of a Starlark text string. -// -// A String encapsulates an an immutable sequence of bytes, -// but strings are not directly iterable. Instead, iterate -// over the result of calling one of these four methods: -// codepoints, codepoint_ords, elems, elem_ords. -// -// Strings typically contain text; use Bytes for binary strings. -// The Starlark spec defines text strings as sequences of UTF-k -// codes that encode Unicode code points. In this Go implementation, -// k=8, whereas in a Java implementation, k=16. For portability, -// operations on strings should aim to avoid assumptions about -// the value of k. -// -// Warning: the contract of the Value interface's String method is that -// it returns the value printed in Starlark notation, -// so s.String() or fmt.Sprintf("%s", s) returns a quoted string. -// Use string(s) or s.GoString() or fmt.Sprintf("%#v", s) to obtain the raw contents -// of a Starlark string as a Go string. -type String string - -func (s String) String() string { return syntax.Quote(string(s), false) } -func (s String) GoString() string { return string(s) } -func (s String) Type() string { return "string" } -func (s String) Freeze() {} // immutable -func (s String) Truth() Bool { return len(s) > 0 } -func (s String) Hash() (uint32, error) { return hashString(string(s)), nil } -func (s String) Len() int { return len(s) } // bytes -func (s String) Index(i int) Value { return s[i : i+1] } - -func (s String) Slice(start, end, step int) Value { - if step == 1 { - return s[start:end] - } - - sign := signum(step) - var str []byte - for i := start; signum(end-i) == sign; i += step { - str = append(str, s[i]) - } - return String(str) -} - -func (s String) Attr(name string) (Value, error) { return builtinAttr(s, name, stringMethods) } -func (s String) AttrNames() []string { return builtinAttrNames(stringMethods) } - -func (x String) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(String) - return threeway(op, strings.Compare(string(x), string(y))), nil -} - -func AsString(x Value) (string, bool) { v, ok := x.(String); return string(v), ok } - -// A stringElems is an iterable whose iterator yields a sequence of -// elements (bytes), either numerically or as successive substrings. -// It is an indexable sequence. -type stringElems struct { - s String - ords bool -} - -var ( - _ Iterable = (*stringElems)(nil) - _ Indexable = (*stringElems)(nil) -) - -func (si stringElems) String() string { - if si.ords { - return si.s.String() + ".elem_ords()" - } else { - return si.s.String() + ".elems()" - } -} -func (si stringElems) Type() string { return "string.elems" } -func (si stringElems) Freeze() {} // immutable -func (si stringElems) Truth() Bool { return True } -func (si stringElems) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", si.Type()) } -func (si stringElems) Iterate() Iterator { return &stringElemsIterator{si, 0} } -func (si stringElems) Len() int { return len(si.s) } -func (si stringElems) Index(i int) Value { - if si.ords { - return MakeInt(int(si.s[i])) - } else { - // TODO(adonovan): opt: preallocate canonical 1-byte strings - // to avoid interface allocation. - return si.s[i : i+1] - } -} - -type stringElemsIterator struct { - si stringElems - i int -} - -func (it *stringElemsIterator) Next(p *Value) bool { - if it.i == len(it.si.s) { - return false - } - *p = it.si.Index(it.i) - it.i++ - return true -} - -func (*stringElemsIterator) Done() {} - -// A stringCodepoints is an iterable whose iterator yields a sequence of -// Unicode code points, either numerically or as successive substrings. -// It is not indexable. -type stringCodepoints struct { - s String - ords bool -} - -var _ Iterable = (*stringCodepoints)(nil) - -func (si stringCodepoints) String() string { - if si.ords { - return si.s.String() + ".codepoint_ords()" - } else { - return si.s.String() + ".codepoints()" - } -} -func (si stringCodepoints) Type() string { return "string.codepoints" } -func (si stringCodepoints) Freeze() {} // immutable -func (si stringCodepoints) Truth() Bool { return True } -func (si stringCodepoints) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", si.Type()) } -func (si stringCodepoints) Iterate() Iterator { return &stringCodepointsIterator{si, 0} } - -type stringCodepointsIterator struct { - si stringCodepoints - i int -} - -func (it *stringCodepointsIterator) Next(p *Value) bool { - s := it.si.s[it.i:] - if s == "" { - return false - } - r, sz := utf8.DecodeRuneInString(string(s)) - if !it.si.ords { - if r == utf8.RuneError { - *p = String(r) - } else { - *p = s[:sz] - } - } else { - *p = MakeInt(int(r)) - } - it.i += sz - return true -} - -func (*stringCodepointsIterator) Done() {} - -// A Function is a function defined by a Starlark def statement or lambda expression. -// The initialization behavior of a Starlark module is also represented by a Function. -type Function struct { - funcode *compile.Funcode - module *module - defaults Tuple - freevars Tuple -} - -// A module is the dynamic counterpart to a Program. -// All functions in the same program share a module. -type module struct { - program *compile.Program - predeclared StringDict - globals []Value - constants []Value -} - -// makeGlobalDict returns a new, unfrozen StringDict containing all global -// variables so far defined in the module. -func (m *module) makeGlobalDict() StringDict { - r := make(StringDict, len(m.program.Globals)) - for i, id := range m.program.Globals { - if v := m.globals[i]; v != nil { - r[id.Name] = v - } - } - return r -} - -func (fn *Function) Name() string { return fn.funcode.Name } // "lambda" for anonymous functions -func (fn *Function) Doc() string { return fn.funcode.Doc } -func (fn *Function) Hash() (uint32, error) { return hashString(fn.funcode.Name), nil } -func (fn *Function) Freeze() { fn.defaults.Freeze(); fn.freevars.Freeze() } -func (fn *Function) String() string { return toString(fn) } -func (fn *Function) Type() string { return "function" } -func (fn *Function) Truth() Bool { return true } - -// Globals returns a new, unfrozen StringDict containing all global -// variables so far defined in the function's module. -func (fn *Function) Globals() StringDict { return fn.module.makeGlobalDict() } - -func (fn *Function) Position() syntax.Position { return fn.funcode.Pos } -func (fn *Function) NumParams() int { return fn.funcode.NumParams } -func (fn *Function) NumKwonlyParams() int { return fn.funcode.NumKwonlyParams } - -// Param returns the name and position of the ith parameter, -// where 0 <= i < NumParams(). -// The *args and **kwargs parameters are at the end -// even if there were optional parameters after *args. -func (fn *Function) Param(i int) (string, syntax.Position) { - if i >= fn.NumParams() { - panic(i) - } - id := fn.funcode.Locals[i] - return id.Name, id.Pos -} - -// ParamDefault returns the default value of the specified parameter -// (0 <= i < NumParams()), or nil if the parameter is not optional. -func (fn *Function) ParamDefault(i int) Value { - if i < 0 || i >= fn.NumParams() { - panic(i) - } - - // fn.defaults omits all required params up to the first optional param. It - // also does not include *args or **kwargs at the end. - firstOptIdx := fn.NumParams() - len(fn.defaults) - if fn.HasVarargs() { - firstOptIdx-- - } - if fn.HasKwargs() { - firstOptIdx-- - } - if i < firstOptIdx || i >= firstOptIdx+len(fn.defaults) { - return nil - } - - dflt := fn.defaults[i-firstOptIdx] - if _, ok := dflt.(mandatory); ok { - return nil - } - return dflt -} - -func (fn *Function) HasVarargs() bool { return fn.funcode.HasVarargs } -func (fn *Function) HasKwargs() bool { return fn.funcode.HasKwargs } - -// A Builtin is a function implemented in Go. -type Builtin struct { - name string - fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) - recv Value // for bound methods (e.g. "".startswith) -} - -func (b *Builtin) Name() string { return b.name } -func (b *Builtin) Freeze() { - if b.recv != nil { - b.recv.Freeze() - } -} -func (b *Builtin) Hash() (uint32, error) { - h := hashString(b.name) - if b.recv != nil { - h ^= 5521 - } - return h, nil -} -func (b *Builtin) Receiver() Value { return b.recv } -func (b *Builtin) String() string { return toString(b) } -func (b *Builtin) Type() string { return "builtin_function_or_method" } -func (b *Builtin) CallInternal(thread *Thread, args Tuple, kwargs []Tuple) (Value, error) { - return b.fn(thread, b, args, kwargs) -} -func (b *Builtin) Truth() Bool { return true } - -// NewBuiltin returns a new 'builtin_function_or_method' value with the specified name -// and implementation. It compares unequal with all other values. -func NewBuiltin(name string, fn func(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error)) *Builtin { - return &Builtin{name: name, fn: fn} -} - -// BindReceiver returns a new Builtin value representing a method -// closure, that is, a built-in function bound to a receiver value. -// -// In the example below, the value of f is the string.index -// built-in method bound to the receiver value "abc": -// -// f = "abc".index; f("a"); f("b") -// -// In the common case, the receiver is bound only during the call, -// but this still results in the creation of a temporary method closure: -// -// "abc".index("a") -func (b *Builtin) BindReceiver(recv Value) *Builtin { - return &Builtin{name: b.name, fn: b.fn, recv: recv} -} - -// A *Dict represents a Starlark dictionary. -// The zero value of Dict is a valid empty dictionary. -// If you know the exact final number of entries, -// it is more efficient to call NewDict. -type Dict struct { - ht hashtable -} - -// NewDict returns a set with initial space for -// at least size insertions before rehashing. -func NewDict(size int) *Dict { - dict := new(Dict) - dict.ht.init(size) - return dict -} - -func (d *Dict) Clear() error { return d.ht.clear() } -func (d *Dict) Delete(k Value) (v Value, found bool, err error) { return d.ht.delete(k) } -func (d *Dict) Get(k Value) (v Value, found bool, err error) { return d.ht.lookup(k) } -func (d *Dict) Items() []Tuple { return d.ht.items() } -func (d *Dict) Keys() []Value { return d.ht.keys() } -func (d *Dict) Len() int { return int(d.ht.len) } -func (d *Dict) Iterate() Iterator { return d.ht.iterate() } -func (d *Dict) SetKey(k, v Value) error { return d.ht.insert(k, v) } -func (d *Dict) String() string { return toString(d) } -func (d *Dict) Type() string { return "dict" } -func (d *Dict) Freeze() { d.ht.freeze() } -func (d *Dict) Truth() Bool { return d.Len() > 0 } -func (d *Dict) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: dict") } - -func (x *Dict) Union(y *Dict) *Dict { - z := new(Dict) - z.ht.init(x.Len()) // a lower bound - z.ht.addAll(&x.ht) // can't fail - z.ht.addAll(&y.ht) // can't fail - return z -} - -func (d *Dict) Attr(name string) (Value, error) { return builtinAttr(d, name, dictMethods) } -func (d *Dict) AttrNames() []string { return builtinAttrNames(dictMethods) } - -func (x *Dict) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(*Dict) - switch op { - case syntax.EQL: - ok, err := dictsEqual(x, y, depth) - return ok, err - case syntax.NEQ: - ok, err := dictsEqual(x, y, depth) - return !ok, err - default: - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) - } -} - -func dictsEqual(x, y *Dict, depth int) (bool, error) { - if x.Len() != y.Len() { - return false, nil - } - for e := x.ht.head; e != nil; e = e.next { - key, xval := e.key, e.value - - if yval, found, _ := y.Get(key); !found { - return false, nil - } else if eq, err := EqualDepth(xval, yval, depth-1); err != nil { - return false, err - } else if !eq { - return false, nil - } - } - return true, nil -} - -// A *List represents a Starlark list value. -type List struct { - elems []Value - frozen bool - itercount uint32 // number of active iterators (ignored if frozen) -} - -// NewList returns a list containing the specified elements. -// Callers should not subsequently modify elems. -func NewList(elems []Value) *List { return &List{elems: elems} } - -func (l *List) Freeze() { - if !l.frozen { - l.frozen = true - for _, elem := range l.elems { - elem.Freeze() - } - } -} - -// checkMutable reports an error if the list should not be mutated. -// verb+" list" should describe the operation. -func (l *List) checkMutable(verb string) error { - if l.frozen { - return fmt.Errorf("cannot %s frozen list", verb) - } - if l.itercount > 0 { - return fmt.Errorf("cannot %s list during iteration", verb) - } - return nil -} - -func (l *List) String() string { return toString(l) } -func (l *List) Type() string { return "list" } -func (l *List) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: list") } -func (l *List) Truth() Bool { return l.Len() > 0 } -func (l *List) Len() int { return len(l.elems) } -func (l *List) Index(i int) Value { return l.elems[i] } - -func (l *List) Slice(start, end, step int) Value { - if step == 1 { - elems := append([]Value{}, l.elems[start:end]...) - return NewList(elems) - } - - sign := signum(step) - var list []Value - for i := start; signum(end-i) == sign; i += step { - list = append(list, l.elems[i]) - } - return NewList(list) -} - -func (l *List) Attr(name string) (Value, error) { return builtinAttr(l, name, listMethods) } -func (l *List) AttrNames() []string { return builtinAttrNames(listMethods) } - -func (l *List) Iterate() Iterator { - if !l.frozen { - l.itercount++ - } - return &listIterator{l: l} -} - -func (x *List) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(*List) - // It's tempting to check x == y as an optimization here, - // but wrong because a list containing NaN is not equal to itself. - return sliceCompare(op, x.elems, y.elems, depth) -} - -func sliceCompare(op syntax.Token, x, y []Value, depth int) (bool, error) { - // Fast path: check length. - if len(x) != len(y) && (op == syntax.EQL || op == syntax.NEQ) { - return op == syntax.NEQ, nil - } - - // Find first element that is not equal in both lists. - for i := 0; i < len(x) && i < len(y); i++ { - if eq, err := EqualDepth(x[i], y[i], depth-1); err != nil { - return false, err - } else if !eq { - switch op { - case syntax.EQL: - return false, nil - case syntax.NEQ: - return true, nil - default: - return CompareDepth(op, x[i], y[i], depth-1) - } - } - } - - return threeway(op, len(x)-len(y)), nil -} - -type listIterator struct { - l *List - i int -} - -func (it *listIterator) Next(p *Value) bool { - if it.i < it.l.Len() { - *p = it.l.elems[it.i] - it.i++ - return true - } - return false -} - -func (it *listIterator) Done() { - if !it.l.frozen { - it.l.itercount-- - } -} - -func (l *List) SetIndex(i int, v Value) error { - if err := l.checkMutable("assign to element of"); err != nil { - return err - } - l.elems[i] = v - return nil -} - -func (l *List) Append(v Value) error { - if err := l.checkMutable("append to"); err != nil { - return err - } - l.elems = append(l.elems, v) - return nil -} - -func (l *List) Clear() error { - if err := l.checkMutable("clear"); err != nil { - return err - } - for i := range l.elems { - l.elems[i] = nil // aid GC - } - l.elems = l.elems[:0] - return nil -} - -// A Tuple represents a Starlark tuple value. -type Tuple []Value - -func (t Tuple) Len() int { return len(t) } -func (t Tuple) Index(i int) Value { return t[i] } - -func (t Tuple) Slice(start, end, step int) Value { - if step == 1 { - return t[start:end] - } - - sign := signum(step) - var tuple Tuple - for i := start; signum(end-i) == sign; i += step { - tuple = append(tuple, t[i]) - } - return tuple -} - -func (t Tuple) Iterate() Iterator { return &tupleIterator{elems: t} } -func (t Tuple) Freeze() { - for _, elem := range t { - elem.Freeze() - } -} -func (t Tuple) String() string { return toString(t) } -func (t Tuple) Type() string { return "tuple" } -func (t Tuple) Truth() Bool { return len(t) > 0 } - -func (x Tuple) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(Tuple) - return sliceCompare(op, x, y, depth) -} - -func (t Tuple) Hash() (uint32, error) { - // Use same algorithm as Python. - var x, mult uint32 = 0x345678, 1000003 - for _, elem := range t { - y, err := elem.Hash() - if err != nil { - return 0, err - } - x = x ^ y*mult - mult += 82520 + uint32(len(t)+len(t)) - } - return x, nil -} - -type tupleIterator struct{ elems Tuple } - -func (it *tupleIterator) Next(p *Value) bool { - if len(it.elems) > 0 { - *p = it.elems[0] - it.elems = it.elems[1:] - return true - } - return false -} - -func (it *tupleIterator) Done() {} - -// A Set represents a Starlark set value. -// The zero value of Set is a valid empty set. -// If you know the exact final number of elements, -// it is more efficient to call NewSet. -type Set struct { - ht hashtable // values are all None -} - -// NewSet returns a dictionary with initial space for -// at least size insertions before rehashing. -func NewSet(size int) *Set { - set := new(Set) - set.ht.init(size) - return set -} - -func (s *Set) Delete(k Value) (found bool, err error) { _, found, err = s.ht.delete(k); return } -func (s *Set) Clear() error { return s.ht.clear() } -func (s *Set) Has(k Value) (found bool, err error) { _, found, err = s.ht.lookup(k); return } -func (s *Set) Insert(k Value) error { return s.ht.insert(k, None) } -func (s *Set) Len() int { return int(s.ht.len) } -func (s *Set) Iterate() Iterator { return s.ht.iterate() } -func (s *Set) String() string { return toString(s) } -func (s *Set) Type() string { return "set" } -func (s *Set) Freeze() { s.ht.freeze() } -func (s *Set) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: set") } -func (s *Set) Truth() Bool { return s.Len() > 0 } - -func (s *Set) Attr(name string) (Value, error) { return builtinAttr(s, name, setMethods) } -func (s *Set) AttrNames() []string { return builtinAttrNames(setMethods) } - -func (x *Set) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(*Set) - switch op { - case syntax.EQL: - ok, err := setsEqual(x, y, depth) - return ok, err - case syntax.NEQ: - ok, err := setsEqual(x, y, depth) - return !ok, err - case syntax.GE: // superset - if x.Len() < y.Len() { - return false, nil - } - iter := y.Iterate() - defer iter.Done() - return x.IsSuperset(iter) - case syntax.LE: // subset - if x.Len() > y.Len() { - return false, nil - } - iter := y.Iterate() - defer iter.Done() - return x.IsSubset(iter) - case syntax.GT: // proper superset - if x.Len() <= y.Len() { - return false, nil - } - iter := y.Iterate() - defer iter.Done() - return x.IsSuperset(iter) - case syntax.LT: // proper subset - if x.Len() >= y.Len() { - return false, nil - } - iter := y.Iterate() - defer iter.Done() - return x.IsSubset(iter) - default: - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) - } -} - -func setsEqual(x, y *Set, depth int) (bool, error) { - if x.Len() != y.Len() { - return false, nil - } - for e := x.ht.head; e != nil; e = e.next { - if found, _ := y.Has(e.key); !found { - return false, nil - } - } - return true, nil -} - -func setFromIterator(iter Iterator) (*Set, error) { - var x Value - set := new(Set) - for iter.Next(&x) { - err := set.Insert(x) - if err != nil { - return set, err - } - } - return set, nil -} - -func (s *Set) clone() *Set { - set := new(Set) - for e := s.ht.head; e != nil; e = e.next { - set.Insert(e.key) // can't fail - } - return set -} - -func (s *Set) Union(iter Iterator) (Value, error) { - set := s.clone() - var x Value - for iter.Next(&x) { - if err := set.Insert(x); err != nil { - return nil, err - } - } - return set, nil -} - -func (s *Set) Difference(other Iterator) (Value, error) { - diff := s.clone() - var x Value - for other.Next(&x) { - if _, err := diff.Delete(x); err != nil { - return nil, err - } - } - return diff, nil -} - -func (s *Set) IsSuperset(other Iterator) (bool, error) { - var x Value - for other.Next(&x) { - found, err := s.Has(x) - if err != nil { - return false, err - } - if !found { - return false, nil - } - } - return true, nil -} - -func (s *Set) IsSubset(other Iterator) (bool, error) { - if count, err := s.ht.count(other); err != nil { - return false, err - } else { - return count == s.Len(), nil - } -} - -func (s *Set) Intersection(other Iterator) (Value, error) { - intersect := new(Set) - var x Value - for other.Next(&x) { - found, err := s.Has(x) - if err != nil { - return nil, err - } - if found { - err = intersect.Insert(x) - if err != nil { - return nil, err - } - } - } - return intersect, nil -} - -func (s *Set) SymmetricDifference(other Iterator) (Value, error) { - diff := s.clone() - var x Value - for other.Next(&x) { - found, err := diff.Delete(x) - if err != nil { - return nil, err - } - if !found { - diff.Insert(x) - } - } - return diff, nil -} - -// toString returns the string form of value v. -// It may be more efficient than v.String() for larger values. -func toString(v Value) string { - buf := new(strings.Builder) - writeValue(buf, v, nil) - return buf.String() -} - -// writeValue writes x to out. -// -// path is used to detect cycles. -// It contains the list of *List and *Dict values we're currently printing. -// (These are the only potentially cyclic structures.) -// Callers should generally pass nil for path. -// It is safe to re-use the same path slice for multiple calls. -func writeValue(out *strings.Builder, x Value, path []Value) { - switch x := x.(type) { - case nil: - out.WriteString("") // indicates a bug - - // These four cases are duplicates of T.String(), for efficiency. - case NoneType: - out.WriteString("None") - - case Int: - out.WriteString(x.String()) - - case Bool: - if x { - out.WriteString("True") - } else { - out.WriteString("False") - } - - case String: - out.WriteString(syntax.Quote(string(x), false)) - - case *List: - out.WriteByte('[') - if pathContains(path, x) { - out.WriteString("...") // list contains itself - } else { - for i, elem := range x.elems { - if i > 0 { - out.WriteString(", ") - } - writeValue(out, elem, append(path, x)) - } - } - out.WriteByte(']') - - case Tuple: - out.WriteByte('(') - for i, elem := range x { - if i > 0 { - out.WriteString(", ") - } - writeValue(out, elem, path) - } - if len(x) == 1 { - out.WriteByte(',') - } - out.WriteByte(')') - - case *Function: - fmt.Fprintf(out, "", x.Name()) - - case *Builtin: - if x.recv != nil { - fmt.Fprintf(out, "", x.Name(), x.recv.Type()) - } else { - fmt.Fprintf(out, "", x.Name()) - } - - case *Dict: - out.WriteByte('{') - if pathContains(path, x) { - out.WriteString("...") // dict contains itself - } else { - sep := "" - for e := x.ht.head; e != nil; e = e.next { - k, v := e.key, e.value - out.WriteString(sep) - writeValue(out, k, path) - out.WriteString(": ") - writeValue(out, v, append(path, x)) // cycle check - sep = ", " - } - } - out.WriteByte('}') - - case *Set: - out.WriteString("set([") - for e := x.ht.head; e != nil; e = e.next { - if e != x.ht.head { - out.WriteString(", ") - } - writeValue(out, e.key, path) - } - out.WriteString("])") - - default: - out.WriteString(x.String()) - } -} - -func pathContains(path []Value, x Value) bool { - for _, y := range path { - if x == y { - return true - } - } - return false -} - -// CompareLimit is the depth limit on recursive comparison operations such as == and <. -// Comparison of data structures deeper than this limit may fail. -var CompareLimit = 10 - -// Equal reports whether two Starlark values are equal. -func Equal(x, y Value) (bool, error) { - if x, ok := x.(String); ok { - return x == y, nil // fast path for an important special case - } - return EqualDepth(x, y, CompareLimit) -} - -// EqualDepth reports whether two Starlark values are equal. -// -// Recursive comparisons by implementations of Value.CompareSameType -// should use EqualDepth to prevent infinite recursion. -func EqualDepth(x, y Value, depth int) (bool, error) { - return CompareDepth(syntax.EQL, x, y, depth) -} - -// Compare compares two Starlark values. -// The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. -// Compare returns an error if an ordered comparison was -// requested for a type that does not support it. -// -// Recursive comparisons by implementations of Value.CompareSameType -// should use CompareDepth to prevent infinite recursion. -func Compare(op syntax.Token, x, y Value) (bool, error) { - return CompareDepth(op, x, y, CompareLimit) -} - -// CompareDepth compares two Starlark values. -// The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. -// CompareDepth returns an error if an ordered comparison was -// requested for a pair of values that do not support it. -// -// The depth parameter limits the maximum depth of recursion -// in cyclic data structures. -func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) { - if depth < 1 { - return false, fmt.Errorf("comparison exceeded maximum recursion depth") - } - if sameType(x, y) { - if xcomp, ok := x.(Comparable); ok { - return xcomp.CompareSameType(op, y, depth) - } - - if xcomp, ok := x.(TotallyOrdered); ok { - t, err := xcomp.Cmp(y, depth) - if err != nil { - return false, err - } - return threeway(op, t), nil - } - - // use identity comparison - switch op { - case syntax.EQL: - return x == y, nil - case syntax.NEQ: - return x != y, nil - } - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) - } - - // different types - - // int/float ordered comparisons - switch x := x.(type) { - case Int: - if y, ok := y.(Float); ok { - var cmp int - if y != y { - cmp = -1 // y is NaN - } else if !math.IsInf(float64(y), 0) { - cmp = x.rational().Cmp(y.rational()) // y is finite - } else if y > 0 { - cmp = -1 // y is +Inf - } else { - cmp = +1 // y is -Inf - } - return threeway(op, cmp), nil - } - case Float: - if y, ok := y.(Int); ok { - var cmp int - if x != x { - cmp = +1 // x is NaN - } else if !math.IsInf(float64(x), 0) { - cmp = x.rational().Cmp(y.rational()) // x is finite - } else if x > 0 { - cmp = +1 // x is +Inf - } else { - cmp = -1 // x is -Inf - } - return threeway(op, cmp), nil - } - } - - // All other values of different types compare unequal. - switch op { - case syntax.EQL: - return false, nil - case syntax.NEQ: - return true, nil - } - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) -} - -func sameType(x, y Value) bool { - return reflect.TypeOf(x) == reflect.TypeOf(y) || x.Type() == y.Type() -} - -// threeway interprets a three-way comparison value cmp (-1, 0, +1) -// as a boolean comparison (e.g. x < y). -func threeway(op syntax.Token, cmp int) bool { - switch op { - case syntax.EQL: - return cmp == 0 - case syntax.NEQ: - return cmp != 0 - case syntax.LE: - return cmp <= 0 - case syntax.LT: - return cmp < 0 - case syntax.GE: - return cmp >= 0 - case syntax.GT: - return cmp > 0 - } - panic(op) -} - -func b2i(b bool) int { - if b { - return 1 - } else { - return 0 - } -} - -// Len returns the length of a string or sequence value, -// and -1 for all others. -// -// Warning: Len(x) >= 0 does not imply Iterate(x) != nil. -// A string has a known length but is not directly iterable. -func Len(x Value) int { - switch x := x.(type) { - case String: - return x.Len() - case Indexable: - return x.Len() - case Sequence: - return x.Len() - } - return -1 -} - -// Iterate return a new iterator for the value if iterable, nil otherwise. -// If the result is non-nil, the caller must call Done when finished with it. -// -// Warning: Iterate(x) != nil does not imply Len(x) >= 0. -// Some iterables may have unknown length. -func Iterate(x Value) Iterator { - if x, ok := x.(Iterable); ok { - return x.Iterate() - } - return nil -} - -// Bytes is the type of a Starlark binary string. -// -// A Bytes encapsulates an immutable sequence of bytes. -// It is comparable, indexable, and sliceable, but not directly iterable; -// use bytes.elems() for an iterable view. -// -// In this Go implementation, the elements of 'string' and 'bytes' are -// both bytes, but in other implementations, notably Java, the elements -// of a 'string' are UTF-16 codes (Java chars). The spec abstracts text -// strings as sequences of UTF-k codes that encode Unicode code points, -// and operations that convert from text to binary incur UTF-k-to-UTF-8 -// transcoding; conversely, conversion from binary to text incurs -// UTF-8-to-UTF-k transcoding. Because k=8 for Go, these operations -// are the identity function, at least for valid encodings of text. -type Bytes string - -var ( - _ Comparable = Bytes("") - _ Sliceable = Bytes("") - _ Indexable = Bytes("") -) - -func (b Bytes) String() string { return syntax.Quote(string(b), true) } -func (b Bytes) Type() string { return "bytes" } -func (b Bytes) Freeze() {} // immutable -func (b Bytes) Truth() Bool { return len(b) > 0 } -func (b Bytes) Hash() (uint32, error) { return String(b).Hash() } -func (b Bytes) Len() int { return len(b) } -func (b Bytes) Index(i int) Value { return b[i : i+1] } - -func (b Bytes) Attr(name string) (Value, error) { return builtinAttr(b, name, bytesMethods) } -func (b Bytes) AttrNames() []string { return builtinAttrNames(bytesMethods) } - -func (b Bytes) Slice(start, end, step int) Value { - if step == 1 { - return b[start:end] - } - - sign := signum(step) - var str []byte - for i := start; signum(end-i) == sign; i += step { - str = append(str, b[i]) - } - return Bytes(str) -} - -func (x Bytes) CompareSameType(op syntax.Token, y_ Value, depth int) (bool, error) { - y := y_.(Bytes) - return threeway(op, strings.Compare(string(x), string(y))), nil -} diff --git a/vendor/go.starlark.net/starlarkstruct/module.go b/vendor/go.starlark.net/starlarkstruct/module.go deleted file mode 100644 index 735c98ae3..000000000 --- a/vendor/go.starlark.net/starlarkstruct/module.go +++ /dev/null @@ -1,43 +0,0 @@ -package starlarkstruct - -import ( - "fmt" - - "go.starlark.net/starlark" -) - -// A Module is a named collection of values, -// typically a suite of functions imported by a load statement. -// -// It differs from Struct primarily in that its string representation -// does not enumerate its fields. -type Module struct { - Name string - Members starlark.StringDict -} - -var _ starlark.HasAttrs = (*Module)(nil) - -func (m *Module) Attr(name string) (starlark.Value, error) { return m.Members[name], nil } -func (m *Module) AttrNames() []string { return m.Members.Keys() } -func (m *Module) Freeze() { m.Members.Freeze() } -func (m *Module) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", m.Type()) } -func (m *Module) String() string { return fmt.Sprintf("", m.Name) } -func (m *Module) Truth() starlark.Bool { return true } -func (m *Module) Type() string { return "module" } - -// MakeModule may be used as the implementation of a Starlark built-in -// function, module(name, **kwargs). It returns a new module with the -// specified name and members. -func MakeModule(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { - var name string - if err := starlark.UnpackPositionalArgs(b.Name(), args, nil, 1, &name); err != nil { - return nil, err - } - members := make(starlark.StringDict, len(kwargs)) - for _, kwarg := range kwargs { - k := string(kwarg[0].(starlark.String)) - members[k] = kwarg[1] - } - return &Module{name, members}, nil -} diff --git a/vendor/go.starlark.net/starlarkstruct/struct.go b/vendor/go.starlark.net/starlarkstruct/struct.go deleted file mode 100644 index ea2b1f639..000000000 --- a/vendor/go.starlark.net/starlarkstruct/struct.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2017 The Bazel 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 starlarkstruct defines the Starlark types 'struct' and -// 'module', both optional language extensions. -// -package starlarkstruct // import "go.starlark.net/starlarkstruct" - -// It is tempting to introduce a variant of Struct that is a wrapper -// around a Go struct value, for stronger typing guarantees and more -// efficient and convenient field lookup. However: -// 1) all fields of Starlark structs are optional, so we cannot represent -// them using more specific types such as String, Int, *Depset, and -// *File, as such types give no way to represent missing fields. -// 2) the efficiency gain of direct struct field access is rather -// marginal: finding the index of a field by binary searching on the -// sorted list of field names is quite fast compared to the other -// overheads. -// 3) the gains in compactness and spatial locality are also rather -// marginal: the array behind the []entry slice is (due to field name -// strings) only a factor of 2 larger than the corresponding Go struct -// would be, and, like the Go struct, requires only a single allocation. - -import ( - "fmt" - "sort" - "strings" - - "go.starlark.net/starlark" - "go.starlark.net/syntax" -) - -// Make is the implementation of a built-in function that instantiates -// an immutable struct from the specified keyword arguments. -// -// An application can add 'struct' to the Starlark environment like so: -// -// globals := starlark.StringDict{ -// "struct": starlark.NewBuiltin("struct", starlarkstruct.Make), -// } -// -func Make(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { - if len(args) > 0 { - return nil, fmt.Errorf("struct: unexpected positional arguments") - } - return FromKeywords(Default, kwargs), nil -} - -// FromKeywords returns a new struct instance whose fields are specified by the -// key/value pairs in kwargs. (Each kwargs[i][0] must be a starlark.String.) -func FromKeywords(constructor starlark.Value, kwargs []starlark.Tuple) *Struct { - if constructor == nil { - panic("nil constructor") - } - s := &Struct{ - constructor: constructor, - entries: make(entries, 0, len(kwargs)), - } - for _, kwarg := range kwargs { - k := string(kwarg[0].(starlark.String)) - v := kwarg[1] - s.entries = append(s.entries, entry{k, v}) - } - sort.Sort(s.entries) - return s -} - -// FromStringDict returns a new struct instance whose elements are those of d. -// The constructor parameter specifies the constructor; use Default for an ordinary struct. -func FromStringDict(constructor starlark.Value, d starlark.StringDict) *Struct { - if constructor == nil { - panic("nil constructor") - } - s := &Struct{ - constructor: constructor, - entries: make(entries, 0, len(d)), - } - for k, v := range d { - s.entries = append(s.entries, entry{k, v}) - } - sort.Sort(s.entries) - return s -} - -// Struct is an immutable Starlark type that maps field names to values. -// It is not iterable and does not support len. -// -// A struct has a constructor, a distinct value that identifies a class -// of structs, and which appears in the struct's string representation. -// -// Operations such as x+y fail if the constructors of the two operands -// are not equal. -// -// The default constructor, Default, is the string "struct", but -// clients may wish to 'brand' structs for their own purposes. -// The constructor value appears in the printed form of the value, -// and is accessible using the Constructor method. -// -// Use Attr to access its fields and AttrNames to enumerate them. -type Struct struct { - constructor starlark.Value - entries entries // sorted by name -} - -// Default is the default constructor for structs. -// It is merely the string "struct". -const Default = starlark.String("struct") - -type entries []entry - -func (a entries) Len() int { return len(a) } -func (a entries) Less(i, j int) bool { return a[i].name < a[j].name } -func (a entries) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type entry struct { - name string - value starlark.Value -} - -var ( - _ starlark.HasAttrs = (*Struct)(nil) - _ starlark.HasBinary = (*Struct)(nil) -) - -// ToStringDict adds a name/value entry to d for each field of the struct. -func (s *Struct) ToStringDict(d starlark.StringDict) { - for _, e := range s.entries { - d[e.name] = e.value - } -} - -func (s *Struct) String() string { - buf := new(strings.Builder) - switch constructor := s.constructor.(type) { - case starlark.String: - // NB: The Java implementation always prints struct - // even for Bazel provider instances. - buf.WriteString(constructor.GoString()) // avoid String()'s quotation - default: - buf.WriteString(s.constructor.String()) - } - buf.WriteByte('(') - for i, e := range s.entries { - if i > 0 { - buf.WriteString(", ") - } - buf.WriteString(e.name) - buf.WriteString(" = ") - buf.WriteString(e.value.String()) - } - buf.WriteByte(')') - return buf.String() -} - -// Constructor returns the constructor used to create this struct. -func (s *Struct) Constructor() starlark.Value { return s.constructor } - -func (s *Struct) Type() string { return "struct" } -func (s *Struct) Truth() starlark.Bool { return true } // even when empty -func (s *Struct) Hash() (uint32, error) { - // Same algorithm as Tuple.hash, but with different primes. - var x, m uint32 = 8731, 9839 - for _, e := range s.entries { - namehash, _ := starlark.String(e.name).Hash() - x = x ^ 3*namehash - y, err := e.value.Hash() - if err != nil { - return 0, err - } - x = x ^ y*m - m += 7349 - } - return x, nil -} -func (s *Struct) Freeze() { - for _, e := range s.entries { - e.value.Freeze() - } -} - -func (x *Struct) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) { - if y, ok := y.(*Struct); ok && op == syntax.PLUS { - if side == starlark.Right { - x, y = y, x - } - - if eq, err := starlark.Equal(x.constructor, y.constructor); err != nil { - return nil, fmt.Errorf("in %s + %s: error comparing constructors: %v", - x.constructor, y.constructor, err) - } else if !eq { - return nil, fmt.Errorf("cannot add structs of different constructors: %s + %s", - x.constructor, y.constructor) - } - - z := make(starlark.StringDict, x.len()+y.len()) - for _, e := range x.entries { - z[e.name] = e.value - } - for _, e := range y.entries { - z[e.name] = e.value - } - - return FromStringDict(x.constructor, z), nil - } - return nil, nil // unhandled -} - -// Attr returns the value of the specified field. -func (s *Struct) Attr(name string) (starlark.Value, error) { - // Binary search the entries. - // This implementation is a specialization of - // sort.Search that avoids dynamic dispatch. - n := len(s.entries) - i, j := 0, n - for i < j { - h := int(uint(i+j) >> 1) - if s.entries[h].name < name { - i = h + 1 - } else { - j = h - } - } - if i < n && s.entries[i].name == name { - return s.entries[i].value, nil - } - - var ctor string - if s.constructor != Default { - ctor = s.constructor.String() + " " - } - return nil, starlark.NoSuchAttrError( - fmt.Sprintf("%sstruct has no .%s attribute", ctor, name)) -} - -func (s *Struct) len() int { return len(s.entries) } - -// AttrNames returns a new sorted list of the struct fields. -func (s *Struct) AttrNames() []string { - names := make([]string, len(s.entries)) - for i, e := range s.entries { - names[i] = e.name - } - return names -} - -func (x *Struct) CompareSameType(op syntax.Token, y_ starlark.Value, depth int) (bool, error) { - y := y_.(*Struct) - switch op { - case syntax.EQL: - return structsEqual(x, y, depth) - case syntax.NEQ: - eq, err := structsEqual(x, y, depth) - return !eq, err - default: - return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) - } -} - -func structsEqual(x, y *Struct, depth int) (bool, error) { - if x.len() != y.len() { - return false, nil - } - - if eq, err := starlark.Equal(x.constructor, y.constructor); err != nil { - return false, fmt.Errorf("error comparing struct constructors %v and %v: %v", - x.constructor, y.constructor, err) - } else if !eq { - return false, nil - } - - for i, n := 0, x.len(); i < n; i++ { - if x.entries[i].name != y.entries[i].name { - return false, nil - } else if eq, err := starlark.EqualDepth(x.entries[i].value, y.entries[i].value, depth-1); err != nil { - return false, err - } else if !eq { - return false, nil - } - } - return true, nil -} diff --git a/vendor/go.starlark.net/syntax/grammar.txt b/vendor/go.starlark.net/syntax/grammar.txt deleted file mode 100644 index 7f5dfc811..000000000 --- a/vendor/go.starlark.net/syntax/grammar.txt +++ /dev/null @@ -1,129 +0,0 @@ - -Grammar of Starlark -================== - -File = {Statement | newline} eof . - -Statement = DefStmt | IfStmt | ForStmt | WhileStmt | SimpleStmt . - -DefStmt = 'def' identifier '(' [Parameters [',']] ')' ':' Suite . - -Parameters = Parameter {',' Parameter}. - -Parameter = identifier | identifier '=' Test | '*' | '*' identifier | '**' identifier . - -IfStmt = 'if' Test ':' Suite {'elif' Test ':' Suite} ['else' ':' Suite] . - -ForStmt = 'for' LoopVariables 'in' Expression ':' Suite . - -WhileStmt = 'while' Test ':' Suite . - -Suite = [newline indent {Statement} outdent] | SimpleStmt . - -SimpleStmt = SmallStmt {';' SmallStmt} [';'] '\n' . -# NOTE: '\n' optional at EOF - -SmallStmt = ReturnStmt - | BreakStmt | ContinueStmt | PassStmt - | AssignStmt - | ExprStmt - | LoadStmt - . - -ReturnStmt = 'return' [Expression] . -BreakStmt = 'break' . -ContinueStmt = 'continue' . -PassStmt = 'pass' . -AssignStmt = Expression ('=' | '+=' | '-=' | '*=' | '/=' | '//=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=') Expression . -ExprStmt = Expression . - -LoadStmt = 'load' '(' string {',' [identifier '='] string} [','] ')' . - -Test = LambdaExpr - | IfExpr - | PrimaryExpr - | UnaryExpr - | BinaryExpr - . - -LambdaExpr = 'lambda' [Parameters] ':' Test . - -IfExpr = Test 'if' Test 'else' Test . - -PrimaryExpr = Operand - | PrimaryExpr DotSuffix - | PrimaryExpr CallSuffix - | PrimaryExpr SliceSuffix - . - -Operand = identifier - | int | float | string - | ListExpr | ListComp - | DictExpr | DictComp - | '(' [Expression [',']] ')' - | ('-' | '+') PrimaryExpr - . - -DotSuffix = '.' identifier . -CallSuffix = '(' [Arguments [',']] ')' . -SliceSuffix = '[' [Expression] [':' Test [':' Test]] ']' . - -Arguments = Argument {',' Argument} . -Argument = Test | identifier '=' Test | '*' Test | '**' Test . - -ListExpr = '[' [Expression [',']] ']' . -ListComp = '[' Test {CompClause} ']'. - -DictExpr = '{' [Entries [',']] '}' . -DictComp = '{' Entry {CompClause} '}' . -Entries = Entry {',' Entry} . -Entry = Test ':' Test . - -CompClause = 'for' LoopVariables 'in' Test | 'if' Test . - -UnaryExpr = 'not' Test . - -BinaryExpr = Test {Binop Test} . - -Binop = 'or' - | 'and' - | '==' | '!=' | '<' | '>' | '<=' | '>=' | 'in' | 'not' 'in' - | '|' - | '^' - | '&' - | '-' | '+' - | '*' | '%' | '/' | '//' - . - -Expression = Test {',' Test} . -# NOTE: trailing comma permitted only when within [...] or (...). - -LoopVariables = PrimaryExpr {',' PrimaryExpr} . - - -# Notation (similar to Go spec): -- lowercase and 'quoted' items are lexical tokens. -- Capitalized names denote grammar productions. -- (...) implies grouping -- x | y means either x or y. -- [x] means x is optional -- {x} means x is repeated zero or more times -- The end of each declaration is marked with a period. - -# Tokens -- spaces: newline, eof, indent, outdent. -- identifier. -- literals: string, int, float. -- plus all quoted tokens such as '+=', 'return'. - -# Notes: -- Ambiguity is resolved using operator precedence. -- The grammar does not enforce the legal order of params and args, - nor that the first compclause must be a 'for'. - -TODO: -- explain how the lexer generates indent, outdent, and newline tokens. -- why is unary NOT separated from unary - and +? -- the grammar is (mostly) in LL(1) style so, for example, - dot expressions are formed suffixes, not complete expressions, - which makes the spec harder to read. Reorganize into non-LL(1) form? diff --git a/vendor/go.starlark.net/syntax/options.go b/vendor/go.starlark.net/syntax/options.go deleted file mode 100644 index 51b263823..000000000 --- a/vendor/go.starlark.net/syntax/options.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2023 The Bazel 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 syntax - -import _ "unsafe" // for linkname - -// FileOptions specifies various per-file options that affect static -// aspects of an individual file such as parsing, name resolution, and -// code generation. (Options that affect global dynamics are typically -// controlled through [starlark.Thread].) -// -// The zero value of FileOptions is the default behavior. -// -// Many functions in this package come in two versions: the legacy -// standalone function (such as [Parse]) uses [LegacyFileOptions], -// whereas the more recent method (such as [Options.Parse]) honors the -// provided options. The second form is preferred. In other packages, -// the modern version is a standalone function with a leading -// FileOptions parameter and the name suffix "Options", such as -// [starlark.ExecFileOptions]. -type FileOptions struct { - // resolver - Set bool // allow references to the 'set' built-in function - While bool // allow 'while' statements - TopLevelControl bool // allow if/for/while statements at top-level - GlobalReassign bool // allow reassignment to top-level names - LoadBindsGlobally bool // load creates global not file-local bindings (deprecated) - - // compiler - Recursion bool // disable recursion check for functions in this file -} - -// TODO(adonovan): provide a canonical flag parser for FileOptions. -// (And use it in the testdata "options:" strings.) - -// LegacyFileOptions returns a new FileOptions containing the current -// values of the resolver package's legacy global variables such as -// [resolve.AllowRecursion], etc. -// These variables may be associated with command-line flags. -func LegacyFileOptions() *FileOptions { - return &FileOptions{ - Set: resolverAllowSet, - While: resolverAllowGlobalReassign, - TopLevelControl: resolverAllowGlobalReassign, - GlobalReassign: resolverAllowGlobalReassign, - Recursion: resolverAllowRecursion, - LoadBindsGlobally: resolverLoadBindsGlobally, - } -} - -// Access resolver (legacy) flags, if they are linked in; false otherwise. -var ( - //go:linkname resolverAllowSet go.starlark.net/resolve.AllowSet - resolverAllowSet bool - //go:linkname resolverAllowGlobalReassign go.starlark.net/resolve.AllowGlobalReassign - resolverAllowGlobalReassign bool - //go:linkname resolverAllowRecursion go.starlark.net/resolve.AllowRecursion - resolverAllowRecursion bool - //go:linkname resolverLoadBindsGlobally go.starlark.net/resolve.LoadBindsGlobally - resolverLoadBindsGlobally bool -) diff --git a/vendor/go.starlark.net/syntax/parse.go b/vendor/go.starlark.net/syntax/parse.go deleted file mode 100644 index 1183a03bf..000000000 --- a/vendor/go.starlark.net/syntax/parse.go +++ /dev/null @@ -1,1057 +0,0 @@ -// Copyright 2017 The Bazel 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 syntax - -// This file defines a recursive-descent parser for Starlark. -// The LL(1) grammar of Starlark and the names of many productions follow Python 2.7. -// -// TODO(adonovan): use syntax.Error more systematically throughout the -// package. Verify that error positions are correct using the -// chunkedfile mechanism. - -import "log" - -// Enable this flag to print the token stream and log.Fatal on the first error. -const debug = false - -// A Mode value is a set of flags (or 0) that controls optional parser functionality. -type Mode uint - -const ( - RetainComments Mode = 1 << iota // retain comments in AST; see Node.Comments -) - -// Parse calls the Parse method of LegacyFileOptions(). -// Deprecated: relies on legacy global variables. -func Parse(filename string, src interface{}, mode Mode) (f *File, err error) { - return LegacyFileOptions().Parse(filename, src, mode) -} - -// Parse parses the input data and returns the corresponding parse tree. -// -// If src != nil, Parse parses the source from src and the filename -// is only used when recording position information. -// The type of the argument for the src parameter must be string, -// []byte, io.Reader, or FilePortion. -// If src == nil, Parse parses the file specified by filename. -func (opts *FileOptions) Parse(filename string, src interface{}, mode Mode) (f *File, err error) { - in, err := newScanner(filename, src, mode&RetainComments != 0) - if err != nil { - return nil, err - } - p := parser{options: opts, in: in} - defer p.in.recover(&err) - - p.nextToken() // read first lookahead token - f = p.parseFile() - if f != nil { - f.Path = filename - } - p.assignComments(f) - return f, nil -} - -// ParseCompoundStmt calls the ParseCompoundStmt method of LegacyFileOptions(). -// Deprecated: relies on legacy global variables. -func ParseCompoundStmt(filename string, readline func() ([]byte, error)) (f *File, err error) { - return LegacyFileOptions().ParseCompoundStmt(filename, readline) -} - -// ParseCompoundStmt parses a single compound statement: -// a blank line, a def, for, while, or if statement, or a -// semicolon-separated list of simple statements followed -// by a newline. These are the units on which the REPL operates. -// ParseCompoundStmt does not consume any following input. -// The parser calls the readline function each -// time it needs a new line of input. -func (opts *FileOptions) ParseCompoundStmt(filename string, readline func() ([]byte, error)) (f *File, err error) { - in, err := newScanner(filename, readline, false) - if err != nil { - return nil, err - } - - p := parser{options: opts, in: in} - defer p.in.recover(&err) - - p.nextToken() // read first lookahead token - - var stmts []Stmt - switch p.tok { - case DEF, IF, FOR, WHILE: - stmts = p.parseStmt(stmts) - case NEWLINE: - // blank line - default: - stmts = p.parseSimpleStmt(stmts, false) - // Require but don't consume newline, to avoid blocking again. - if p.tok != NEWLINE { - p.in.errorf(p.in.pos, "invalid syntax") - } - } - - return &File{Options: opts, Path: filename, Stmts: stmts}, nil -} - -// ParseExpr calls the ParseExpr method of LegacyFileOptions(). -// Deprecated: relies on legacy global variables. -func ParseExpr(filename string, src interface{}, mode Mode) (expr Expr, err error) { - return LegacyFileOptions().ParseExpr(filename, src, mode) -} - -// ParseExpr parses a Starlark expression. -// A comma-separated list of expressions is parsed as a tuple. -// See Parse for explanation of parameters. -func (opts *FileOptions) ParseExpr(filename string, src interface{}, mode Mode) (expr Expr, err error) { - in, err := newScanner(filename, src, mode&RetainComments != 0) - if err != nil { - return nil, err - } - p := parser{options: opts, in: in} - defer p.in.recover(&err) - - p.nextToken() // read first lookahead token - - // Use parseExpr, not parseTest, to permit an unparenthesized tuple. - expr = p.parseExpr(false) - - // A following newline (e.g. "f()\n") appears outside any brackets, - // on a non-blank line, and thus results in a NEWLINE token. - if p.tok == NEWLINE { - p.nextToken() - } - - if p.tok != EOF { - p.in.errorf(p.in.pos, "got %#v after expression, want EOF", p.tok) - } - p.assignComments(expr) - return expr, nil -} - -type parser struct { - options *FileOptions - in *scanner - tok Token - tokval tokenValue -} - -// nextToken advances the scanner and returns the position of the -// previous token. -func (p *parser) nextToken() Position { - oldpos := p.tokval.pos - p.tok = p.in.nextToken(&p.tokval) - // enable to see the token stream - if debug { - log.Printf("nextToken: %-20s%+v\n", p.tok, p.tokval.pos) - } - return oldpos -} - -// file_input = (NEWLINE | stmt)* EOF -func (p *parser) parseFile() *File { - var stmts []Stmt - for p.tok != EOF { - if p.tok == NEWLINE { - p.nextToken() - continue - } - stmts = p.parseStmt(stmts) - } - return &File{Options: p.options, Stmts: stmts} -} - -func (p *parser) parseStmt(stmts []Stmt) []Stmt { - if p.tok == DEF { - return append(stmts, p.parseDefStmt()) - } else if p.tok == IF { - return append(stmts, p.parseIfStmt()) - } else if p.tok == FOR { - return append(stmts, p.parseForStmt()) - } else if p.tok == WHILE { - return append(stmts, p.parseWhileStmt()) - } - return p.parseSimpleStmt(stmts, true) -} - -func (p *parser) parseDefStmt() Stmt { - defpos := p.nextToken() // consume DEF - id := p.parseIdent() - lparen := p.consume(LPAREN) - params := p.parseParams() - rparen := p.consume(RPAREN) - p.consume(COLON) - body := p.parseSuite() - return &DefStmt{ - Def: defpos, - Name: id, - Lparen: lparen, - Params: params, - Rparen: rparen, - Body: body, - } -} - -func (p *parser) parseIfStmt() Stmt { - ifpos := p.nextToken() // consume IF - cond := p.parseTest() - p.consume(COLON) - body := p.parseSuite() - ifStmt := &IfStmt{ - If: ifpos, - Cond: cond, - True: body, - } - tail := ifStmt - for p.tok == ELIF { - elifpos := p.nextToken() // consume ELIF - cond := p.parseTest() - p.consume(COLON) - body := p.parseSuite() - elif := &IfStmt{ - If: elifpos, - Cond: cond, - True: body, - } - tail.ElsePos = elifpos - tail.False = []Stmt{elif} - tail = elif - } - if p.tok == ELSE { - tail.ElsePos = p.nextToken() // consume ELSE - p.consume(COLON) - tail.False = p.parseSuite() - } - return ifStmt -} - -func (p *parser) parseForStmt() Stmt { - forpos := p.nextToken() // consume FOR - vars := p.parseForLoopVariables() - p.consume(IN) - x := p.parseExpr(false) - p.consume(COLON) - body := p.parseSuite() - return &ForStmt{ - For: forpos, - Vars: vars, - X: x, - Body: body, - } -} - -func (p *parser) parseWhileStmt() Stmt { - whilepos := p.nextToken() // consume WHILE - cond := p.parseTest() - p.consume(COLON) - body := p.parseSuite() - return &WhileStmt{ - While: whilepos, - Cond: cond, - Body: body, - } -} - -// Equivalent to 'exprlist' production in Python grammar. -// -// loop_variables = primary_with_suffix (COMMA primary_with_suffix)* COMMA? -func (p *parser) parseForLoopVariables() Expr { - // Avoid parseExpr because it would consume the IN token - // following x in "for x in y: ...". - v := p.parsePrimaryWithSuffix() - if p.tok != COMMA { - return v - } - - list := []Expr{v} - for p.tok == COMMA { - p.nextToken() - if terminatesExprList(p.tok) { - break - } - list = append(list, p.parsePrimaryWithSuffix()) - } - return &TupleExpr{List: list} -} - -// simple_stmt = small_stmt (SEMI small_stmt)* SEMI? NEWLINE -// In REPL mode, it does not consume the NEWLINE. -func (p *parser) parseSimpleStmt(stmts []Stmt, consumeNL bool) []Stmt { - for { - stmts = append(stmts, p.parseSmallStmt()) - if p.tok != SEMI { - break - } - p.nextToken() // consume SEMI - if p.tok == NEWLINE || p.tok == EOF { - break - } - } - // EOF without NEWLINE occurs in `if x: pass`, for example. - if p.tok != EOF && consumeNL { - p.consume(NEWLINE) - } - - return stmts -} - -// small_stmt = RETURN expr? -// -// | PASS | BREAK | CONTINUE -// | LOAD ... -// | expr ('=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=') expr // assign -// | expr -func (p *parser) parseSmallStmt() Stmt { - switch p.tok { - case RETURN: - pos := p.nextToken() // consume RETURN - var result Expr - if p.tok != EOF && p.tok != NEWLINE && p.tok != SEMI { - result = p.parseExpr(false) - } - return &ReturnStmt{Return: pos, Result: result} - - case BREAK, CONTINUE, PASS: - tok := p.tok - pos := p.nextToken() // consume it - return &BranchStmt{Token: tok, TokenPos: pos} - - case LOAD: - return p.parseLoadStmt() - } - - // Assignment - x := p.parseExpr(false) - switch p.tok { - case EQ, PLUS_EQ, MINUS_EQ, STAR_EQ, SLASH_EQ, SLASHSLASH_EQ, PERCENT_EQ, AMP_EQ, PIPE_EQ, CIRCUMFLEX_EQ, LTLT_EQ, GTGT_EQ: - op := p.tok - pos := p.nextToken() // consume op - rhs := p.parseExpr(false) - return &AssignStmt{OpPos: pos, Op: op, LHS: x, RHS: rhs} - } - - // Expression statement (e.g. function call, doc string). - return &ExprStmt{X: x} -} - -// stmt = LOAD '(' STRING {',' (IDENT '=')? STRING} [','] ')' -func (p *parser) parseLoadStmt() *LoadStmt { - loadPos := p.nextToken() // consume LOAD - lparen := p.consume(LPAREN) - - if p.tok != STRING { - p.in.errorf(p.in.pos, "first operand of load statement must be a string literal") - } - module := p.parsePrimary().(*Literal) - - var from, to []*Ident - for p.tok != RPAREN && p.tok != EOF { - p.consume(COMMA) - if p.tok == RPAREN { - break // allow trailing comma - } - switch p.tok { - case STRING: - // load("module", "id") - // To name is same as original. - lit := p.parsePrimary().(*Literal) - id := &Ident{ - NamePos: lit.TokenPos.add(`"`), - Name: lit.Value.(string), - } - to = append(to, id) - from = append(from, id) - - case IDENT: - // load("module", to="from") - id := p.parseIdent() - to = append(to, id) - if p.tok != EQ { - p.in.errorf(p.in.pos, `load operand must be "%[1]s" or %[1]s="originalname" (want '=' after %[1]s)`, id.Name) - } - p.consume(EQ) - if p.tok != STRING { - p.in.errorf(p.in.pos, `original name of loaded symbol must be quoted: %s="originalname"`, id.Name) - } - lit := p.parsePrimary().(*Literal) - from = append(from, &Ident{ - NamePos: lit.TokenPos.add(`"`), - Name: lit.Value.(string), - }) - - case RPAREN: - p.in.errorf(p.in.pos, "trailing comma in load statement") - - default: - p.in.errorf(p.in.pos, `load operand must be "name" or localname="name" (got %#v)`, p.tok) - } - } - rparen := p.consume(RPAREN) - - if len(to) == 0 { - p.in.errorf(lparen, "load statement must import at least 1 symbol") - } - return &LoadStmt{ - Load: loadPos, - Module: module, - To: to, - From: from, - Rparen: rparen, - } -} - -// suite is typically what follows a COLON (e.g. after DEF or FOR). -// suite = simple_stmt | NEWLINE INDENT stmt+ OUTDENT -func (p *parser) parseSuite() []Stmt { - if p.tok == NEWLINE { - p.nextToken() // consume NEWLINE - p.consume(INDENT) - var stmts []Stmt - for p.tok != OUTDENT && p.tok != EOF { - stmts = p.parseStmt(stmts) - } - p.consume(OUTDENT) - return stmts - } - - return p.parseSimpleStmt(nil, true) -} - -func (p *parser) parseIdent() *Ident { - if p.tok != IDENT { - p.in.error(p.in.pos, "not an identifier") - } - id := &Ident{ - NamePos: p.tokval.pos, - Name: p.tokval.raw, - } - p.nextToken() - return id -} - -func (p *parser) consume(t Token) Position { - if p.tok != t { - p.in.errorf(p.in.pos, "got %#v, want %#v", p.tok, t) - } - return p.nextToken() -} - -// params = (param COMMA)* param COMMA? -// -// | -// -// param = IDENT -// -// | IDENT EQ test -// | STAR -// | STAR IDENT -// | STARSTAR IDENT -// -// parseParams parses a parameter list. The resulting expressions are of the form: -// -// *Ident x -// *Binary{Op: EQ, X: *Ident, Y: Expr} x=y -// *Unary{Op: STAR} * -// *Unary{Op: STAR, X: *Ident} *args -// *Unary{Op: STARSTAR, X: *Ident} **kwargs -func (p *parser) parseParams() []Expr { - var params []Expr - for p.tok != RPAREN && p.tok != COLON && p.tok != EOF { - if len(params) > 0 { - p.consume(COMMA) - } - if p.tok == RPAREN { - break - } - - // * or *args or **kwargs - if p.tok == STAR || p.tok == STARSTAR { - op := p.tok - pos := p.nextToken() - var x Expr - if op == STARSTAR || p.tok == IDENT { - x = p.parseIdent() - } - params = append(params, &UnaryExpr{ - OpPos: pos, - Op: op, - X: x, - }) - continue - } - - // IDENT - // IDENT = test - id := p.parseIdent() - if p.tok == EQ { // default value - eq := p.nextToken() - dflt := p.parseTest() - params = append(params, &BinaryExpr{ - X: id, - OpPos: eq, - Op: EQ, - Y: dflt, - }) - continue - } - - params = append(params, id) - } - return params -} - -// parseExpr parses an expression, possible consisting of a -// comma-separated list of 'test' expressions. -// -// In many cases we must use parseTest to avoid ambiguity such as -// f(x, y) vs. f((x, y)). -func (p *parser) parseExpr(inParens bool) Expr { - x := p.parseTest() - if p.tok != COMMA { - return x - } - - // tuple - exprs := p.parseExprs([]Expr{x}, inParens) - return &TupleExpr{List: exprs} -} - -// parseExprs parses a comma-separated list of expressions, starting with the comma. -// It is used to parse tuples and list elements. -// expr_list = (',' expr)* ','? -func (p *parser) parseExprs(exprs []Expr, allowTrailingComma bool) []Expr { - for p.tok == COMMA { - pos := p.nextToken() - if terminatesExprList(p.tok) { - if !allowTrailingComma { - p.in.error(pos, "unparenthesized tuple with trailing comma") - } - break - } - exprs = append(exprs, p.parseTest()) - } - return exprs -} - -// parseTest parses a 'test', a single-component expression. -func (p *parser) parseTest() Expr { - if p.tok == LAMBDA { - return p.parseLambda(true) - } - - x := p.parseTestPrec(0) - - // conditional expression (t IF cond ELSE f) - if p.tok == IF { - ifpos := p.nextToken() - cond := p.parseTestPrec(0) - if p.tok != ELSE { - p.in.error(ifpos, "conditional expression without else clause") - } - elsepos := p.nextToken() - else_ := p.parseTest() - return &CondExpr{If: ifpos, Cond: cond, True: x, ElsePos: elsepos, False: else_} - } - - return x -} - -// parseTestNoCond parses a a single-component expression without -// consuming a trailing 'if expr else expr'. -func (p *parser) parseTestNoCond() Expr { - if p.tok == LAMBDA { - return p.parseLambda(false) - } - return p.parseTestPrec(0) -} - -// parseLambda parses a lambda expression. -// The allowCond flag allows the body to be an 'a if b else c' conditional. -func (p *parser) parseLambda(allowCond bool) Expr { - lambda := p.nextToken() - var params []Expr - if p.tok != COLON { - params = p.parseParams() - } - p.consume(COLON) - - var body Expr - if allowCond { - body = p.parseTest() - } else { - body = p.parseTestNoCond() - } - - return &LambdaExpr{ - Lambda: lambda, - Params: params, - Body: body, - } -} - -func (p *parser) parseTestPrec(prec int) Expr { - if prec >= len(preclevels) { - return p.parsePrimaryWithSuffix() - } - - // expr = NOT expr - if p.tok == NOT && prec == int(precedence[NOT]) { - pos := p.nextToken() - x := p.parseTestPrec(prec) - return &UnaryExpr{ - OpPos: pos, - Op: NOT, - X: x, - } - } - - return p.parseBinopExpr(prec) -} - -// expr = test (OP test)* -// Uses precedence climbing; see http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm#climbing. -func (p *parser) parseBinopExpr(prec int) Expr { - x := p.parseTestPrec(prec + 1) - for first := true; ; first = false { - if p.tok == NOT { - p.nextToken() // consume NOT - // In this context, NOT must be followed by IN. - // Replace NOT IN by a single NOT_IN token. - if p.tok != IN { - p.in.errorf(p.in.pos, "got %#v, want in", p.tok) - } - p.tok = NOT_IN - } - - // Binary operator of specified precedence? - opprec := int(precedence[p.tok]) - if opprec < prec { - return x - } - - // Comparisons are non-associative. - if !first && opprec == int(precedence[EQL]) { - p.in.errorf(p.in.pos, "%s does not associate with %s (use parens)", - x.(*BinaryExpr).Op, p.tok) - } - - op := p.tok - pos := p.nextToken() - y := p.parseTestPrec(opprec + 1) - x = &BinaryExpr{OpPos: pos, Op: op, X: x, Y: y} - } -} - -// precedence maps each operator to its precedence (0-7), or -1 for other tokens. -var precedence [maxToken]int8 - -// preclevels groups operators of equal precedence. -// Comparisons are nonassociative; other binary operators associate to the left. -// Unary MINUS, unary PLUS, and TILDE have higher precedence so are handled in parsePrimary. -// See https://github.com/google/starlark-go/blob/master/doc/spec.md#binary-operators -var preclevels = [...][]Token{ - {OR}, // or - {AND}, // and - {NOT}, // not (unary) - {EQL, NEQ, LT, GT, LE, GE, IN, NOT_IN}, // == != < > <= >= in not in - {PIPE}, // | - {CIRCUMFLEX}, // ^ - {AMP}, // & - {LTLT, GTGT}, // << >> - {MINUS, PLUS}, // - - {STAR, PERCENT, SLASH, SLASHSLASH}, // * % / // -} - -func init() { - // populate precedence table - for i := range precedence { - precedence[i] = -1 - } - for level, tokens := range preclevels { - for _, tok := range tokens { - precedence[tok] = int8(level) - } - } -} - -// primary_with_suffix = primary -// -// | primary '.' IDENT -// | primary slice_suffix -// | primary call_suffix -func (p *parser) parsePrimaryWithSuffix() Expr { - x := p.parsePrimary() - for { - switch p.tok { - case DOT: - dot := p.nextToken() - id := p.parseIdent() - x = &DotExpr{Dot: dot, X: x, Name: id} - case LBRACK: - x = p.parseSliceSuffix(x) - case LPAREN: - x = p.parseCallSuffix(x) - default: - return x - } - } -} - -// slice_suffix = '[' expr? ':' expr? ':' expr? ']' -func (p *parser) parseSliceSuffix(x Expr) Expr { - lbrack := p.nextToken() - var lo, hi, step Expr - if p.tok != COLON { - y := p.parseExpr(false) - - // index x[y] - if p.tok == RBRACK { - rbrack := p.nextToken() - return &IndexExpr{X: x, Lbrack: lbrack, Y: y, Rbrack: rbrack} - } - - lo = y - } - - // slice or substring x[lo:hi:step] - if p.tok == COLON { - p.nextToken() - if p.tok != COLON && p.tok != RBRACK { - hi = p.parseTest() - } - } - if p.tok == COLON { - p.nextToken() - if p.tok != RBRACK { - step = p.parseTest() - } - } - rbrack := p.consume(RBRACK) - return &SliceExpr{X: x, Lbrack: lbrack, Lo: lo, Hi: hi, Step: step, Rbrack: rbrack} -} - -// call_suffix = '(' arg_list? ')' -func (p *parser) parseCallSuffix(fn Expr) Expr { - lparen := p.consume(LPAREN) - var rparen Position - var args []Expr - if p.tok == RPAREN { - rparen = p.nextToken() - } else { - args = p.parseArgs() - rparen = p.consume(RPAREN) - } - return &CallExpr{Fn: fn, Lparen: lparen, Args: args, Rparen: rparen} -} - -// parseArgs parses a list of actual parameter values (arguments). -// It mirrors the structure of parseParams. -// arg_list = ((arg COMMA)* arg COMMA?)? -func (p *parser) parseArgs() []Expr { - var args []Expr - for p.tok != RPAREN && p.tok != EOF { - if len(args) > 0 { - p.consume(COMMA) - } - if p.tok == RPAREN { - break - } - - // *args or **kwargs - if p.tok == STAR || p.tok == STARSTAR { - op := p.tok - pos := p.nextToken() - x := p.parseTest() - args = append(args, &UnaryExpr{ - OpPos: pos, - Op: op, - X: x, - }) - continue - } - - // We use a different strategy from Bazel here to stay within LL(1). - // Instead of looking ahead two tokens (IDENT, EQ) we parse - // 'test = test' then check that the first was an IDENT. - x := p.parseTest() - - if p.tok == EQ { - // name = value - if _, ok := x.(*Ident); !ok { - p.in.errorf(p.in.pos, "keyword argument must have form name=expr") - } - eq := p.nextToken() - y := p.parseTest() - x = &BinaryExpr{ - X: x, - OpPos: eq, - Op: EQ, - Y: y, - } - } - - args = append(args, x) - } - return args -} - -// primary = IDENT -// -// | INT | FLOAT | STRING | BYTES -// | '[' ... // list literal or comprehension -// | '{' ... // dict literal or comprehension -// | '(' ... // tuple or parenthesized expression -// | ('-'|'+'|'~') primary_with_suffix -func (p *parser) parsePrimary() Expr { - switch p.tok { - case IDENT: - return p.parseIdent() - - case INT, FLOAT, STRING, BYTES: - var val interface{} - tok := p.tok - switch tok { - case INT: - if p.tokval.bigInt != nil { - val = p.tokval.bigInt - } else { - val = p.tokval.int - } - case FLOAT: - val = p.tokval.float - case STRING, BYTES: - val = p.tokval.string - } - raw := p.tokval.raw - pos := p.nextToken() - return &Literal{Token: tok, TokenPos: pos, Raw: raw, Value: val} - - case LBRACK: - return p.parseList() - - case LBRACE: - return p.parseDict() - - case LPAREN: - lparen := p.nextToken() - if p.tok == RPAREN { - // empty tuple - rparen := p.nextToken() - return &TupleExpr{Lparen: lparen, Rparen: rparen} - } - e := p.parseExpr(true) // allow trailing comma - rparen := p.consume(RPAREN) - return &ParenExpr{ - Lparen: lparen, - X: e, - Rparen: rparen, - } - - case MINUS, PLUS, TILDE: // unary - tok := p.tok - pos := p.nextToken() - x := p.parsePrimaryWithSuffix() - return &UnaryExpr{ - OpPos: pos, - Op: tok, - X: x, - } - } - p.in.errorf(p.in.pos, "got %#v, want primary expression", p.tok) - panic("unreachable") -} - -// list = '[' ']' -// -// | '[' expr ']' -// | '[' expr expr_list ']' -// | '[' expr (FOR loop_variables IN expr)+ ']' -func (p *parser) parseList() Expr { - lbrack := p.nextToken() - if p.tok == RBRACK { - // empty List - rbrack := p.nextToken() - return &ListExpr{Lbrack: lbrack, Rbrack: rbrack} - } - - x := p.parseTest() - - if p.tok == FOR { - // list comprehension - return p.parseComprehensionSuffix(lbrack, x, RBRACK) - } - - exprs := []Expr{x} - if p.tok == COMMA { - // multi-item list literal - exprs = p.parseExprs(exprs, true) // allow trailing comma - } - - rbrack := p.consume(RBRACK) - return &ListExpr{Lbrack: lbrack, List: exprs, Rbrack: rbrack} -} - -// dict = '{' '}' -// -// | '{' dict_entry_list '}' -// | '{' dict_entry FOR loop_variables IN expr '}' -func (p *parser) parseDict() Expr { - lbrace := p.nextToken() - if p.tok == RBRACE { - // empty dict - rbrace := p.nextToken() - return &DictExpr{Lbrace: lbrace, Rbrace: rbrace} - } - - x := p.parseDictEntry() - - if p.tok == FOR { - // dict comprehension - return p.parseComprehensionSuffix(lbrace, x, RBRACE) - } - - entries := []Expr{x} - for p.tok == COMMA { - p.nextToken() - if p.tok == RBRACE { - break - } - entries = append(entries, p.parseDictEntry()) - } - - rbrace := p.consume(RBRACE) - return &DictExpr{Lbrace: lbrace, List: entries, Rbrace: rbrace} -} - -// dict_entry = test ':' test -func (p *parser) parseDictEntry() *DictEntry { - k := p.parseTest() - colon := p.consume(COLON) - v := p.parseTest() - return &DictEntry{Key: k, Colon: colon, Value: v} -} - -// comp_suffix = FOR loopvars IN expr comp_suffix -// -// | IF expr comp_suffix -// | ']' or ')' (end) -// -// There can be multiple FOR/IF clauses; the first is always a FOR. -func (p *parser) parseComprehensionSuffix(lbrace Position, body Expr, endBrace Token) Expr { - var clauses []Node - for p.tok != endBrace { - if p.tok == FOR { - pos := p.nextToken() - vars := p.parseForLoopVariables() - in := p.consume(IN) - // Following Python 3, the operand of IN cannot be: - // - a conditional expression ('x if y else z'), - // due to conflicts in Python grammar - // ('if' is used by the comprehension); - // - a lambda expression - // - an unparenthesized tuple. - x := p.parseTestPrec(0) - clauses = append(clauses, &ForClause{For: pos, Vars: vars, In: in, X: x}) - } else if p.tok == IF { - pos := p.nextToken() - cond := p.parseTestNoCond() - clauses = append(clauses, &IfClause{If: pos, Cond: cond}) - } else { - p.in.errorf(p.in.pos, "got %#v, want '%s', for, or if", p.tok, endBrace) - } - } - rbrace := p.nextToken() - - return &Comprehension{ - Curly: endBrace == RBRACE, - Lbrack: lbrace, - Body: body, - Clauses: clauses, - Rbrack: rbrace, - } -} - -func terminatesExprList(tok Token) bool { - switch tok { - case EOF, NEWLINE, EQ, RBRACE, RBRACK, RPAREN, SEMI: - return true - } - return false -} - -// Comment assignment. -// We build two lists of all subnodes, preorder and postorder. -// The preorder list is ordered by start location, with outer nodes first. -// The postorder list is ordered by end location, with outer nodes last. -// We use the preorder list to assign each whole-line comment to the syntax -// immediately following it, and we use the postorder list to assign each -// end-of-line comment to the syntax immediately preceding it. - -// flattenAST returns the list of AST nodes, both in prefix order and in postfix -// order. -func flattenAST(root Node) (pre, post []Node) { - stack := []Node{} - Walk(root, func(n Node) bool { - if n != nil { - pre = append(pre, n) - stack = append(stack, n) - } else { - post = append(post, stack[len(stack)-1]) - stack = stack[:len(stack)-1] - } - return true - }) - return pre, post -} - -// assignComments attaches comments to nearby syntax. -func (p *parser) assignComments(n Node) { - // Leave early if there are no comments - if len(p.in.lineComments)+len(p.in.suffixComments) == 0 { - return - } - - pre, post := flattenAST(n) - - // Assign line comments to syntax immediately following. - line := p.in.lineComments - for _, x := range pre { - start, _ := x.Span() - - switch x.(type) { - case *File: - continue - } - - for len(line) > 0 && !start.isBefore(line[0].Start) { - x.AllocComments() - x.Comments().Before = append(x.Comments().Before, line[0]) - line = line[1:] - } - } - - // Remaining line comments go at end of file. - if len(line) > 0 { - n.AllocComments() - n.Comments().After = append(n.Comments().After, line...) - } - - // Assign suffix comments to syntax immediately before. - suffix := p.in.suffixComments - for i := len(post) - 1; i >= 0; i-- { - x := post[i] - - // Do not assign suffix comments to file - switch x.(type) { - case *File: - continue - } - - _, end := x.Span() - if len(suffix) > 0 && end.isBefore(suffix[len(suffix)-1].Start) { - x.AllocComments() - x.Comments().Suffix = append(x.Comments().Suffix, suffix[len(suffix)-1]) - suffix = suffix[:len(suffix)-1] - } - } -} diff --git a/vendor/go.starlark.net/syntax/quote.go b/vendor/go.starlark.net/syntax/quote.go deleted file mode 100644 index 741e106ad..000000000 --- a/vendor/go.starlark.net/syntax/quote.go +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright 2017 The Bazel 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 syntax - -// Starlark quoted string utilities. - -import ( - "fmt" - "strconv" - "strings" - "unicode" - "unicode/utf8" -) - -// unesc maps single-letter chars following \ to their actual values. -var unesc = [256]byte{ - 'a': '\a', - 'b': '\b', - 'f': '\f', - 'n': '\n', - 'r': '\r', - 't': '\t', - 'v': '\v', - '\\': '\\', - '\'': '\'', - '"': '"', -} - -// esc maps escape-worthy bytes to the char that should follow \. -var esc = [256]byte{ - '\a': 'a', - '\b': 'b', - '\f': 'f', - '\n': 'n', - '\r': 'r', - '\t': 't', - '\v': 'v', - '\\': '\\', - '\'': '\'', - '"': '"', -} - -// unquote unquotes the quoted string, returning the actual -// string value, whether the original was triple-quoted, -// whether it was a byte string, and an error describing invalid input. -func unquote(quoted string) (s string, triple, isByte bool, err error) { - // Check for raw prefix: means don't interpret the inner \. - raw := false - if strings.HasPrefix(quoted, "r") { - raw = true - quoted = quoted[1:] - } - // Check for bytes prefix. - if strings.HasPrefix(quoted, "b") { - isByte = true - quoted = quoted[1:] - } - - if len(quoted) < 2 { - err = fmt.Errorf("string literal too short") - return - } - - if quoted[0] != '"' && quoted[0] != '\'' || quoted[0] != quoted[len(quoted)-1] { - err = fmt.Errorf("string literal has invalid quotes") - return - } - - // Check for triple quoted string. - quote := quoted[0] - if len(quoted) >= 6 && quoted[1] == quote && quoted[2] == quote && quoted[:3] == quoted[len(quoted)-3:] { - triple = true - quoted = quoted[3 : len(quoted)-3] - } else { - quoted = quoted[1 : len(quoted)-1] - } - - // Now quoted is the quoted data, but no quotes. - // If we're in raw mode or there are no escapes or - // carriage returns, we're done. - var unquoteChars string - if raw { - unquoteChars = "\r" - } else { - unquoteChars = "\\\r" - } - if !strings.ContainsAny(quoted, unquoteChars) { - s = quoted - return - } - - // Otherwise process quoted string. - // Each iteration processes one escape sequence along with the - // plain text leading up to it. - buf := new(strings.Builder) - for { - // Remove prefix before escape sequence. - i := strings.IndexAny(quoted, unquoteChars) - if i < 0 { - i = len(quoted) - } - buf.WriteString(quoted[:i]) - quoted = quoted[i:] - - if len(quoted) == 0 { - break - } - - // Process carriage return. - if quoted[0] == '\r' { - buf.WriteByte('\n') - if len(quoted) > 1 && quoted[1] == '\n' { - quoted = quoted[2:] - } else { - quoted = quoted[1:] - } - continue - } - - // Process escape sequence. - if len(quoted) == 1 { - err = fmt.Errorf(`truncated escape sequence \`) - return - } - - switch quoted[1] { - default: - // In Starlark, like Go, a backslash must escape something. - // (Python still treats unnecessary backslashes literally, - // but since 3.6 has emitted a deprecation warning.) - err = fmt.Errorf("invalid escape sequence \\%c", quoted[1]) - return - - case '\n': - // Ignore the escape and the line break. - quoted = quoted[2:] - - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '\'', '"': - // One-char escape. - // Escapes are allowed for both kinds of quotation - // mark, not just the kind in use. - buf.WriteByte(unesc[quoted[1]]) - quoted = quoted[2:] - - case '0', '1', '2', '3', '4', '5', '6', '7': - // Octal escape, up to 3 digits, \OOO. - n := int(quoted[1] - '0') - quoted = quoted[2:] - for i := 1; i < 3; i++ { - if len(quoted) == 0 || quoted[0] < '0' || '7' < quoted[0] { - break - } - n = n*8 + int(quoted[0]-'0') - quoted = quoted[1:] - } - if !isByte && n > 127 { - err = fmt.Errorf(`non-ASCII octal escape \%o (use \u%04X for the UTF-8 encoding of U+%04X)`, n, n, n) - return - } - if n >= 256 { - // NOTE: Python silently discards the high bit, - // so that '\541' == '\141' == 'a'. - // Let's see if we can avoid doing that in BUILD files. - err = fmt.Errorf(`invalid escape sequence \%03o`, n) - return - } - buf.WriteByte(byte(n)) - - case 'x': - // Hexadecimal escape, exactly 2 digits, \xXX. [0-127] - if len(quoted) < 4 { - err = fmt.Errorf(`truncated escape sequence %s`, quoted) - return - } - n, err1 := strconv.ParseUint(quoted[2:4], 16, 0) - if err1 != nil { - err = fmt.Errorf(`invalid escape sequence %s`, quoted[:4]) - return - } - if !isByte && n > 127 { - err = fmt.Errorf(`non-ASCII hex escape %s (use \u%04X for the UTF-8 encoding of U+%04X)`, - quoted[:4], n, n) - return - } - buf.WriteByte(byte(n)) - quoted = quoted[4:] - - case 'u', 'U': - // Unicode code point, 4 (\uXXXX) or 8 (\UXXXXXXXX) hex digits. - sz := 6 - if quoted[1] == 'U' { - sz = 10 - } - if len(quoted) < sz { - err = fmt.Errorf(`truncated escape sequence %s`, quoted) - return - } - n, err1 := strconv.ParseUint(quoted[2:sz], 16, 0) - if err1 != nil { - err = fmt.Errorf(`invalid escape sequence %s`, quoted[:sz]) - return - } - if n > unicode.MaxRune { - err = fmt.Errorf(`code point out of range: %s (max \U%08x)`, - quoted[:sz], n) - return - } - // As in Go, surrogates are disallowed. - if 0xD800 <= n && n < 0xE000 { - err = fmt.Errorf(`invalid Unicode code point U+%04X`, n) - return - } - buf.WriteRune(rune(n)) - quoted = quoted[sz:] - } - } - - s = buf.String() - return -} - -// indexByte returns the index of the first instance of b in s, or else -1. -func indexByte(s string, b byte) int { - for i := 0; i < len(s); i++ { - if s[i] == b { - return i - } - } - return -1 -} - -// Quote returns a Starlark literal that denotes s. -// If b, it returns a bytes literal. -func Quote(s string, b bool) string { - const hex = "0123456789abcdef" - var runeTmp [utf8.UTFMax]byte - - buf := make([]byte, 0, 3*len(s)/2) - if b { - buf = append(buf, 'b') - } - buf = append(buf, '"') - for width := 0; len(s) > 0; s = s[width:] { - r := rune(s[0]) - width = 1 - if r >= utf8.RuneSelf { - r, width = utf8.DecodeRuneInString(s) - } - if width == 1 && r == utf8.RuneError { - // String (!b) literals accept \xXX escapes only for ASCII, - // but we must use them here to represent invalid bytes. - // The result is not a legal literal. - buf = append(buf, `\x`...) - buf = append(buf, hex[s[0]>>4]) - buf = append(buf, hex[s[0]&0xF]) - continue - } - if r == '"' || r == '\\' { // always backslashed - buf = append(buf, '\\') - buf = append(buf, byte(r)) - continue - } - if strconv.IsPrint(r) { - n := utf8.EncodeRune(runeTmp[:], r) - buf = append(buf, runeTmp[:n]...) - continue - } - switch r { - case '\a': - buf = append(buf, `\a`...) - case '\b': - buf = append(buf, `\b`...) - case '\f': - buf = append(buf, `\f`...) - case '\n': - buf = append(buf, `\n`...) - case '\r': - buf = append(buf, `\r`...) - case '\t': - buf = append(buf, `\t`...) - case '\v': - buf = append(buf, `\v`...) - default: - switch { - case r < ' ' || r == 0x7f: - buf = append(buf, `\x`...) - buf = append(buf, hex[byte(r)>>4]) - buf = append(buf, hex[byte(r)&0xF]) - case r > utf8.MaxRune: - r = 0xFFFD - fallthrough - case r < 0x10000: - buf = append(buf, `\u`...) - for s := 12; s >= 0; s -= 4 { - buf = append(buf, hex[r>>uint(s)&0xF]) - } - default: - buf = append(buf, `\U`...) - for s := 28; s >= 0; s -= 4 { - buf = append(buf, hex[r>>uint(s)&0xF]) - } - } - } - } - buf = append(buf, '"') - return string(buf) -} diff --git a/vendor/go.starlark.net/syntax/scan.go b/vendor/go.starlark.net/syntax/scan.go deleted file mode 100644 index 95499772f..000000000 --- a/vendor/go.starlark.net/syntax/scan.go +++ /dev/null @@ -1,1124 +0,0 @@ -// Copyright 2017 The Bazel 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 syntax - -// A lexical scanner for Starlark. - -import ( - "fmt" - "io" - "log" - "math/big" - "os" - "strconv" - "strings" - "unicode" - "unicode/utf8" -) - -// A Token represents a Starlark lexical token. -type Token int8 - -const ( - ILLEGAL Token = iota - EOF - - NEWLINE - INDENT - OUTDENT - - // Tokens with values - IDENT // x - INT // 123 - FLOAT // 1.23e45 - STRING // "foo" or 'foo' or '''foo''' or r'foo' or r"foo" - BYTES // b"foo", etc - - // Punctuation - PLUS // + - MINUS // - - STAR // * - SLASH // / - SLASHSLASH // // - PERCENT // % - AMP // & - PIPE // | - CIRCUMFLEX // ^ - LTLT // << - GTGT // >> - TILDE // ~ - DOT // . - COMMA // , - EQ // = - SEMI // ; - COLON // : - LPAREN // ( - RPAREN // ) - LBRACK // [ - RBRACK // ] - LBRACE // { - RBRACE // } - LT // < - GT // > - GE // >= - LE // <= - EQL // == - NEQ // != - PLUS_EQ // += (keep order consistent with PLUS..GTGT) - MINUS_EQ // -= - STAR_EQ // *= - SLASH_EQ // /= - SLASHSLASH_EQ // //= - PERCENT_EQ // %= - AMP_EQ // &= - PIPE_EQ // |= - CIRCUMFLEX_EQ // ^= - LTLT_EQ // <<= - GTGT_EQ // >>= - STARSTAR // ** - - // Keywords - AND - BREAK - CONTINUE - DEF - ELIF - ELSE - FOR - IF - IN - LAMBDA - LOAD - NOT - NOT_IN // synthesized by parser from NOT IN - OR - PASS - RETURN - WHILE - - maxToken -) - -func (tok Token) String() string { return tokenNames[tok] } - -// GoString is like String but quotes punctuation tokens. -// Use Sprintf("%#v", tok) when constructing error messages. -func (tok Token) GoString() string { - if tok >= PLUS && tok <= STARSTAR { - return "'" + tokenNames[tok] + "'" - } - return tokenNames[tok] -} - -var tokenNames = [...]string{ - ILLEGAL: "illegal token", - EOF: "end of file", - NEWLINE: "newline", - INDENT: "indent", - OUTDENT: "outdent", - IDENT: "identifier", - INT: "int literal", - FLOAT: "float literal", - STRING: "string literal", - PLUS: "+", - MINUS: "-", - STAR: "*", - SLASH: "/", - SLASHSLASH: "//", - PERCENT: "%", - AMP: "&", - PIPE: "|", - CIRCUMFLEX: "^", - LTLT: "<<", - GTGT: ">>", - TILDE: "~", - DOT: ".", - COMMA: ",", - EQ: "=", - SEMI: ";", - COLON: ":", - LPAREN: "(", - RPAREN: ")", - LBRACK: "[", - RBRACK: "]", - LBRACE: "{", - RBRACE: "}", - LT: "<", - GT: ">", - GE: ">=", - LE: "<=", - EQL: "==", - NEQ: "!=", - PLUS_EQ: "+=", - MINUS_EQ: "-=", - STAR_EQ: "*=", - SLASH_EQ: "/=", - SLASHSLASH_EQ: "//=", - PERCENT_EQ: "%=", - AMP_EQ: "&=", - PIPE_EQ: "|=", - CIRCUMFLEX_EQ: "^=", - LTLT_EQ: "<<=", - GTGT_EQ: ">>=", - STARSTAR: "**", - AND: "and", - BREAK: "break", - CONTINUE: "continue", - DEF: "def", - ELIF: "elif", - ELSE: "else", - FOR: "for", - IF: "if", - IN: "in", - LAMBDA: "lambda", - LOAD: "load", - NOT: "not", - NOT_IN: "not in", - OR: "or", - PASS: "pass", - RETURN: "return", - WHILE: "while", -} - -// A FilePortion describes the content of a portion of a file. -// Callers may provide a FilePortion for the src argument of Parse -// when the desired initial line and column numbers are not (1, 1), -// such as when an expression is parsed from within larger file. -type FilePortion struct { - Content []byte - FirstLine, FirstCol int32 -} - -// A Position describes the location of a rune of input. -type Position struct { - file *string // filename (indirect for compactness) - Line int32 // 1-based line number; 0 if line unknown - Col int32 // 1-based column (rune) number; 0 if column unknown -} - -// IsValid reports whether the position is valid. -func (p Position) IsValid() bool { return p.file != nil } - -// Filename returns the name of the file containing this position. -func (p Position) Filename() string { - if p.file != nil { - return *p.file - } - return "" -} - -// MakePosition returns position with the specified components. -func MakePosition(file *string, line, col int32) Position { return Position{file, line, col} } - -// add returns the position at the end of s, assuming it starts at p. -func (p Position) add(s string) Position { - if n := strings.Count(s, "\n"); n > 0 { - p.Line += int32(n) - s = s[strings.LastIndex(s, "\n")+1:] - p.Col = 1 - } - p.Col += int32(utf8.RuneCountInString(s)) - return p -} - -func (p Position) String() string { - file := p.Filename() - if p.Line > 0 { - if p.Col > 0 { - return fmt.Sprintf("%s:%d:%d", file, p.Line, p.Col) - } - return fmt.Sprintf("%s:%d", file, p.Line) - } - return file -} - -func (p Position) isBefore(q Position) bool { - if p.Line != q.Line { - return p.Line < q.Line - } - return p.Col < q.Col -} - -// An scanner represents a single input file being parsed. -type scanner struct { - rest []byte // rest of input (in REPL, a line of input) - token []byte // token being scanned - pos Position // current input position - depth int // nesting of [ ] { } ( ) - indentstk []int // stack of indentation levels - dents int // number of saved INDENT (>0) or OUTDENT (<0) tokens to return - lineStart bool // after NEWLINE; convert spaces to indentation tokens - keepComments bool // accumulate comments in slice - lineComments []Comment // list of full line comments (if keepComments) - suffixComments []Comment // list of suffix comments (if keepComments) - - readline func() ([]byte, error) // read next line of input (REPL only) -} - -func newScanner(filename string, src interface{}, keepComments bool) (*scanner, error) { - var firstLine, firstCol int32 = 1, 1 - if portion, ok := src.(FilePortion); ok { - firstLine, firstCol = portion.FirstLine, portion.FirstCol - } - sc := &scanner{ - pos: MakePosition(&filename, firstLine, firstCol), - indentstk: make([]int, 1, 10), // []int{0} + spare capacity - lineStart: true, - keepComments: keepComments, - } - sc.readline, _ = src.(func() ([]byte, error)) // ParseCompoundStmt (REPL) only - if sc.readline == nil { - data, err := readSource(filename, src) - if err != nil { - return nil, err - } - sc.rest = data - } - return sc, nil -} - -func readSource(filename string, src interface{}) ([]byte, error) { - switch src := src.(type) { - case string: - return []byte(src), nil - case []byte: - return src, nil - case io.Reader: - data, err := io.ReadAll(src) - if err != nil { - err = &os.PathError{Op: "read", Path: filename, Err: err} - return nil, err - } - return data, nil - case FilePortion: - return src.Content, nil - case nil: - return os.ReadFile(filename) - default: - return nil, fmt.Errorf("invalid source: %T", src) - } -} - -// An Error describes the nature and position of a scanner or parser error. -type Error struct { - Pos Position - Msg string -} - -func (e Error) Error() string { return e.Pos.String() + ": " + e.Msg } - -// errorf is called to report an error. -// errorf does not return: it panics. -func (sc *scanner) error(pos Position, s string) { - panic(Error{pos, s}) -} - -func (sc *scanner) errorf(pos Position, format string, args ...interface{}) { - sc.error(pos, fmt.Sprintf(format, args...)) -} - -func (sc *scanner) recover(err *error) { - // The scanner and parser panic both for routine errors like - // syntax errors and for programmer bugs like array index - // errors. Turn both into error returns. Catching bug panics - // is especially important when processing many files. - switch e := recover().(type) { - case nil: - // no panic - case Error: - *err = e - default: - *err = Error{sc.pos, fmt.Sprintf("internal error: %v", e)} - if debug { - log.Fatal(*err) - } - } -} - -// eof reports whether the input has reached end of file. -func (sc *scanner) eof() bool { - return len(sc.rest) == 0 && !sc.readLine() -} - -// readLine attempts to read another line of input. -// Precondition: len(sc.rest)==0. -func (sc *scanner) readLine() bool { - if sc.readline != nil { - var err error - sc.rest, err = sc.readline() - if err != nil { - sc.errorf(sc.pos, "%v", err) // EOF or ErrInterrupt - } - return len(sc.rest) > 0 - } - return false -} - -// peekRune returns the next rune in the input without consuming it. -// Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'. -func (sc *scanner) peekRune() rune { - // TODO(adonovan): opt: measure and perhaps inline eof. - if sc.eof() { - return 0 - } - - // fast path: ASCII - if b := sc.rest[0]; b < utf8.RuneSelf { - if b == '\r' { - return '\n' - } - return rune(b) - } - - r, _ := utf8.DecodeRune(sc.rest) - return r -} - -// readRune consumes and returns the next rune in the input. -// Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'. -func (sc *scanner) readRune() rune { - // eof() has been inlined here, both to avoid a call - // and to establish len(rest)>0 to avoid a bounds check. - if len(sc.rest) == 0 { - if !sc.readLine() { - sc.error(sc.pos, "internal scanner error: readRune at EOF") - } - // Redundant, but eliminates the bounds-check below. - if len(sc.rest) == 0 { - return 0 - } - } - - // fast path: ASCII - if b := sc.rest[0]; b < utf8.RuneSelf { - r := rune(b) - sc.rest = sc.rest[1:] - if r == '\r' { - if len(sc.rest) > 0 && sc.rest[0] == '\n' { - sc.rest = sc.rest[1:] - } - r = '\n' - } - if r == '\n' { - sc.pos.Line++ - sc.pos.Col = 1 - } else { - sc.pos.Col++ - } - return r - } - - r, size := utf8.DecodeRune(sc.rest) - sc.rest = sc.rest[size:] - sc.pos.Col++ - return r -} - -// tokenValue records the position and value associated with each token. -type tokenValue struct { - raw string // raw text of token - int int64 // decoded int - bigInt *big.Int // decoded integers > int64 - float float64 // decoded float - string string // decoded string or bytes - pos Position // start position of token -} - -// startToken marks the beginning of the next input token. -// It must be followed by a call to endToken once the token has -// been consumed using readRune. -func (sc *scanner) startToken(val *tokenValue) { - sc.token = sc.rest - val.raw = "" - val.pos = sc.pos -} - -// endToken marks the end of an input token. -// It records the actual token string in val.raw if the caller -// has not done that already. -func (sc *scanner) endToken(val *tokenValue) { - if val.raw == "" { - val.raw = string(sc.token[:len(sc.token)-len(sc.rest)]) - } -} - -// nextToken is called by the parser to obtain the next input token. -// It returns the token value and sets val to the data associated with -// the token. -// -// For all our input tokens, the associated data is val.pos (the -// position where the token begins), val.raw (the input string -// corresponding to the token). For string and int tokens, the string -// and int fields additionally contain the token's interpreted value. -func (sc *scanner) nextToken(val *tokenValue) Token { - - // The following distribution of tokens guides case ordering: - // - // COMMA 27 % - // STRING 23 % - // IDENT 15 % - // EQL 11 % - // LBRACK 5.5 % - // RBRACK 5.5 % - // NEWLINE 3 % - // LPAREN 2.9 % - // RPAREN 2.9 % - // INT 2 % - // others < 1 % - // - // Although NEWLINE tokens are infrequent, and lineStart is - // usually (~97%) false on entry, skipped newlines account for - // about 50% of all iterations of the 'start' loop. - -start: - var c rune - - // Deal with leading spaces and indentation. - blank := false - savedLineStart := sc.lineStart - if sc.lineStart { - sc.lineStart = false - col := 0 - for { - c = sc.peekRune() - if c == ' ' { - col++ - sc.readRune() - } else if c == '\t' { - const tab = 8 - col += int(tab - (sc.pos.Col-1)%tab) - sc.readRune() - } else { - break - } - } - - // The third clause matches EOF. - if c == '#' || c == '\n' || c == 0 { - blank = true - } - - // Compute indentation level for non-blank lines not - // inside an expression. This is not the common case. - if !blank && sc.depth == 0 { - cur := sc.indentstk[len(sc.indentstk)-1] - if col > cur { - // indent - sc.dents++ - sc.indentstk = append(sc.indentstk, col) - } else if col < cur { - // outdent(s) - for len(sc.indentstk) > 0 && col < sc.indentstk[len(sc.indentstk)-1] { - sc.dents-- - sc.indentstk = sc.indentstk[:len(sc.indentstk)-1] // pop - } - if col != sc.indentstk[len(sc.indentstk)-1] { - sc.error(sc.pos, "unindent does not match any outer indentation level") - } - } - } - } - - // Return saved indentation tokens. - if sc.dents != 0 { - sc.startToken(val) - sc.endToken(val) - if sc.dents < 0 { - sc.dents++ - return OUTDENT - } else { - sc.dents-- - return INDENT - } - } - - // start of line proper - c = sc.peekRune() - - // Skip spaces. - for c == ' ' || c == '\t' { - sc.readRune() - c = sc.peekRune() - } - - // comment - if c == '#' { - if sc.keepComments { - sc.startToken(val) - } - // Consume up to newline (included). - for c != 0 && c != '\n' { - sc.readRune() - c = sc.peekRune() - } - if sc.keepComments { - sc.endToken(val) - if blank { - sc.lineComments = append(sc.lineComments, Comment{val.pos, val.raw}) - } else { - sc.suffixComments = append(sc.suffixComments, Comment{val.pos, val.raw}) - } - } - } - - // newline - if c == '\n' { - sc.lineStart = true - - // Ignore newlines within expressions (common case). - if sc.depth > 0 { - sc.readRune() - goto start - } - - // Ignore blank lines, except in the REPL, - // where they emit OUTDENTs and NEWLINE. - if blank { - if sc.readline == nil { - sc.readRune() - goto start - } else if len(sc.indentstk) > 1 { - sc.dents = 1 - len(sc.indentstk) - sc.indentstk = sc.indentstk[:1] - goto start - } - } - - // At top-level (not in an expression). - sc.startToken(val) - sc.readRune() - val.raw = "\n" - return NEWLINE - } - - // end of file - if c == 0 { - // Emit OUTDENTs for unfinished indentation, - // preceded by a NEWLINE if we haven't just emitted one. - if len(sc.indentstk) > 1 { - if savedLineStart { - sc.dents = 1 - len(sc.indentstk) - sc.indentstk = sc.indentstk[:1] - goto start - } else { - sc.lineStart = true - sc.startToken(val) - val.raw = "\n" - return NEWLINE - } - } - - sc.startToken(val) - sc.endToken(val) - return EOF - } - - // line continuation - if c == '\\' { - sc.readRune() - if sc.peekRune() != '\n' { - sc.errorf(sc.pos, "stray backslash in program") - } - sc.readRune() - goto start - } - - // start of the next token - sc.startToken(val) - - // comma (common case) - if c == ',' { - sc.readRune() - sc.endToken(val) - return COMMA - } - - // string literal - if c == '"' || c == '\'' { - return sc.scanString(val, c) - } - - // identifier or keyword - if isIdentStart(c) { - if (c == 'r' || c == 'b') && len(sc.rest) > 1 && (sc.rest[1] == '"' || sc.rest[1] == '\'') { - // r"..." - // b"..." - sc.readRune() - c = sc.peekRune() - return sc.scanString(val, c) - } else if c == 'r' && len(sc.rest) > 2 && sc.rest[1] == 'b' && (sc.rest[2] == '"' || sc.rest[2] == '\'') { - // rb"..." - sc.readRune() - sc.readRune() - c = sc.peekRune() - return sc.scanString(val, c) - } - - for isIdent(c) { - sc.readRune() - c = sc.peekRune() - } - sc.endToken(val) - if k, ok := keywordToken[val.raw]; ok { - return k - } - - return IDENT - } - - // brackets - switch c { - case '[', '(', '{': - sc.depth++ - sc.readRune() - sc.endToken(val) - switch c { - case '[': - return LBRACK - case '(': - return LPAREN - case '{': - return LBRACE - } - panic("unreachable") - - case ']', ')', '}': - if sc.depth == 0 { - sc.errorf(sc.pos, "unexpected %q", c) - } else { - sc.depth-- - } - sc.readRune() - sc.endToken(val) - switch c { - case ']': - return RBRACK - case ')': - return RPAREN - case '}': - return RBRACE - } - panic("unreachable") - } - - // int or float literal, or period - if isdigit(c) || c == '.' { - return sc.scanNumber(val, c) - } - - // other punctuation - defer sc.endToken(val) - switch c { - case '=', '<', '>', '!', '+', '-', '%', '/', '&', '|', '^': // possibly followed by '=' - start := sc.pos - sc.readRune() - if sc.peekRune() == '=' { - sc.readRune() - switch c { - case '<': - return LE - case '>': - return GE - case '=': - return EQL - case '!': - return NEQ - case '+': - return PLUS_EQ - case '-': - return MINUS_EQ - case '/': - return SLASH_EQ - case '%': - return PERCENT_EQ - case '&': - return AMP_EQ - case '|': - return PIPE_EQ - case '^': - return CIRCUMFLEX_EQ - } - } - switch c { - case '=': - return EQ - case '<': - if sc.peekRune() == '<' { - sc.readRune() - if sc.peekRune() == '=' { - sc.readRune() - return LTLT_EQ - } else { - return LTLT - } - } - return LT - case '>': - if sc.peekRune() == '>' { - sc.readRune() - if sc.peekRune() == '=' { - sc.readRune() - return GTGT_EQ - } else { - return GTGT - } - } - return GT - case '!': - sc.error(start, "unexpected input character '!'") - case '+': - return PLUS - case '-': - return MINUS - case '/': - if sc.peekRune() == '/' { - sc.readRune() - if sc.peekRune() == '=' { - sc.readRune() - return SLASHSLASH_EQ - } else { - return SLASHSLASH - } - } - return SLASH - case '%': - return PERCENT - case '&': - return AMP - case '|': - return PIPE - case '^': - return CIRCUMFLEX - } - panic("unreachable") - - case ':', ';', '~': // single-char tokens (except comma) - sc.readRune() - switch c { - case ':': - return COLON - case ';': - return SEMI - case '~': - return TILDE - } - panic("unreachable") - - case '*': // possibly followed by '*' or '=' - sc.readRune() - switch sc.peekRune() { - case '*': - sc.readRune() - return STARSTAR - case '=': - sc.readRune() - return STAR_EQ - } - return STAR - } - - sc.errorf(sc.pos, "unexpected input character %#q", c) - panic("unreachable") -} - -func (sc *scanner) scanString(val *tokenValue, quote rune) Token { - start := sc.pos - triple := len(sc.rest) >= 3 && sc.rest[0] == byte(quote) && sc.rest[1] == byte(quote) && sc.rest[2] == byte(quote) - sc.readRune() - - // String literals may contain escaped or unescaped newlines, - // causing them to span multiple lines (gulps) of REPL input; - // they are the only such token. Thus we cannot call endToken, - // as it assumes sc.rest is unchanged since startToken. - // Instead, buffer the token here. - // TODO(adonovan): opt: buffer only if we encounter a newline. - raw := new(strings.Builder) - - // Copy the prefix, e.g. r' or " (see startToken). - raw.Write(sc.token[:len(sc.token)-len(sc.rest)]) - - if !triple { - // single-quoted string literal - for { - if sc.eof() { - sc.error(val.pos, "unexpected EOF in string") - } - c := sc.readRune() - raw.WriteRune(c) - if c == quote { - break - } - if c == '\n' { - sc.error(val.pos, "unexpected newline in string") - } - if c == '\\' { - if sc.eof() { - sc.error(val.pos, "unexpected EOF in string") - } - c = sc.readRune() - raw.WriteRune(c) - } - } - } else { - // triple-quoted string literal - sc.readRune() - raw.WriteRune(quote) - sc.readRune() - raw.WriteRune(quote) - - quoteCount := 0 - for { - if sc.eof() { - sc.error(val.pos, "unexpected EOF in string") - } - c := sc.readRune() - raw.WriteRune(c) - if c == quote { - quoteCount++ - if quoteCount == 3 { - break - } - } else { - quoteCount = 0 - } - if c == '\\' { - if sc.eof() { - sc.error(val.pos, "unexpected EOF in string") - } - c = sc.readRune() - raw.WriteRune(c) - } - } - } - val.raw = raw.String() - - s, _, isByte, err := unquote(val.raw) - if err != nil { - sc.error(start, err.Error()) - } - val.string = s - if isByte { - return BYTES - } else { - return STRING - } -} - -func (sc *scanner) scanNumber(val *tokenValue, c rune) Token { - // https://github.com/google/starlark-go/blob/master/doc/spec.md#lexical-elements - // - // Python features not supported: - // - integer literals of >64 bits of precision - // - 123L or 123l long suffix - // - traditional octal: 0755 - // https://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals - - start := sc.pos - fraction, exponent := false, false - - if c == '.' { - // dot or start of fraction - sc.readRune() - c = sc.peekRune() - if !isdigit(c) { - sc.endToken(val) - return DOT - } - fraction = true - } else if c == '0' { - // hex, octal, binary or float - sc.readRune() - c = sc.peekRune() - - if c == '.' { - fraction = true - } else if c == 'x' || c == 'X' { - // hex - sc.readRune() - c = sc.peekRune() - if !isxdigit(c) { - sc.error(start, "invalid hex literal") - } - for isxdigit(c) { - sc.readRune() - c = sc.peekRune() - } - } else if c == 'o' || c == 'O' { - // octal - sc.readRune() - c = sc.peekRune() - if !isodigit(c) { - sc.error(sc.pos, "invalid octal literal") - } - for isodigit(c) { - sc.readRune() - c = sc.peekRune() - } - } else if c == 'b' || c == 'B' { - // binary - sc.readRune() - c = sc.peekRune() - if !isbdigit(c) { - sc.error(sc.pos, "invalid binary literal") - } - for isbdigit(c) { - sc.readRune() - c = sc.peekRune() - } - } else { - // float (or obsolete octal "0755") - allzeros, octal := true, true - for isdigit(c) { - if c != '0' { - allzeros = false - } - if c > '7' { - octal = false - } - sc.readRune() - c = sc.peekRune() - } - if c == '.' { - fraction = true - } else if c == 'e' || c == 'E' { - exponent = true - } else if octal && !allzeros { - sc.endToken(val) - sc.errorf(sc.pos, "obsolete form of octal literal; use 0o%s", val.raw[1:]) - } - } - } else { - // decimal - for isdigit(c) { - sc.readRune() - c = sc.peekRune() - } - - if c == '.' { - fraction = true - } else if c == 'e' || c == 'E' { - exponent = true - } - } - - if fraction { - sc.readRune() // consume '.' - c = sc.peekRune() - for isdigit(c) { - sc.readRune() - c = sc.peekRune() - } - - if c == 'e' || c == 'E' { - exponent = true - } - } - - if exponent { - sc.readRune() // consume [eE] - c = sc.peekRune() - if c == '+' || c == '-' { - sc.readRune() - c = sc.peekRune() - if !isdigit(c) { - sc.error(sc.pos, "invalid float literal") - } - } - for isdigit(c) { - sc.readRune() - c = sc.peekRune() - } - } - - sc.endToken(val) - if fraction || exponent { - var err error - val.float, err = strconv.ParseFloat(val.raw, 64) - if err != nil { - sc.error(sc.pos, "invalid float literal") - } - return FLOAT - } else { - var err error - s := val.raw - val.bigInt = nil - if len(s) > 2 && s[0] == '0' && (s[1] == 'o' || s[1] == 'O') { - val.int, err = strconv.ParseInt(s[2:], 8, 64) - } else if len(s) > 2 && s[0] == '0' && (s[1] == 'b' || s[1] == 'B') { - val.int, err = strconv.ParseInt(s[2:], 2, 64) - } else { - val.int, err = strconv.ParseInt(s, 0, 64) - if err != nil { - num := new(big.Int) - var ok bool - val.bigInt, ok = num.SetString(s, 0) - if ok { - err = nil - } - } - } - if err != nil { - sc.error(start, "invalid int literal") - } - return INT - } -} - -// isIdent reports whether c is an identifier rune. -func isIdent(c rune) bool { - return isdigit(c) || isIdentStart(c) -} - -func isIdentStart(c rune) bool { - return 'a' <= c && c <= 'z' || - 'A' <= c && c <= 'Z' || - c == '_' || - unicode.IsLetter(c) -} - -func isdigit(c rune) bool { return '0' <= c && c <= '9' } -func isodigit(c rune) bool { return '0' <= c && c <= '7' } -func isxdigit(c rune) bool { return isdigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f' } -func isbdigit(c rune) bool { return '0' == c || c == '1' } - -// keywordToken records the special tokens for -// strings that should not be treated as ordinary identifiers. -var keywordToken = map[string]Token{ - "and": AND, - "break": BREAK, - "continue": CONTINUE, - "def": DEF, - "elif": ELIF, - "else": ELSE, - "for": FOR, - "if": IF, - "in": IN, - "lambda": LAMBDA, - "load": LOAD, - "not": NOT, - "or": OR, - "pass": PASS, - "return": RETURN, - "while": WHILE, - - // reserved words: - "as": ILLEGAL, - // "assert": ILLEGAL, // heavily used by our tests - "async": ILLEGAL, - "await": ILLEGAL, - "class": ILLEGAL, - "del": ILLEGAL, - "except": ILLEGAL, - "finally": ILLEGAL, - "from": ILLEGAL, - "global": ILLEGAL, - "import": ILLEGAL, - "is": ILLEGAL, - "nonlocal": ILLEGAL, - "raise": ILLEGAL, - "try": ILLEGAL, - "with": ILLEGAL, - "yield": ILLEGAL, -} diff --git a/vendor/go.starlark.net/syntax/syntax.go b/vendor/go.starlark.net/syntax/syntax.go deleted file mode 100644 index 5bfbcec39..000000000 --- a/vendor/go.starlark.net/syntax/syntax.go +++ /dev/null @@ -1,529 +0,0 @@ -// Copyright 2017 The Bazel 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 syntax provides a Starlark parser and abstract syntax tree. -package syntax // import "go.starlark.net/syntax" - -// A Node is a node in a Starlark syntax tree. -type Node interface { - // Span returns the start and end position of the expression. - Span() (start, end Position) - - // Comments returns the comments associated with this node. - // It returns nil if RetainComments was not specified during parsing, - // or if AllocComments was not called. - Comments() *Comments - - // AllocComments allocates a new Comments node if there was none. - // This makes possible to add new comments using Comments() method. - AllocComments() -} - -// A Comment represents a single # comment. -type Comment struct { - Start Position - Text string // without trailing newline -} - -// Comments collects the comments associated with an expression. -type Comments struct { - Before []Comment // whole-line comments before this expression - Suffix []Comment // end-of-line comments after this expression (up to 1) - - // For top-level expressions only, After lists whole-line - // comments following the expression. - After []Comment -} - -// A commentsRef is a possibly-nil reference to a set of comments. -// A commentsRef is embedded in each type of syntax node, -// and provides its Comments and AllocComments methods. -type commentsRef struct{ ref *Comments } - -// Comments returns the comments associated with a syntax node, -// or nil if AllocComments has not yet been called. -func (cr commentsRef) Comments() *Comments { return cr.ref } - -// AllocComments enables comments to be associated with a syntax node. -func (cr *commentsRef) AllocComments() { - if cr.ref == nil { - cr.ref = new(Comments) - } -} - -// Start returns the start position of the expression. -func Start(n Node) Position { - start, _ := n.Span() - return start -} - -// End returns the end position of the expression. -func End(n Node) Position { - _, end := n.Span() - return end -} - -// A File represents a Starlark file. -type File struct { - commentsRef - Path string - Stmts []Stmt - - Module interface{} // a *resolve.Module, set by resolver - Options *FileOptions -} - -func (x *File) Span() (start, end Position) { - if len(x.Stmts) == 0 { - return - } - start, _ = x.Stmts[0].Span() - _, end = x.Stmts[len(x.Stmts)-1].Span() - return start, end -} - -// A Stmt is a Starlark statement. -type Stmt interface { - Node - stmt() -} - -func (*AssignStmt) stmt() {} -func (*BranchStmt) stmt() {} -func (*DefStmt) stmt() {} -func (*ExprStmt) stmt() {} -func (*ForStmt) stmt() {} -func (*WhileStmt) stmt() {} -func (*IfStmt) stmt() {} -func (*LoadStmt) stmt() {} -func (*ReturnStmt) stmt() {} - -// An AssignStmt represents an assignment: -// -// x = 0 -// x, y = y, x -// x += 1 -type AssignStmt struct { - commentsRef - OpPos Position - Op Token // = EQ | {PLUS,MINUS,STAR,PERCENT}_EQ - LHS Expr - RHS Expr -} - -func (x *AssignStmt) Span() (start, end Position) { - start, _ = x.LHS.Span() - _, end = x.RHS.Span() - return -} - -// A DefStmt represents a function definition. -type DefStmt struct { - commentsRef - Def Position - Name *Ident - Lparen Position - Params []Expr // param = ident | ident=expr | * | *ident | **ident - Rparen Position - Body []Stmt - - Function interface{} // a *resolve.Function, set by resolver -} - -func (x *DefStmt) Span() (start, end Position) { - _, end = x.Body[len(x.Body)-1].Span() - return x.Def, end -} - -// An ExprStmt is an expression evaluated for side effects. -type ExprStmt struct { - commentsRef - X Expr -} - -func (x *ExprStmt) Span() (start, end Position) { - return x.X.Span() -} - -// An IfStmt is a conditional: If Cond: True; else: False. -// 'elseif' is desugared into a chain of IfStmts. -type IfStmt struct { - commentsRef - If Position // IF or ELIF - Cond Expr - True []Stmt - ElsePos Position // ELSE or ELIF - False []Stmt // optional -} - -func (x *IfStmt) Span() (start, end Position) { - body := x.False - if body == nil { - body = x.True - } - _, end = body[len(body)-1].Span() - return x.If, end -} - -// A LoadStmt loads another module and binds names from it: -// load(Module, "x", y="foo"). -// -// The AST is slightly unfaithful to the concrete syntax here because -// Starlark's load statement, so that it can be implemented in Python, -// binds some names (like y above) with an identifier and some (like x) -// without. For consistency we create fake identifiers for all the -// strings. -type LoadStmt struct { - commentsRef - Load Position - Module *Literal // a string - From []*Ident // name defined in loading module - To []*Ident // name in loaded module - Rparen Position -} - -func (x *LoadStmt) Span() (start, end Position) { - return x.Load, x.Rparen -} - -// ModuleName returns the name of the module loaded by this statement. -func (x *LoadStmt) ModuleName() string { return x.Module.Value.(string) } - -// A BranchStmt changes the flow of control: break, continue, pass. -type BranchStmt struct { - commentsRef - Token Token // = BREAK | CONTINUE | PASS - TokenPos Position -} - -func (x *BranchStmt) Span() (start, end Position) { - return x.TokenPos, x.TokenPos.add(x.Token.String()) -} - -// A ReturnStmt returns from a function. -type ReturnStmt struct { - commentsRef - Return Position - Result Expr // may be nil -} - -func (x *ReturnStmt) Span() (start, end Position) { - if x.Result == nil { - return x.Return, x.Return.add("return") - } - _, end = x.Result.Span() - return x.Return, end -} - -// An Expr is a Starlark expression. -type Expr interface { - Node - expr() -} - -func (*BinaryExpr) expr() {} -func (*CallExpr) expr() {} -func (*Comprehension) expr() {} -func (*CondExpr) expr() {} -func (*DictEntry) expr() {} -func (*DictExpr) expr() {} -func (*DotExpr) expr() {} -func (*Ident) expr() {} -func (*IndexExpr) expr() {} -func (*LambdaExpr) expr() {} -func (*ListExpr) expr() {} -func (*Literal) expr() {} -func (*ParenExpr) expr() {} -func (*SliceExpr) expr() {} -func (*TupleExpr) expr() {} -func (*UnaryExpr) expr() {} - -// An Ident represents an identifier. -type Ident struct { - commentsRef - NamePos Position - Name string - - Binding interface{} // a *resolver.Binding, set by resolver -} - -func (x *Ident) Span() (start, end Position) { - return x.NamePos, x.NamePos.add(x.Name) -} - -// A Literal represents a literal string or number. -type Literal struct { - commentsRef - Token Token // = STRING | BYTES | INT | FLOAT - TokenPos Position - Raw string // uninterpreted text - Value interface{} // = string | int64 | *big.Int | float64 -} - -func (x *Literal) Span() (start, end Position) { - return x.TokenPos, x.TokenPos.add(x.Raw) -} - -// A ParenExpr represents a parenthesized expression: (X). -type ParenExpr struct { - commentsRef - Lparen Position - X Expr - Rparen Position -} - -func (x *ParenExpr) Span() (start, end Position) { - return x.Lparen, x.Rparen.add(")") -} - -// A CallExpr represents a function call expression: Fn(Args). -type CallExpr struct { - commentsRef - Fn Expr - Lparen Position - Args []Expr // arg = expr | ident=expr | *expr | **expr - Rparen Position -} - -func (x *CallExpr) Span() (start, end Position) { - start, _ = x.Fn.Span() - return start, x.Rparen.add(")") -} - -// A DotExpr represents a field or method selector: X.Name. -type DotExpr struct { - commentsRef - X Expr - Dot Position - NamePos Position - Name *Ident -} - -func (x *DotExpr) Span() (start, end Position) { - start, _ = x.X.Span() - _, end = x.Name.Span() - return -} - -// A Comprehension represents a list or dict comprehension: -// [Body for ... if ...] or {Body for ... if ...} -type Comprehension struct { - commentsRef - Curly bool // {x:y for ...} or {x for ...}, not [x for ...] - Lbrack Position - Body Expr - Clauses []Node // = *ForClause | *IfClause - Rbrack Position -} - -func (x *Comprehension) Span() (start, end Position) { - return x.Lbrack, x.Rbrack.add("]") -} - -// A ForStmt represents a loop: for Vars in X: Body. -type ForStmt struct { - commentsRef - For Position - Vars Expr // name, or tuple of names - X Expr - Body []Stmt -} - -func (x *ForStmt) Span() (start, end Position) { - _, end = x.Body[len(x.Body)-1].Span() - return x.For, end -} - -// A WhileStmt represents a while loop: while X: Body. -type WhileStmt struct { - commentsRef - While Position - Cond Expr - Body []Stmt -} - -func (x *WhileStmt) Span() (start, end Position) { - _, end = x.Body[len(x.Body)-1].Span() - return x.While, end -} - -// A ForClause represents a for clause in a list comprehension: for Vars in X. -type ForClause struct { - commentsRef - For Position - Vars Expr // name, or tuple of names - In Position - X Expr -} - -func (x *ForClause) Span() (start, end Position) { - _, end = x.X.Span() - return x.For, end -} - -// An IfClause represents an if clause in a list comprehension: if Cond. -type IfClause struct { - commentsRef - If Position - Cond Expr -} - -func (x *IfClause) Span() (start, end Position) { - _, end = x.Cond.Span() - return x.If, end -} - -// A DictExpr represents a dictionary literal: { List }. -type DictExpr struct { - commentsRef - Lbrace Position - List []Expr // all *DictEntrys - Rbrace Position -} - -func (x *DictExpr) Span() (start, end Position) { - return x.Lbrace, x.Rbrace.add("}") -} - -// A DictEntry represents a dictionary entry: Key: Value. -// Used only within a DictExpr. -type DictEntry struct { - commentsRef - Key Expr - Colon Position - Value Expr -} - -func (x *DictEntry) Span() (start, end Position) { - start, _ = x.Key.Span() - _, end = x.Value.Span() - return start, end -} - -// A LambdaExpr represents an inline function abstraction. -type LambdaExpr struct { - commentsRef - Lambda Position - Params []Expr // param = ident | ident=expr | * | *ident | **ident - Body Expr - - Function interface{} // a *resolve.Function, set by resolver -} - -func (x *LambdaExpr) Span() (start, end Position) { - _, end = x.Body.Span() - return x.Lambda, end -} - -// A ListExpr represents a list literal: [ List ]. -type ListExpr struct { - commentsRef - Lbrack Position - List []Expr - Rbrack Position -} - -func (x *ListExpr) Span() (start, end Position) { - return x.Lbrack, x.Rbrack.add("]") -} - -// CondExpr represents the conditional: X if COND else ELSE. -type CondExpr struct { - commentsRef - If Position - Cond Expr - True Expr - ElsePos Position - False Expr -} - -func (x *CondExpr) Span() (start, end Position) { - start, _ = x.True.Span() - _, end = x.False.Span() - return start, end -} - -// A TupleExpr represents a tuple literal: (List). -type TupleExpr struct { - commentsRef - Lparen Position // optional (e.g. in x, y = 0, 1), but required if List is empty - List []Expr - Rparen Position -} - -func (x *TupleExpr) Span() (start, end Position) { - if x.Lparen.IsValid() { - return x.Lparen, x.Rparen - } else { - return Start(x.List[0]), End(x.List[len(x.List)-1]) - } -} - -// A UnaryExpr represents a unary expression: Op X. -// -// As a special case, UnaryOp{Op:Star} may also represent -// the star parameter in def f(*args) or def f(*, x). -type UnaryExpr struct { - commentsRef - OpPos Position - Op Token - X Expr // may be nil if Op==STAR -} - -func (x *UnaryExpr) Span() (start, end Position) { - if x.X != nil { - _, end = x.X.Span() - } else { - end = x.OpPos.add("*") - } - return x.OpPos, end -} - -// A BinaryExpr represents a binary expression: X Op Y. -// -// As a special case, BinaryExpr{Op:EQ} may also -// represent a named argument in a call f(k=v) -// or a named parameter in a function declaration -// def f(param=default). -type BinaryExpr struct { - commentsRef - X Expr - OpPos Position - Op Token - Y Expr -} - -func (x *BinaryExpr) Span() (start, end Position) { - start, _ = x.X.Span() - _, end = x.Y.Span() - return start, end -} - -// A SliceExpr represents a slice or substring expression: X[Lo:Hi:Step]. -type SliceExpr struct { - commentsRef - X Expr - Lbrack Position - Lo, Hi, Step Expr // all optional - Rbrack Position -} - -func (x *SliceExpr) Span() (start, end Position) { - start, _ = x.X.Span() - return start, x.Rbrack -} - -// An IndexExpr represents an index expression: X[Y]. -type IndexExpr struct { - commentsRef - X Expr - Lbrack Position - Y Expr - Rbrack Position -} - -func (x *IndexExpr) Span() (start, end Position) { - start, _ = x.X.Span() - return start, x.Rbrack -} diff --git a/vendor/go.starlark.net/syntax/walk.go b/vendor/go.starlark.net/syntax/walk.go deleted file mode 100644 index 5e6c805c2..000000000 --- a/vendor/go.starlark.net/syntax/walk.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2017 The Bazel 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 syntax - -// Walk traverses a syntax tree in depth-first order. -// It starts by calling f(n); n must not be nil. -// If f returns true, Walk calls itself -// recursively for each non-nil child of n. -// Walk then calls f(nil). -func Walk(n Node, f func(Node) bool) { - if n == nil { - panic("nil") - } - if !f(n) { - return - } - - // TODO(adonovan): opt: order cases using profile data. - switch n := n.(type) { - case *File: - walkStmts(n.Stmts, f) - - case *ExprStmt: - Walk(n.X, f) - - case *BranchStmt: - // no-op - - case *IfStmt: - Walk(n.Cond, f) - walkStmts(n.True, f) - walkStmts(n.False, f) - - case *AssignStmt: - Walk(n.LHS, f) - Walk(n.RHS, f) - - case *DefStmt: - Walk(n.Name, f) - for _, param := range n.Params { - Walk(param, f) - } - walkStmts(n.Body, f) - - case *ForStmt: - Walk(n.Vars, f) - Walk(n.X, f) - walkStmts(n.Body, f) - - case *ReturnStmt: - if n.Result != nil { - Walk(n.Result, f) - } - - case *LoadStmt: - Walk(n.Module, f) - for _, from := range n.From { - Walk(from, f) - } - for _, to := range n.To { - Walk(to, f) - } - - case *Ident, *Literal: - // no-op - - case *ListExpr: - for _, x := range n.List { - Walk(x, f) - } - - case *ParenExpr: - Walk(n.X, f) - - case *CondExpr: - Walk(n.Cond, f) - Walk(n.True, f) - Walk(n.False, f) - - case *IndexExpr: - Walk(n.X, f) - Walk(n.Y, f) - - case *DictEntry: - Walk(n.Key, f) - Walk(n.Value, f) - - case *SliceExpr: - Walk(n.X, f) - if n.Lo != nil { - Walk(n.Lo, f) - } - if n.Hi != nil { - Walk(n.Hi, f) - } - if n.Step != nil { - Walk(n.Step, f) - } - - case *Comprehension: - Walk(n.Body, f) - for _, clause := range n.Clauses { - Walk(clause, f) - } - - case *IfClause: - Walk(n.Cond, f) - - case *ForClause: - Walk(n.Vars, f) - Walk(n.X, f) - - case *TupleExpr: - for _, x := range n.List { - Walk(x, f) - } - - case *DictExpr: - for _, entry := range n.List { - Walk(entry, f) - } - - case *UnaryExpr: - if n.X != nil { - Walk(n.X, f) - } - - case *BinaryExpr: - Walk(n.X, f) - Walk(n.Y, f) - - case *DotExpr: - Walk(n.X, f) - Walk(n.Name, f) - - case *CallExpr: - Walk(n.Fn, f) - for _, arg := range n.Args { - Walk(arg, f) - } - - case *LambdaExpr: - for _, param := range n.Params { - Walk(param, f) - } - Walk(n.Body, f) - - default: - panic(n) - } - - f(nil) -} - -func walkStmts(stmts []Stmt, f func(Node) bool) { - for _, stmt := range stmts { - Walk(stmt, f) - } -} diff --git a/vendor/golang.org/x/sys/unix/ioctl_linux.go b/vendor/golang.org/x/sys/unix/ioctl_linux.go index dbe680eab..7ca4fa12a 100644 --- a/vendor/golang.org/x/sys/unix/ioctl_linux.go +++ b/vendor/golang.org/x/sys/unix/ioctl_linux.go @@ -58,6 +58,102 @@ func IoctlGetEthtoolDrvinfo(fd int, ifname string) (*EthtoolDrvinfo, error) { return &value, err } +// IoctlGetEthtoolTsInfo fetches ethtool timestamping and PHC +// association for the network device specified by ifname. +func IoctlGetEthtoolTsInfo(fd int, ifname string) (*EthtoolTsInfo, error) { + ifr, err := NewIfreq(ifname) + if err != nil { + return nil, err + } + + value := EthtoolTsInfo{Cmd: ETHTOOL_GET_TS_INFO} + ifrd := ifr.withData(unsafe.Pointer(&value)) + + err = ioctlIfreqData(fd, SIOCETHTOOL, &ifrd) + return &value, err +} + +// IoctlGetHwTstamp retrieves the hardware timestamping configuration +// for the network device specified by ifname. +func IoctlGetHwTstamp(fd int, ifname string) (*HwTstampConfig, error) { + ifr, err := NewIfreq(ifname) + if err != nil { + return nil, err + } + + value := HwTstampConfig{} + ifrd := ifr.withData(unsafe.Pointer(&value)) + + err = ioctlIfreqData(fd, SIOCGHWTSTAMP, &ifrd) + return &value, err +} + +// IoctlSetHwTstamp updates the hardware timestamping configuration for +// the network device specified by ifname. +func IoctlSetHwTstamp(fd int, ifname string, cfg *HwTstampConfig) error { + ifr, err := NewIfreq(ifname) + if err != nil { + return err + } + ifrd := ifr.withData(unsafe.Pointer(cfg)) + return ioctlIfreqData(fd, SIOCSHWTSTAMP, &ifrd) +} + +// FdToClockID derives the clock ID from the file descriptor number +// - see clock_gettime(3), FD_TO_CLOCKID macros. The resulting ID is +// suitable for system calls like ClockGettime. +func FdToClockID(fd int) int32 { return int32((int(^fd) << 3) | 3) } + +// IoctlPtpClockGetcaps returns the description of a given PTP device. +func IoctlPtpClockGetcaps(fd int) (*PtpClockCaps, error) { + var value PtpClockCaps + err := ioctlPtr(fd, PTP_CLOCK_GETCAPS2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpSysOffsetPrecise returns a description of the clock +// offset compared to the system clock. +func IoctlPtpSysOffsetPrecise(fd int) (*PtpSysOffsetPrecise, error) { + var value PtpSysOffsetPrecise + err := ioctlPtr(fd, PTP_SYS_OFFSET_PRECISE2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpSysOffsetExtended returns an extended description of the +// clock offset compared to the system clock. The samples parameter +// specifies the desired number of measurements. +func IoctlPtpSysOffsetExtended(fd int, samples uint) (*PtpSysOffsetExtended, error) { + value := PtpSysOffsetExtended{Samples: uint32(samples)} + err := ioctlPtr(fd, PTP_SYS_OFFSET_EXTENDED2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpPinGetfunc returns the configuration of the specified +// I/O pin on given PTP device. +func IoctlPtpPinGetfunc(fd int, index uint) (*PtpPinDesc, error) { + value := PtpPinDesc{Index: uint32(index)} + err := ioctlPtr(fd, PTP_PIN_GETFUNC2, unsafe.Pointer(&value)) + return &value, err +} + +// IoctlPtpPinSetfunc updates configuration of the specified PTP +// I/O pin. +func IoctlPtpPinSetfunc(fd int, pd *PtpPinDesc) error { + return ioctlPtr(fd, PTP_PIN_SETFUNC2, unsafe.Pointer(pd)) +} + +// IoctlPtpPeroutRequest configures the periodic output mode of the +// PTP I/O pins. +func IoctlPtpPeroutRequest(fd int, r *PtpPeroutRequest) error { + return ioctlPtr(fd, PTP_PEROUT_REQUEST2, unsafe.Pointer(r)) +} + +// IoctlPtpExttsRequest configures the external timestamping mode +// of the PTP I/O pins. +func IoctlPtpExttsRequest(fd int, r *PtpExttsRequest) error { + return ioctlPtr(fd, PTP_EXTTS_REQUEST2, unsafe.Pointer(r)) +} + // IoctlGetWatchdogInfo fetches information about a watchdog device from the // Linux watchdog API. For more information, see: // https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html. diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index ac54ecaba..6ab02b6c3 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -158,6 +158,16 @@ includes_Linux=' #endif #define _GNU_SOURCE +// See the description in unix/linux/types.go +#if defined(__ARM_EABI__) || \ + (defined(__mips__) && (_MIPS_SIM == _ABIO32)) || \ + (defined(__powerpc__) && (!defined(__powerpc64__))) +# ifdef _TIME_BITS +# undef _TIME_BITS +# endif +# define _TIME_BITS 32 +#endif + // is broken on powerpc64, as it fails to include definitions of // these structures. We just include them copied from . #if defined(__powerpc__) @@ -256,6 +266,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -527,6 +538,7 @@ ccflags="$@" $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ || + $2 ~ /^PTP_/ || $2 ~ /^RAW_PAYLOAD_/ || $2 ~ /^[US]F_/ || $2 ~ /^TP_STATUS_/ || diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index f08abd434..230a94549 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1860,6 +1860,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error) //sys ClockGetres(clockid int32, res *Timespec) (err error) //sys ClockGettime(clockid int32, time *Timespec) (err error) +//sys ClockSettime(clockid int32, time *Timespec) (err error) //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) //sys Close(fd int) (err error) //sys CloseRange(first uint, last uint, flags uint) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 312ae6ac1..7bf5c04bb 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -768,6 +768,15 @@ func Munmap(b []byte) (err error) { return mapper.Munmap(b) } +func MmapPtr(fd int, offset int64, addr unsafe.Pointer, length uintptr, prot int, flags int) (ret unsafe.Pointer, err error) { + xaddr, err := mapper.mmap(uintptr(addr), length, prot, flags, fd, offset) + return unsafe.Pointer(xaddr), err +} + +func MunmapPtr(addr unsafe.Pointer, length uintptr) (err error) { + return mapper.munmap(uintptr(addr), length) +} + //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A //sysnb Getgid() (gid int) //sysnb Getpid() (pid int) @@ -816,10 +825,10 @@ func Lstat(path string, stat *Stat_t) (err error) { // for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/ func isSpecialPath(path []byte) (v bool) { var special = [4][8]byte{ - [8]byte{'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, - [8]byte{'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, - [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, - [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} + {'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, + {'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, + {'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, + {'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} var i, j int for i = 0; i < len(special); i++ { @@ -3115,3 +3124,90 @@ func legacy_Mkfifoat(dirfd int, path string, mode uint32) (err error) { //sys Posix_openpt(oflag int) (fd int, err error) = SYS_POSIX_OPENPT //sys Grantpt(fildes int) (rc int, err error) = SYS_GRANTPT //sys Unlockpt(fildes int) (rc int, err error) = SYS_UNLOCKPT + +func fcntlAsIs(fd uintptr, cmd int, arg uintptr) (val int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), arg) + runtime.ExitSyscall() + val = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +func Fcntl(fd uintptr, cmd int, op interface{}) (ret int, err error) { + switch op.(type) { + case *Flock_t: + err = FcntlFlock(fd, cmd, op.(*Flock_t)) + if err != nil { + ret = -1 + } + return + case int: + return FcntlInt(fd, cmd, op.(int)) + case *F_cnvrt: + return fcntlAsIs(fd, cmd, uintptr(unsafe.Pointer(op.(*F_cnvrt)))) + case unsafe.Pointer: + return fcntlAsIs(fd, cmd, uintptr(op.(unsafe.Pointer))) + default: + return -1, EINVAL + } + return +} + +func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + if raceenabled { + raceReleaseMerge(unsafe.Pointer(&ioSync)) + } + return sendfile(outfd, infd, offset, count) +} + +func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + // TODO: use LE call instead if the call is implemented + originalOffset, err := Seek(infd, 0, SEEK_CUR) + if err != nil { + return -1, err + } + //start reading data from in_fd + if offset != nil { + _, err := Seek(infd, *offset, SEEK_SET) + if err != nil { + return -1, err + } + } + + buf := make([]byte, count) + readBuf := make([]byte, 0) + var n int = 0 + for i := 0; i < count; i += n { + n, err := Read(infd, buf) + if n == 0 { + if err != nil { + return -1, err + } else { // EOF + break + } + } + readBuf = append(readBuf, buf...) + buf = buf[0:0] + } + + n2, err := Write(outfd, readBuf) + if err != nil { + return -1, err + } + + //When sendfile() returns, this variable will be set to the + // offset of the byte following the last byte that was read. + if offset != nil { + *offset = *offset + int64(n) + // If offset is not NULL, then sendfile() does not modify the file + // offset of in_fd + _, err := Seek(infd, originalOffset, SEEK_SET) + if err != nil { + return -1, err + } + } + return n2, nil +} diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index de3b46248..6ebc48b3f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -321,6 +321,9 @@ const ( AUDIT_INTEGRITY_STATUS = 0x70a AUDIT_IPC = 0x517 AUDIT_IPC_SET_PERM = 0x51f + AUDIT_IPE_ACCESS = 0x58c + AUDIT_IPE_CONFIG_CHANGE = 0x58d + AUDIT_IPE_POLICY_LOAD = 0x58e AUDIT_KERNEL = 0x7d0 AUDIT_KERNEL_OTHER = 0x524 AUDIT_KERN_MODULE = 0x532 @@ -489,6 +492,7 @@ const ( BPF_F_ID = 0x20 BPF_F_NETFILTER_IP_DEFRAG = 0x1 BPF_F_QUERY_EFFECTIVE = 0x1 + BPF_F_REDIRECT_FLAGS = 0x19 BPF_F_REPLACE = 0x4 BPF_F_SLEEPABLE = 0x10 BPF_F_STRICT_ALIGNMENT = 0x1 @@ -1166,6 +1170,7 @@ const ( EXTA = 0xe EXTB = 0xf F2FS_SUPER_MAGIC = 0xf2f52010 + FALLOC_FL_ALLOCATE_RANGE = 0x0 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -1799,6 +1804,8 @@ const ( LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 + LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET = 0x1 + LANDLOCK_SCOPE_SIGNAL = 0x2 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 @@ -1924,6 +1931,7 @@ const ( MNT_FORCE = 0x1 MNT_ID_REQ_SIZE_VER0 = 0x18 MNT_ID_REQ_SIZE_VER1 = 0x20 + MNT_NS_INFO_SIZE_VER0 = 0x10 MODULE_INIT_COMPRESSED_FILE = 0x4 MODULE_INIT_IGNORE_MODVERSIONS = 0x1 MODULE_INIT_IGNORE_VERMAGIC = 0x2 @@ -2625,6 +2633,28 @@ const ( PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PSTOREFS_MAGIC = 0x6165676c + PTP_CLK_MAGIC = '=' + PTP_ENABLE_FEATURE = 0x1 + PTP_EXTTS_EDGES = 0x6 + PTP_EXTTS_EVENT_VALID = 0x1 + PTP_EXTTS_V1_VALID_FLAGS = 0x7 + PTP_EXTTS_VALID_FLAGS = 0x1f + PTP_EXT_OFFSET = 0x10 + PTP_FALLING_EDGE = 0x4 + PTP_MAX_SAMPLES = 0x19 + PTP_PEROUT_DUTY_CYCLE = 0x2 + PTP_PEROUT_ONE_SHOT = 0x1 + PTP_PEROUT_PHASE = 0x4 + PTP_PEROUT_V1_VALID_FLAGS = 0x0 + PTP_PEROUT_VALID_FLAGS = 0x7 + PTP_PIN_GETFUNC = 0xc0603d06 + PTP_PIN_GETFUNC2 = 0xc0603d0f + PTP_RISING_EDGE = 0x2 + PTP_STRICT_FLAGS = 0x8 + PTP_SYS_OFFSET_EXTENDED = 0xc4c03d09 + PTP_SYS_OFFSET_EXTENDED2 = 0xc4c03d12 + PTP_SYS_OFFSET_PRECISE = 0xc0403d08 + PTP_SYS_OFFSET_PRECISE2 = 0xc0403d11 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -2948,6 +2978,7 @@ const ( RWF_WRITE_LIFE_NOT_SET = 0x0 SCHED_BATCH = 0x3 SCHED_DEADLINE = 0x6 + SCHED_EXT = 0x7 SCHED_FIFO = 0x1 SCHED_FLAG_ALL = 0x7f SCHED_FLAG_DL_OVERRUN = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 8aa6d77c0..c0d45e320 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -109,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -237,6 +238,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 PTRACE_GET_THREAD_AREA = 0x19 @@ -283,6 +298,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -321,6 +338,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index da428f425..c731d24f0 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -109,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -237,6 +238,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_ARCH_PRCTL = 0x1e PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 @@ -284,6 +299,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -322,6 +339,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index bf45bfec7..680018a4a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETCRUNCHREGS = 0x19 PTRACE_GETFDPIC = 0x1f PTRACE_GETFDPIC_EXEC = 0x0 @@ -289,6 +304,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -327,6 +344,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 71c67162b..a63909f30 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -112,6 +112,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -205,6 +206,7 @@ const ( PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + POE_MAGIC = 0x504f4530 PPPIOCATTACH = 0x4004743d PPPIOCATTCHAN = 0x40047438 PPPIOCBRIDGECHAN = 0x40047435 @@ -240,6 +242,20 @@ const ( PROT_BTI = 0x10 PROT_MTE = 0x20 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_PEEKMTETAGS = 0x21 PTRACE_POKEMTETAGS = 0x22 PTRACE_SYSEMU = 0x1f @@ -280,6 +296,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -318,6 +336,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index 9476628fa..9b0a2573f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -109,6 +109,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -238,6 +239,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 RLIMIT_AS = 0x9 @@ -276,6 +291,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -314,6 +331,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index b9e85f3cf..958e6e064 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -282,6 +297,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -320,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index a48b68a76..50c7f25bd 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -282,6 +297,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -320,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index ea00e8522..ced21d66d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -282,6 +297,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -320,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 91c646871..226c04419 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x100 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPREGS = 0xe PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 @@ -282,6 +297,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -320,6 +337,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 8cbf38d63..3122737cd 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -237,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -337,6 +352,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -375,6 +392,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index a2df73419..eb5d3467e 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -237,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -341,6 +356,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -379,6 +396,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 247913792..e921ebc60 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x4000 ICANON = 0x100 IEXTEN = 0x400 @@ -237,6 +238,20 @@ const ( PPPIOCXFERUNIT = 0x2000744e PROT_SAO = 0x10 PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS64 = 0x16 @@ -341,6 +356,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -379,6 +396,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index d265f146e..38ba81c55 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_GETFDPIC = 0x21 PTRACE_GETFDPIC_EXEC = 0x0 PTRACE_GETFDPIC_INTERP = 0x1 @@ -273,6 +288,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -311,6 +328,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 3f2d64439..71f040097 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -108,6 +108,7 @@ const ( HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESC = 0x90044802 HIDIOCGRDESCSIZE = 0x80044801 + HIDIOCREVOKE = 0x4004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -234,6 +235,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x80503d01 + PTP_CLOCK_GETCAPS2 = 0x80503d0a + PTP_ENABLE_PPS = 0x40043d04 + PTP_ENABLE_PPS2 = 0x40043d0d + PTP_EXTTS_REQUEST = 0x40103d02 + PTP_EXTTS_REQUEST2 = 0x40103d0b + PTP_MASK_CLEAR_ALL = 0x3d13 + PTP_MASK_EN_SINGLE = 0x40043d14 + PTP_PEROUT_REQUEST = 0x40383d03 + PTP_PEROUT_REQUEST2 = 0x40383d0c + PTP_PIN_SETFUNC = 0x40603d07 + PTP_PIN_SETFUNC2 = 0x40603d10 + PTP_SYS_OFFSET = 0x43403d05 + PTP_SYS_OFFSET2 = 0x43403d0e PTRACE_DISABLE_TE = 0x5010 PTRACE_ENABLE_TE = 0x5009 PTRACE_GET_LAST_BREAK = 0x5006 @@ -345,6 +360,8 @@ const ( RTC_WIE_ON = 0x700f RTC_WKALM_RD = 0x80287010 RTC_WKALM_SET = 0x4028700f + SCM_DEVMEM_DMABUF = 0x4f + SCM_DEVMEM_LINEAR = 0x4e SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a @@ -383,6 +400,9 @@ const ( SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DETACH_REUSEPORT_BPF = 0x44 + SO_DEVMEM_DMABUF = 0x4f + SO_DEVMEM_DONTNEED = 0x50 + SO_DEVMEM_LINEAR = 0x4e SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 5d8b727a1..c44a31332 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -112,6 +112,7 @@ const ( HIDIOCGRAWINFO = 0x40084803 HIDIOCGRDESC = 0x50044802 HIDIOCGRDESCSIZE = 0x40044801 + HIDIOCREVOKE = 0x8004480d HUPCL = 0x400 ICANON = 0x2 IEXTEN = 0x8000 @@ -239,6 +240,20 @@ const ( PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCXFERUNIT = 0x2000744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTP_CLOCK_GETCAPS = 0x40503d01 + PTP_CLOCK_GETCAPS2 = 0x40503d0a + PTP_ENABLE_PPS = 0x80043d04 + PTP_ENABLE_PPS2 = 0x80043d0d + PTP_EXTTS_REQUEST = 0x80103d02 + PTP_EXTTS_REQUEST2 = 0x80103d0b + PTP_MASK_CLEAR_ALL = 0x20003d13 + PTP_MASK_EN_SINGLE = 0x80043d14 + PTP_PEROUT_REQUEST = 0x80383d03 + PTP_PEROUT_REQUEST2 = 0x80383d0c + PTP_PIN_SETFUNC = 0x80603d07 + PTP_PIN_SETFUNC2 = 0x80603d10 + PTP_SYS_OFFSET = 0x83403d05 + PTP_SYS_OFFSET2 = 0x83403d0e PTRACE_GETFPAREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS64 = 0x19 @@ -336,6 +351,8 @@ const ( RTC_WIE_ON = 0x2000700f RTC_WKALM_RD = 0x40287010 RTC_WKALM_SET = 0x8028700f + SCM_DEVMEM_DMABUF = 0x58 + SCM_DEVMEM_LINEAR = 0x57 SCM_TIMESTAMPING = 0x23 SCM_TIMESTAMPING_OPT_STATS = 0x38 SCM_TIMESTAMPING_PKTINFO = 0x3c @@ -422,6 +439,9 @@ const ( SO_CNX_ADVICE = 0x37 SO_COOKIE = 0x3b SO_DETACH_REUSEPORT_BPF = 0x47 + SO_DEVMEM_DMABUF = 0x58 + SO_DEVMEM_DONTNEED = 0x59 + SO_DEVMEM_LINEAR = 0x57 SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index af30da557..5cc1e8eb2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -592,6 +592,16 @@ func ClockGettime(clockid int32, time *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func ClockSettime(clockid int32, time *Timespec) (err error) { + _, _, e1 := Syscall(SYS_CLOCK_SETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) { _, _, e1 := Syscall6(SYS_CLOCK_NANOSLEEP, uintptr(clockid), uintptr(flags), uintptr(unsafe.Pointer(request)), uintptr(unsafe.Pointer(remain)), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go index d003c3d43..17c53bd9b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go @@ -462,11 +462,14 @@ type FdSet struct { const ( SizeofIfMsghdr = 0x70 + SizeofIfMsghdr2 = 0xa0 SizeofIfData = 0x60 + SizeofIfData64 = 0x80 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c + SizeofRtMsghdr2 = 0x5c SizeofRtMetrics = 0x38 ) @@ -480,6 +483,20 @@ type IfMsghdr struct { Data IfData } +type IfMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + Snd_len int32 + Snd_maxlen int32 + Snd_drops int32 + Timer int32 + Data IfData64 +} + type IfData struct { Type uint8 Typelen uint8 @@ -512,6 +529,34 @@ type IfData struct { Reserved2 uint32 } +type IfData64 struct { + Type uint8 + Typelen uint8 + Physical uint8 + Addrlen uint8 + Hdrlen uint8 + Recvquota uint8 + Xmitquota uint8 + Unused1 uint8 + Mtu uint32 + Metric uint32 + Baudrate uint64 + Ipackets uint64 + Ierrors uint64 + Opackets uint64 + Oerrors uint64 + Collisions uint64 + Ibytes uint64 + Obytes uint64 + Imcasts uint64 + Omcasts uint64 + Iqdrops uint64 + Noproto uint64 + Recvtiming uint32 + Xmittiming uint32 + Lastchange Timeval32 +} + type IfaMsghdr struct { Msglen uint16 Version uint8 @@ -557,6 +602,21 @@ type RtMsghdr struct { Rmx RtMetrics } +type RtMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + Flags int32 + Addrs int32 + Refcnt int32 + Parentflags int32 + Reserved int32 + Use int32 + Inits uint32 + Rmx RtMetrics +} + type RtMetrics struct { Locks uint32 Mtu uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go index 0d45a941a..2392226a7 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go @@ -462,11 +462,14 @@ type FdSet struct { const ( SizeofIfMsghdr = 0x70 + SizeofIfMsghdr2 = 0xa0 SizeofIfData = 0x60 + SizeofIfData64 = 0x80 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c + SizeofRtMsghdr2 = 0x5c SizeofRtMetrics = 0x38 ) @@ -480,6 +483,20 @@ type IfMsghdr struct { Data IfData } +type IfMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + Snd_len int32 + Snd_maxlen int32 + Snd_drops int32 + Timer int32 + Data IfData64 +} + type IfData struct { Type uint8 Typelen uint8 @@ -512,6 +529,34 @@ type IfData struct { Reserved2 uint32 } +type IfData64 struct { + Type uint8 + Typelen uint8 + Physical uint8 + Addrlen uint8 + Hdrlen uint8 + Recvquota uint8 + Xmitquota uint8 + Unused1 uint8 + Mtu uint32 + Metric uint32 + Baudrate uint64 + Ipackets uint64 + Ierrors uint64 + Opackets uint64 + Oerrors uint64 + Collisions uint64 + Ibytes uint64 + Obytes uint64 + Imcasts uint64 + Omcasts uint64 + Iqdrops uint64 + Noproto uint64 + Recvtiming uint32 + Xmittiming uint32 + Lastchange Timeval32 +} + type IfaMsghdr struct { Msglen uint16 Version uint8 @@ -557,6 +602,21 @@ type RtMsghdr struct { Rmx RtMetrics } +type RtMsghdr2 struct { + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + Flags int32 + Addrs int32 + Refcnt int32 + Parentflags int32 + Reserved int32 + Use int32 + Inits uint32 + Rmx RtMetrics +} + type RtMetrics struct { Locks uint32 Mtu uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 3a69e4549..5537148dc 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -1752,12 +1752,6 @@ const ( IFLA_IPVLAN_UNSPEC = 0x0 IFLA_IPVLAN_MODE = 0x1 IFLA_IPVLAN_FLAGS = 0x2 - NETKIT_NEXT = -0x1 - NETKIT_PASS = 0x0 - NETKIT_DROP = 0x2 - NETKIT_REDIRECT = 0x7 - NETKIT_L2 = 0x0 - NETKIT_L3 = 0x1 IFLA_NETKIT_UNSPEC = 0x0 IFLA_NETKIT_PEER_INFO = 0x1 IFLA_NETKIT_PRIMARY = 0x2 @@ -1796,6 +1790,7 @@ const ( IFLA_VXLAN_DF = 0x1d IFLA_VXLAN_VNIFILTER = 0x1e IFLA_VXLAN_LOCALBYPASS = 0x1f + IFLA_VXLAN_LABEL_POLICY = 0x20 IFLA_GENEVE_UNSPEC = 0x0 IFLA_GENEVE_ID = 0x1 IFLA_GENEVE_REMOTE = 0x2 @@ -1825,6 +1820,8 @@ const ( IFLA_GTP_ROLE = 0x4 IFLA_GTP_CREATE_SOCKETS = 0x5 IFLA_GTP_RESTART_COUNT = 0x6 + IFLA_GTP_LOCAL = 0x7 + IFLA_GTP_LOCAL6 = 0x8 IFLA_BOND_UNSPEC = 0x0 IFLA_BOND_MODE = 0x1 IFLA_BOND_ACTIVE_SLAVE = 0x2 @@ -1857,6 +1854,7 @@ const ( IFLA_BOND_AD_LACP_ACTIVE = 0x1d IFLA_BOND_MISSED_MAX = 0x1e IFLA_BOND_NS_IP6_TARGET = 0x1f + IFLA_BOND_COUPLED_CONTROL = 0x20 IFLA_BOND_AD_INFO_UNSPEC = 0x0 IFLA_BOND_AD_INFO_AGGREGATOR = 0x1 IFLA_BOND_AD_INFO_NUM_PORTS = 0x2 @@ -1925,6 +1923,7 @@ const ( IFLA_HSR_SEQ_NR = 0x5 IFLA_HSR_VERSION = 0x6 IFLA_HSR_PROTOCOL = 0x7 + IFLA_HSR_INTERLINK = 0x8 IFLA_STATS_UNSPEC = 0x0 IFLA_STATS_LINK_64 = 0x1 IFLA_STATS_LINK_XSTATS = 0x2 @@ -1977,6 +1976,15 @@ const ( IFLA_DSA_MASTER = 0x1 ) +const ( + NETKIT_NEXT = -0x1 + NETKIT_PASS = 0x0 + NETKIT_DROP = 0x2 + NETKIT_REDIRECT = 0x7 + NETKIT_L2 = 0x0 + NETKIT_L3 = 0x1 +) + const ( NF_INET_PRE_ROUTING = 0x0 NF_INET_LOCAL_IN = 0x1 @@ -2586,8 +2594,8 @@ const ( SOF_TIMESTAMPING_BIND_PHC = 0x8000 SOF_TIMESTAMPING_OPT_ID_TCP = 0x10000 - SOF_TIMESTAMPING_LAST = 0x10000 - SOF_TIMESTAMPING_MASK = 0x1ffff + SOF_TIMESTAMPING_LAST = 0x20000 + SOF_TIMESTAMPING_MASK = 0x3ffff SCM_TSTAMP_SND = 0x0 SCM_TSTAMP_SCHED = 0x1 @@ -3533,7 +3541,7 @@ type Nhmsg struct { type NexthopGrp struct { Id uint32 Weight uint8 - Resvd1 uint8 + High uint8 Resvd2 uint16 } @@ -3794,7 +3802,7 @@ const ( ETHTOOL_MSG_PSE_GET = 0x24 ETHTOOL_MSG_PSE_SET = 0x25 ETHTOOL_MSG_RSS_GET = 0x26 - ETHTOOL_MSG_USER_MAX = 0x2c + ETHTOOL_MSG_USER_MAX = 0x2d ETHTOOL_MSG_KERNEL_NONE = 0x0 ETHTOOL_MSG_STRSET_GET_REPLY = 0x1 ETHTOOL_MSG_LINKINFO_GET_REPLY = 0x2 @@ -3834,7 +3842,7 @@ const ( ETHTOOL_MSG_MODULE_NTF = 0x24 ETHTOOL_MSG_PSE_GET_REPLY = 0x25 ETHTOOL_MSG_RSS_GET_REPLY = 0x26 - ETHTOOL_MSG_KERNEL_MAX = 0x2c + ETHTOOL_MSG_KERNEL_MAX = 0x2e ETHTOOL_FLAG_COMPACT_BITSETS = 0x1 ETHTOOL_FLAG_OMIT_REPLY = 0x2 ETHTOOL_FLAG_STATS = 0x4 @@ -3842,7 +3850,7 @@ const ( ETHTOOL_A_HEADER_DEV_INDEX = 0x1 ETHTOOL_A_HEADER_DEV_NAME = 0x2 ETHTOOL_A_HEADER_FLAGS = 0x3 - ETHTOOL_A_HEADER_MAX = 0x3 + ETHTOOL_A_HEADER_MAX = 0x4 ETHTOOL_A_BITSET_BIT_UNSPEC = 0x0 ETHTOOL_A_BITSET_BIT_INDEX = 0x1 ETHTOOL_A_BITSET_BIT_NAME = 0x2 @@ -4023,11 +4031,11 @@ const ( ETHTOOL_A_CABLE_RESULT_UNSPEC = 0x0 ETHTOOL_A_CABLE_RESULT_PAIR = 0x1 ETHTOOL_A_CABLE_RESULT_CODE = 0x2 - ETHTOOL_A_CABLE_RESULT_MAX = 0x2 + ETHTOOL_A_CABLE_RESULT_MAX = 0x3 ETHTOOL_A_CABLE_FAULT_LENGTH_UNSPEC = 0x0 ETHTOOL_A_CABLE_FAULT_LENGTH_PAIR = 0x1 ETHTOOL_A_CABLE_FAULT_LENGTH_CM = 0x2 - ETHTOOL_A_CABLE_FAULT_LENGTH_MAX = 0x2 + ETHTOOL_A_CABLE_FAULT_LENGTH_MAX = 0x3 ETHTOOL_A_CABLE_TEST_NTF_STATUS_UNSPEC = 0x0 ETHTOOL_A_CABLE_TEST_NTF_STATUS_STARTED = 0x1 ETHTOOL_A_CABLE_TEST_NTF_STATUS_COMPLETED = 0x2 @@ -4110,6 +4118,107 @@ type EthtoolDrvinfo struct { Regdump_len uint32 } +type EthtoolTsInfo struct { + Cmd uint32 + So_timestamping uint32 + Phc_index int32 + Tx_types uint32 + Tx_reserved [3]uint32 + Rx_filters uint32 + Rx_reserved [3]uint32 +} + +type HwTstampConfig struct { + Flags int32 + Tx_type int32 + Rx_filter int32 +} + +const ( + HWTSTAMP_FILTER_NONE = 0x0 + HWTSTAMP_FILTER_ALL = 0x1 + HWTSTAMP_FILTER_SOME = 0x2 + HWTSTAMP_FILTER_PTP_V1_L4_EVENT = 0x3 + HWTSTAMP_FILTER_PTP_V2_L4_EVENT = 0x6 + HWTSTAMP_FILTER_PTP_V2_L2_EVENT = 0x9 + HWTSTAMP_FILTER_PTP_V2_EVENT = 0xc +) + +const ( + HWTSTAMP_TX_OFF = 0x0 + HWTSTAMP_TX_ON = 0x1 + HWTSTAMP_TX_ONESTEP_SYNC = 0x2 +) + +type ( + PtpClockCaps struct { + Max_adj int32 + N_alarm int32 + N_ext_ts int32 + N_per_out int32 + Pps int32 + N_pins int32 + Cross_timestamping int32 + Adjust_phase int32 + Max_phase_adj int32 + Rsv [11]int32 + } + PtpClockTime struct { + Sec int64 + Nsec uint32 + Reserved uint32 + } + PtpExttsEvent struct { + T PtpClockTime + Index uint32 + Flags uint32 + Rsv [2]uint32 + } + PtpExttsRequest struct { + Index uint32 + Flags uint32 + Rsv [2]uint32 + } + PtpPeroutRequest struct { + StartOrPhase PtpClockTime + Period PtpClockTime + Index uint32 + Flags uint32 + On PtpClockTime + } + PtpPinDesc struct { + Name [64]byte + Index uint32 + Func uint32 + Chan uint32 + Rsv [5]uint32 + } + PtpSysOffset struct { + Samples uint32 + Rsv [3]uint32 + Ts [51]PtpClockTime + } + PtpSysOffsetExtended struct { + Samples uint32 + Clockid int32 + Rsv [2]uint32 + Ts [25][3]PtpClockTime + } + PtpSysOffsetPrecise struct { + Device PtpClockTime + Realtime PtpClockTime + Monoraw PtpClockTime + Rsv [4]uint32 + } +) + +const ( + PTP_PF_NONE = 0x0 + PTP_PF_EXTTS = 0x1 + PTP_PF_PEROUT = 0x2 + PTP_PF_PHYSYNC = 0x3 +) + type ( HIDRawReportDescriptor struct { Size uint32 @@ -4291,6 +4400,7 @@ const ( type LandlockRulesetAttr struct { Access_fs uint64 Access_net uint64 + Scoped uint64 } type LandlockPathBeneathAttr struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index d9a13af46..2e5d5a443 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -377,6 +377,12 @@ type Flock_t struct { Pid int32 } +type F_cnvrt struct { + Cvtcmd int32 + Pccsid int16 + Fccsid int16 +} + type Termios struct { Cflag uint32 Iflag uint32 diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 5cee9a314..4a3254386 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -168,6 +168,8 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW //sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) //sys DisconnectNamedPipe(pipe Handle) (err error) +//sys GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error) +//sys GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error) //sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) //sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW //sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState @@ -725,20 +727,12 @@ func DurationSinceBoot() time.Duration { } func Ftruncate(fd Handle, length int64) (err error) { - curoffset, e := Seek(fd, 0, 1) - if e != nil { - return e - } - defer Seek(fd, curoffset, 0) - _, e = Seek(fd, length, 0) - if e != nil { - return e + type _FILE_END_OF_FILE_INFO struct { + EndOfFile int64 } - e = SetEndOfFile(fd) - if e != nil { - return e - } - return nil + var info _FILE_END_OF_FILE_INFO + info.EndOfFile = length + return SetFileInformationByHandle(fd, FileEndOfFileInfo, (*byte)(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))) } func Gettimeofday(tv *Timeval) (err error) { @@ -894,6 +888,11 @@ const socket_error = uintptr(^uint32(0)) //sys GetACP() (acp uint32) = kernel32.GetACP //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar //sys getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) = iphlpapi.GetBestInterfaceEx +//sys GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) = iphlpapi.GetIfEntry2Ex +//sys GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) = iphlpapi.GetUnicastIpAddressEntry +//sys NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyIpInterfaceChange +//sys NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyUnicastIpAddressChange +//sys CancelMibChangeNotify2(notificationHandle Handle) (errcode error) = iphlpapi.CancelMibChangeNotify2 // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. @@ -1685,13 +1684,16 @@ func (s NTStatus) Error() string { // do not use NTUnicodeString, and instead UTF16PtrFromString should be used for // the more common *uint16 string type. func NewNTUnicodeString(s string) (*NTUnicodeString, error) { - var u NTUnicodeString - s16, err := UTF16PtrFromString(s) + s16, err := UTF16FromString(s) if err != nil { return nil, err } - RtlInitUnicodeString(&u, s16) - return &u, nil + n := uint16(len(s16) * 2) + return &NTUnicodeString{ + Length: n - 2, // subtract 2 bytes for the NULL terminator + MaximumLength: n, + Buffer: &s16[0], + }, nil } // Slice returns a uint16 slice that aliases the data in the NTUnicodeString. diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 7b97a154c..9d138de5f 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -176,6 +176,7 @@ const ( WAIT_FAILED = 0xFFFFFFFF // Access rights for process. + PROCESS_ALL_ACCESS = 0xFFFF PROCESS_CREATE_PROCESS = 0x0080 PROCESS_CREATE_THREAD = 0x0002 PROCESS_DUP_HANDLE = 0x0040 @@ -2203,6 +2204,132 @@ const ( IfOperStatusLowerLayerDown = 7 ) +const ( + IF_MAX_PHYS_ADDRESS_LENGTH = 32 + IF_MAX_STRING_SIZE = 256 +) + +// MIB_IF_ENTRY_LEVEL enumeration from netioapi.h or +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getifentry2ex. +const ( + MibIfEntryNormal = 0 + MibIfEntryNormalWithoutStatistics = 2 +) + +// MIB_NOTIFICATION_TYPE enumeration from netioapi.h or +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ne-netioapi-mib_notification_type. +const ( + MibParameterNotification = 0 + MibAddInstance = 1 + MibDeleteInstance = 2 + MibInitialNotification = 3 +) + +// MibIfRow2 stores information about a particular interface. See +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_if_row2. +type MibIfRow2 struct { + InterfaceLuid uint64 + InterfaceIndex uint32 + InterfaceGuid GUID + Alias [IF_MAX_STRING_SIZE + 1]uint16 + Description [IF_MAX_STRING_SIZE + 1]uint16 + PhysicalAddressLength uint32 + PhysicalAddress [IF_MAX_PHYS_ADDRESS_LENGTH]uint8 + PermanentPhysicalAddress [IF_MAX_PHYS_ADDRESS_LENGTH]uint8 + Mtu uint32 + Type uint32 + TunnelType uint32 + MediaType uint32 + PhysicalMediumType uint32 + AccessType uint32 + DirectionType uint32 + InterfaceAndOperStatusFlags uint8 + OperStatus uint32 + AdminStatus uint32 + MediaConnectState uint32 + NetworkGuid GUID + ConnectionType uint32 + TransmitLinkSpeed uint64 + ReceiveLinkSpeed uint64 + InOctets uint64 + InUcastPkts uint64 + InNUcastPkts uint64 + InDiscards uint64 + InErrors uint64 + InUnknownProtos uint64 + InUcastOctets uint64 + InMulticastOctets uint64 + InBroadcastOctets uint64 + OutOctets uint64 + OutUcastPkts uint64 + OutNUcastPkts uint64 + OutDiscards uint64 + OutErrors uint64 + OutUcastOctets uint64 + OutMulticastOctets uint64 + OutBroadcastOctets uint64 + OutQLen uint64 +} + +// MIB_UNICASTIPADDRESS_ROW stores information about a unicast IP address. See +// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_unicastipaddress_row. +type MibUnicastIpAddressRow struct { + Address RawSockaddrInet6 // SOCKADDR_INET union + InterfaceLuid uint64 + InterfaceIndex uint32 + PrefixOrigin uint32 + SuffixOrigin uint32 + ValidLifetime uint32 + PreferredLifetime uint32 + OnLinkPrefixLength uint8 + SkipAsSource uint8 + DadState uint32 + ScopeId uint32 + CreationTimeStamp Filetime +} + +const ScopeLevelCount = 16 + +// MIB_IPINTERFACE_ROW stores interface management information for a particular IP address family on a network interface. +// See https://learn.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_ipinterface_row. +type MibIpInterfaceRow struct { + Family uint16 + InterfaceLuid uint64 + InterfaceIndex uint32 + MaxReassemblySize uint32 + InterfaceIdentifier uint64 + MinRouterAdvertisementInterval uint32 + MaxRouterAdvertisementInterval uint32 + AdvertisingEnabled uint8 + ForwardingEnabled uint8 + WeakHostSend uint8 + WeakHostReceive uint8 + UseAutomaticMetric uint8 + UseNeighborUnreachabilityDetection uint8 + ManagedAddressConfigurationSupported uint8 + OtherStatefulConfigurationSupported uint8 + AdvertiseDefaultRoute uint8 + RouterDiscoveryBehavior uint32 + DadTransmits uint32 + BaseReachableTime uint32 + RetransmitTime uint32 + PathMtuDiscoveryTimeout uint32 + LinkLocalAddressBehavior uint32 + LinkLocalAddressTimeout uint32 + ZoneIndices [ScopeLevelCount]uint32 + SitePrefixLength uint32 + Metric uint32 + NlMtu uint32 + Connected uint8 + SupportsWakeUpPatterns uint8 + SupportsNeighborDiscovery uint8 + SupportsRouterDiscovery uint8 + ReachableTime uint32 + TransmitOffload uint32 + ReceiveOffload uint32 + DisableDefaultRoutes uint8 +} + // Console related constants used for the mode parameter to SetConsoleMode. See // https://docs.microsoft.com/en-us/windows/console/setconsolemode for details. diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 4c2e1bdc0..01c0716c2 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -181,10 +181,15 @@ var ( procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") procDwmGetWindowAttribute = moddwmapi.NewProc("DwmGetWindowAttribute") procDwmSetWindowAttribute = moddwmapi.NewProc("DwmSetWindowAttribute") + procCancelMibChangeNotify2 = modiphlpapi.NewProc("CancelMibChangeNotify2") procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses") procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx") procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") + procGetIfEntry2Ex = modiphlpapi.NewProc("GetIfEntry2Ex") + procGetUnicastIpAddressEntry = modiphlpapi.NewProc("GetUnicastIpAddressEntry") + procNotifyIpInterfaceChange = modiphlpapi.NewProc("NotifyIpInterfaceChange") + procNotifyUnicastIpAddressChange = modiphlpapi.NewProc("NotifyUnicastIpAddressChange") procAddDllDirectory = modkernel32.NewProc("AddDllDirectory") procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject") procCancelIo = modkernel32.NewProc("CancelIo") @@ -275,8 +280,10 @@ var ( procGetMaximumProcessorCount = modkernel32.NewProc("GetMaximumProcessorCount") procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW") procGetModuleHandleExW = modkernel32.NewProc("GetModuleHandleExW") + procGetNamedPipeClientProcessId = modkernel32.NewProc("GetNamedPipeClientProcessId") procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") + procGetNamedPipeServerProcessId = modkernel32.NewProc("GetNamedPipeServerProcessId") procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") procGetPriorityClass = modkernel32.NewProc("GetPriorityClass") procGetProcAddress = modkernel32.NewProc("GetProcAddress") @@ -1606,6 +1613,14 @@ func DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, si return } +func CancelMibChangeNotify2(notificationHandle Handle) (errcode error) { + r0, _, _ := syscall.Syscall(procCancelMibChangeNotify2.Addr(), 1, uintptr(notificationHandle), 0, 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) { r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0) if r0 != 0 { @@ -1638,6 +1653,46 @@ func GetIfEntry(pIfRow *MibIfRow) (errcode error) { return } +func GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) { + r0, _, _ := syscall.Syscall(procGetIfEntry2Ex.Addr(), 2, uintptr(level), uintptr(unsafe.Pointer(row)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) { + r0, _, _ := syscall.Syscall(procGetUnicastIpAddressEntry.Addr(), 1, uintptr(unsafe.Pointer(row)), 0, 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) { + var _p0 uint32 + if initialNotification { + _p0 = 1 + } + r0, _, _ := syscall.Syscall6(procNotifyIpInterfaceChange.Addr(), 5, uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + +func NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) { + var _p0 uint32 + if initialNotification { + _p0 = 1 + } + r0, _, _ := syscall.Syscall6(procNotifyUnicastIpAddressChange.Addr(), 5, uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle)), 0) + if r0 != 0 { + errcode = syscall.Errno(r0) + } + return +} + func AddDllDirectory(path *uint16) (cookie uintptr, err error) { r0, _, e1 := syscall.Syscall(procAddDllDirectory.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) cookie = uintptr(r0) @@ -2393,6 +2448,14 @@ func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err er return } +func GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetNamedPipeClientProcessId.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(clientProcessID)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) if r1 == 0 { @@ -2409,6 +2472,14 @@ func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint3 return } +func GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetNamedPipeServerProcessId.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(serverProcessID)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error) { var _p0 uint32 if wait { diff --git a/vendor/golang.org/x/term/README.md b/vendor/golang.org/x/term/README.md index d03d0aefe..05ff623f9 100644 --- a/vendor/golang.org/x/term/README.md +++ b/vendor/golang.org/x/term/README.md @@ -4,16 +4,13 @@ This repository provides Go terminal and console support packages. -## Download/Install - -The easiest way to install is to run `go get -u golang.org/x/term`. You can -also manually git clone the repository to `$GOPATH/src/golang.org/x/term`. - ## Report Issues / Send Patches This repository uses Gerrit for code changes. To learn how to submit changes to -this repository, see https://golang.org/doc/contribute.html. +this repository, see https://go.dev/doc/contribute. + +The git repository is https://go.googlesource.com/term. The main issue tracker for the term repository is located at -https://github.com/golang/go/issues. Prefix your issue with "x/term:" in the +https://go.dev/issues. Prefix your issue with "x/term:" in the subject line, so it is easy to find. diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml deleted file mode 100644 index 7348c50c0..000000000 --- a/vendor/gopkg.in/yaml.v2/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -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/gopkg.in/yaml.v2/LICENSE.libyaml b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml deleted file mode 100644 index 8da58fbf6..000000000 --- a/vendor/gopkg.in/yaml.v2/LICENSE.libyaml +++ /dev/null @@ -1,31 +0,0 @@ -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/gopkg.in/yaml.v2/NOTICE b/vendor/gopkg.in/yaml.v2/NOTICE deleted file mode 100644 index 866d74a7a..000000000 --- a/vendor/gopkg.in/yaml.v2/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -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/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md deleted file mode 100644 index b50c6e877..000000000 --- a/vendor/gopkg.in/yaml.v2/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# 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 *gopkg.in/yaml.v2*. - -To install it, run: - - go get gopkg.in/yaml.v2 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) - -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" - - "gopkg.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/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go deleted file mode 100644 index acf71402c..000000000 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ /dev/null @@ -1,744 +0,0 @@ -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/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go deleted file mode 100644 index 129bc2a97..000000000 --- a/vendor/gopkg.in/yaml.v2/decode.go +++ /dev/null @@ -1,815 +0,0 @@ -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/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go deleted file mode 100644 index a1c2cc526..000000000 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ /dev/null @@ -1,1685 +0,0 @@ -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/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go deleted file mode 100644 index 0ee738e11..000000000 --- a/vendor/gopkg.in/yaml.v2/encode.go +++ /dev/null @@ -1,390 +0,0 @@ -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/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go deleted file mode 100644 index 81d05dfe5..000000000 --- a/vendor/gopkg.in/yaml.v2/parserc.go +++ /dev/null @@ -1,1095 +0,0 @@ -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/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go deleted file mode 100644 index 7c1f5fac3..000000000 --- a/vendor/gopkg.in/yaml.v2/readerc.go +++ /dev/null @@ -1,412 +0,0 @@ -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/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go deleted file mode 100644 index 4120e0c91..000000000 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ /dev/null @@ -1,258 +0,0 @@ -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/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go deleted file mode 100644 index 0b9bb6030..000000000 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ /dev/null @@ -1,2711 +0,0 @@ -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/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go deleted file mode 100644 index 4c45e660a..000000000 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ /dev/null @@ -1,113 +0,0 @@ -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/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go deleted file mode 100644 index a2dde608c..000000000 --- a/vendor/gopkg.in/yaml.v2/writerc.go +++ /dev/null @@ -1,26 +0,0 @@ -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/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go deleted file mode 100644 index 30813884c..000000000 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ /dev/null @@ -1,478 +0,0 @@ -// Package yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/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/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go deleted file mode 100644 index f6a9c8e34..000000000 --- a/vendor/gopkg.in/yaml.v2/yamlh.go +++ /dev/null @@ -1,739 +0,0 @@ -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/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go deleted file mode 100644 index 8110ce3c3..000000000 --- a/vendor/gopkg.in/yaml.v2/yamlprivateh.go +++ /dev/null @@ -1,173 +0,0 @@ -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/helm.sh/helm/v3/internal/resolver/resolver.go b/vendor/helm.sh/helm/v3/internal/resolver/resolver.go index c5fc63643..b6f45da9e 100644 --- a/vendor/helm.sh/helm/v3/internal/resolver/resolver.go +++ b/vendor/helm.sh/helm/v3/internal/resolver/resolver.go @@ -172,7 +172,7 @@ func (r *Resolver) Resolve(reqs []*chart.Dependency, repoNames map[string]string Repository: d.Repository, Version: version, } - // The version are already sorted and hence the first one to satisfy the constraint is used + // The versions are already sorted and hence the first one to satisfy the constraint is used for _, ver := range vs { v, err := semver.NewVersion(ver.Version) // OCI does not need URLs diff --git a/vendor/helm.sh/helm/v3/internal/third_party/dep/fs/fs.go b/vendor/helm.sh/helm/v3/internal/third_party/dep/fs/fs.go index 4e4eacc60..d29bb5f87 100644 --- a/vendor/helm.sh/helm/v3/internal/third_party/dep/fs/fs.go +++ b/vendor/helm.sh/helm/v3/internal/third_party/dep/fs/fs.go @@ -260,7 +260,7 @@ func fixLongPath(path string) string { // minus 12)." Since MAX_PATH is 260, 260 - 12 = 248. // // The MSDN docs appear to say that a normal path that is 248 bytes long - // will work; empirically the path must be less then 248 bytes long. + // will work; empirically the path must be less than 248 bytes long. if len(path) < 248 { // Don't fix. (This is how Go 1.7 and earlier worked, // not automatically generating the \\?\ form) diff --git a/vendor/helm.sh/helm/v3/internal/tlsutil/tls.go b/vendor/helm.sh/helm/v3/internal/tlsutil/tls.go index dc832ed80..7cd1dace9 100644 --- a/vendor/helm.sh/helm/v3/internal/tlsutil/tls.go +++ b/vendor/helm.sh/helm/v3/internal/tlsutil/tls.go @@ -65,7 +65,7 @@ func CertPoolFromFile(filename string) (*x509.CertPool, error) { return cp, nil } -// CertFromFilePair returns an tls.Certificate containing the +// CertFromFilePair returns a tls.Certificate containing the // certificates public/private key pair from a pair of given PEM-encoded files. // Returns an error if the file could not be read, a certificate could not // be parsed, or if the file does not contain any certificates diff --git a/vendor/helm.sh/helm/v3/pkg/action/hooks.go b/vendor/helm.sh/helm/v3/pkg/action/hooks.go index 0af625dff..4bffb6ae0 100644 --- a/vendor/helm.sh/helm/v3/pkg/action/hooks.go +++ b/vendor/helm.sh/helm/v3/pkg/action/hooks.go @@ -99,7 +99,8 @@ func (cfg *Configuration) execHook(rl *release.Release, hook release.HookEvent, // If all hooks are successful, check the annotation of each hook to determine whether the hook should be deleted // under succeeded condition. If so, then clear the corresponding resource object in each hook - for _, h := range executingHooks { + for i := len(executingHooks) - 1; i >= 0; i-- { + h := executingHooks[i] if err := cfg.deleteHookByPolicy(h, release.HookSucceeded, timeout); err != nil { return err } diff --git a/vendor/helm.sh/helm/v3/pkg/action/install.go b/vendor/helm.sh/helm/v3/pkg/action/install.go index f0292a0a3..7ca40c88a 100644 --- a/vendor/helm.sh/helm/v3/pkg/action/install.go +++ b/vendor/helm.sh/helm/v3/pkg/action/install.go @@ -55,7 +55,7 @@ import ( "helm.sh/helm/v3/pkg/storage/driver" ) -// NOTESFILE_SUFFIX that we want to treat special. It goes through the templating engine +// notesFileSuffix that we want to treat special. It goes through the templating engine // but it's not a yaml file (resource) hence can't have hooks, etc. And the user actually // wants to see this file after rendering in the status command. However, it must be a suffix // since there can be filepath in front of it. @@ -307,7 +307,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma } if driver.ContainsSystemLabels(i.Labels) { - return nil, fmt.Errorf("user suplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()) + return nil, fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()) } rel := i.createRelease(chrt, vals, i.Labels) @@ -389,7 +389,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma } } - // If Replace is true, we need to supercede the last release. + // If Replace is true, we need to supersede the last release. if i.Replace { if err := i.replaceRelease(rel); err != nil { return nil, err @@ -631,7 +631,7 @@ func createOrOpenFile(filename string, append bool) (*os.File, error) { return os.Create(filename) } -// check if the directory exists to create file. creates if don't exists +// check if the directory exists to create file. creates if doesn't exist func ensureDirectoryForFile(file string) error { baseDir := path.Dir(file) _, err := os.Stat(baseDir) diff --git a/vendor/helm.sh/helm/v3/pkg/action/upgrade.go b/vendor/helm.sh/helm/v3/pkg/action/upgrade.go index 15bdae8da..a08d68495 100644 --- a/vendor/helm.sh/helm/v3/pkg/action/upgrade.go +++ b/vendor/helm.sh/helm/v3/pkg/action/upgrade.go @@ -279,7 +279,7 @@ func (u *Upgrade) prepareUpgrade(name string, chart *chart.Chart, vals map[strin } if driver.ContainsSystemLabels(u.Labels) { - return nil, nil, fmt.Errorf("user suplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()) + return nil, nil, fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()) } // Store an upgraded release. diff --git a/vendor/helm.sh/helm/v3/pkg/chart/loader/archive.go b/vendor/helm.sh/helm/v3/pkg/chart/loader/archive.go index 196e5f81d..8bb549346 100644 --- a/vendor/helm.sh/helm/v3/pkg/chart/loader/archive.go +++ b/vendor/helm.sh/helm/v3/pkg/chart/loader/archive.go @@ -101,7 +101,7 @@ func ensureArchive(name string, raw *os.File) error { return nil } -// isGZipApplication checks whether the achieve is of the application/x-gzip type. +// isGZipApplication checks whether the archive is of the application/x-gzip type. func isGZipApplication(data []byte) bool { sig := []byte("\x1F\x8B\x08") return bytes.HasPrefix(data, sig) diff --git a/vendor/helm.sh/helm/v3/pkg/chartutil/dependencies.go b/vendor/helm.sh/helm/v3/pkg/chartutil/dependencies.go index 205d99e09..36a341927 100644 --- a/vendor/helm.sh/helm/v3/pkg/chartutil/dependencies.go +++ b/vendor/helm.sh/helm/v3/pkg/chartutil/dependencies.go @@ -137,7 +137,7 @@ func processDependencyEnabled(c *chart.Chart, v map[string]interface{}, path str // If any dependency is not a part of Chart.yaml // then this should be added to chartDependencies. // However, if the dependency is already specified in Chart.yaml - // we should not add it, as it would be anyways processed from Chart.yaml + // we should not add it, as it would be processed from Chart.yaml anyway. Loop: for _, existing := range c.Dependencies() { diff --git a/vendor/helm.sh/helm/v3/pkg/downloader/manager.go b/vendor/helm.sh/helm/v3/pkg/downloader/manager.go index d5340575d..ec4056d27 100644 --- a/vendor/helm.sh/helm/v3/pkg/downloader/manager.go +++ b/vendor/helm.sh/helm/v3/pkg/downloader/manager.go @@ -173,7 +173,7 @@ func (m *Manager) Update() error { // has some information about them and, when possible, the index files // locally. // TODO(mattfarina): Repositories should be explicitly added by end users - // rather than automattic. In Helm v4 require users to add repositories. They + // rather than automatic. In Helm v4 require users to add repositories. They // should have to add them in order to make sure they are aware of the // repositories and opt-in to any locations, for security. repoNames, err = m.ensureMissingRepos(repoNames, req) diff --git a/vendor/helm.sh/helm/v3/pkg/engine/engine.go b/vendor/helm.sh/helm/v3/pkg/engine/engine.go index 058cfa749..df3a600a3 100644 --- a/vendor/helm.sh/helm/v3/pkg/engine/engine.go +++ b/vendor/helm.sh/helm/v3/pkg/engine/engine.go @@ -169,7 +169,7 @@ func tplFun(parent *template.Template, includedNames map[string]int, strict bool }) // We need a .New template, as template text which is just blanks - // or comments after parsing out defines just addes new named + // or comments after parsing out defines just adds new named // template definitions without changing the main template. // https://pkg.go.dev/text/template#Template.Parse // Use the parent's name for lack of a better way to identify the tpl diff --git a/vendor/helm.sh/helm/v3/pkg/engine/lookup_func.go b/vendor/helm.sh/helm/v3/pkg/engine/lookup_func.go index 86a7d698c..75e85098d 100644 --- a/vendor/helm.sh/helm/v3/pkg/engine/lookup_func.go +++ b/vendor/helm.sh/helm/v3/pkg/engine/lookup_func.go @@ -131,7 +131,7 @@ func getAPIResourceForGVK(gvk schema.GroupVersionKind, config *rest.Config) (met return res, err } for _, resource := range resList.APIResources { - // if a resource contains a "/" it's referencing a subresource. we don't support suberesource for now. + // if a resource contains a "/" it's referencing a subresource. we don't support subresource for now. if resource.Kind == gvk.Kind && !strings.Contains(resource.Name, "/") { res = resource res.Group = gvk.Group diff --git a/vendor/helm.sh/helm/v3/pkg/helmpath/lazypath.go b/vendor/helm.sh/helm/v3/pkg/helmpath/lazypath.go index 22d7bf0a1..6b4f1fc77 100644 --- a/vendor/helm.sh/helm/v3/pkg/helmpath/lazypath.go +++ b/vendor/helm.sh/helm/v3/pkg/helmpath/lazypath.go @@ -34,7 +34,7 @@ const ( DataHomeEnvVar = "HELM_DATA_HOME" ) -// lazypath is an lazy-loaded path buffer for the XDG base directory specification. +// lazypath is a lazy-loaded path buffer for the XDG base directory specification. type lazypath string func (l lazypath) path(helmEnvVar, xdgEnvVar string, defaultFn func() string, elem ...string) string { diff --git a/vendor/helm.sh/helm/v3/pkg/ignore/doc.go b/vendor/helm.sh/helm/v3/pkg/ignore/doc.go index 5245d410e..1f5e91847 100644 --- a/vendor/helm.sh/helm/v3/pkg/ignore/doc.go +++ b/vendor/helm.sh/helm/v3/pkg/ignore/doc.go @@ -26,7 +26,7 @@ The formatting rules are as follows: - Parsing is line-by-line - Empty lines are ignored - - Lines the begin with # (comments) will be ignored + - Lines that begin with # (comments) will be ignored - Leading and trailing spaces are always ignored - Inline comments are NOT supported ('foo* # Any foo' does not contain a comment) - There is no support for multi-line patterns diff --git a/vendor/helm.sh/helm/v3/pkg/kube/client.go b/vendor/helm.sh/helm/v3/pkg/kube/client.go index 9df833a43..d979fd22c 100644 --- a/vendor/helm.sh/helm/v3/pkg/kube/client.go +++ b/vendor/helm.sh/helm/v3/pkg/kube/client.go @@ -124,7 +124,7 @@ func (c *Client) getKubeClient() (*kubernetes.Clientset, error) { func (c *Client) IsReachable() error { client, err := c.getKubeClient() if err == genericclioptions.ErrEmptyConfig { - // re-replace kubernetes ErrEmptyConfig error with a friendy error + // re-replace kubernetes ErrEmptyConfig error with a friendly error // moar workarounds for Kubernetes API breaking. return errors.New("Kubernetes cluster unreachable") } @@ -635,7 +635,7 @@ func createPatch(target *resource.Info, current runtime.Object) ([]byte, types.P // Get a versioned object versionedObject := AsVersioned(target) - // Unstructured objects, such as CRDs, may not have an not registered error + // Unstructured objects, such as CRDs, may not have a not registered error // returned from ConvertToVersion. Anything that's unstructured should // use the jsonpatch.CreateMergePatch. Strategic Merge Patch is not supported // on objects like CRDs. diff --git a/vendor/helm.sh/helm/v3/pkg/kube/ready.go b/vendor/helm.sh/helm/v3/pkg/kube/ready.go index b2d26ba76..55c4a39bf 100644 --- a/vendor/helm.sh/helm/v3/pkg/kube/ready.go +++ b/vendor/helm.sh/helm/v3/pkg/kube/ready.go @@ -426,7 +426,7 @@ func (c *ReadyChecker) statefulSetReady(sts *appsv1.StatefulSet) bool { return false } // This check only makes sense when all partitions are being upgraded otherwise during a - // partioned rolling upgrade, this condition will never evaluate to true, leading to + // partitioned rolling upgrade, this condition will never evaluate to true, leading to // error. if partition == 0 && sts.Status.CurrentRevision != sts.Status.UpdateRevision { c.log("StatefulSet is not ready: %s/%s. currentRevision %s does not yet match updateRevision %s", sts.Namespace, sts.Name, sts.Status.CurrentRevision, sts.Status.UpdateRevision) diff --git a/vendor/helm.sh/helm/v3/pkg/registry/util.go b/vendor/helm.sh/helm/v3/pkg/registry/util.go index 45fbdd0b5..727cdae03 100644 --- a/vendor/helm.sh/helm/v3/pkg/registry/util.go +++ b/vendor/helm.sh/helm/v3/pkg/registry/util.go @@ -65,8 +65,7 @@ func GetTagMatchingVersionOrConstraint(tags []string, versionString string) (str // If string is empty, set wildcard constraint constraint, _ = semver.NewConstraint("*") } else { - // when customer input exact version, check whether have exact match - // one first + // when customer inputs specific version, check whether there's an exact match first for _, v := range tags { if versionString == v { return v, nil diff --git a/vendor/helm.sh/helm/v3/pkg/release/status.go b/vendor/helm.sh/helm/v3/pkg/release/status.go index e0e3ed62a..edd27a5f1 100644 --- a/vendor/helm.sh/helm/v3/pkg/release/status.go +++ b/vendor/helm.sh/helm/v3/pkg/release/status.go @@ -31,13 +31,13 @@ const ( StatusSuperseded Status = "superseded" // StatusFailed indicates that the release was not successfully deployed. StatusFailed Status = "failed" - // StatusUninstalling indicates that a uninstall operation is underway. + // StatusUninstalling indicates that an uninstall operation is underway. StatusUninstalling Status = "uninstalling" // StatusPendingInstall indicates that an install operation is underway. StatusPendingInstall Status = "pending-install" // StatusPendingUpgrade indicates that an upgrade operation is underway. StatusPendingUpgrade Status = "pending-upgrade" - // StatusPendingRollback indicates that an rollback operation is underway. + // StatusPendingRollback indicates that a rollback operation is underway. StatusPendingRollback Status = "pending-rollback" ) diff --git a/vendor/helm.sh/helm/v3/pkg/repo/index.go b/vendor/helm.sh/helm/v3/pkg/repo/index.go index 40b11c5cf..e1ce3c62d 100644 --- a/vendor/helm.sh/helm/v3/pkg/repo/index.go +++ b/vendor/helm.sh/helm/v3/pkg/repo/index.go @@ -200,7 +200,7 @@ func (i IndexFile) Get(name, version string) (*ChartVersion, error) { } } - // when customer input exact version, check whether have exact match one first + // when customer inputs specific version, check whether there's an exact match first if len(version) != 0 { for _, ver := range vs { if version == ver.Version { @@ -371,6 +371,8 @@ func loadIndex(data []byte, source string) (*IndexFile, error) { cvs = append(cvs[:idx], cvs[idx+1:]...) } } + // adjust slice to only contain a set of valid versions + i.Entries[name] = cvs } i.SortEntries() if i.APIVersion == "" { @@ -397,7 +399,7 @@ func jsonOrYamlUnmarshal(b []byte, i interface{}) error { // the error isn't important for index loading // // In particular, charts may introduce validations that don't impact repository indexes -// And repository indexes may be generated by older/non-complient software, which doesn't +// And repository indexes may be generated by older/non-compliant software, which doesn't // conform to all validations. func ignoreSkippableChartValidationError(err error) error { verr, ok := err.(chart.ValidationError) diff --git a/vendor/helm.sh/helm/v3/pkg/storage/driver/sql.go b/vendor/helm.sh/helm/v3/pkg/storage/driver/sql.go index 2ef951184..33bde9b6a 100644 --- a/vendor/helm.sh/helm/v3/pkg/storage/driver/sql.go +++ b/vendor/helm.sh/helm/v3/pkg/storage/driver/sql.go @@ -72,8 +72,8 @@ const ( // Following limits based on k8s labels limits - https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set const ( - sqlCustomLabelsTableKeyMaxLenght = 253 + 1 + 63 - sqlCustomLabelsTableValueMaxLenght = 63 + sqlCustomLabelsTableKeyMaxLength = 253 + 1 + 63 + sqlCustomLabelsTableValueMaxLength = 63 ) const ( @@ -119,7 +119,7 @@ func (s *SQL) checkAlreadyApplied(migrations []*migrate.Migration) bool { } } - // check if all migrations appliyed + // check if all migrations applied if len(migrationsIDs) != 0 { for id := range migrationsIDs { s.Log("checkAlreadyApplied: find unapplied migration (id: %v)", id) @@ -204,7 +204,7 @@ func (s *SQL) ensureDBSetup() error { CREATE TABLE %s ( %s VARCHAR(64), %s VARCHAR(67), - %s VARCHAR(%d), + %s VARCHAR(%d), %s VARCHAR(%d) ); CREATE INDEX ON %s (%s, %s); @@ -216,9 +216,9 @@ func (s *SQL) ensureDBSetup() error { sqlCustomLabelsTableReleaseKeyColumn, sqlCustomLabelsTableReleaseNamespaceColumn, sqlCustomLabelsTableKeyColumn, - sqlCustomLabelsTableKeyMaxLenght, + sqlCustomLabelsTableKeyMaxLength, sqlCustomLabelsTableValueColumn, - sqlCustomLabelsTableValueMaxLenght, + sqlCustomLabelsTableValueMaxLength, sqlCustomLabelsTableName, sqlCustomLabelsTableReleaseKeyColumn, sqlCustomLabelsTableReleaseNamespaceColumn, diff --git a/vendor/helm.sh/helm/v3/pkg/strvals/parser.go b/vendor/helm.sh/helm/v3/pkg/strvals/parser.go index 2828f20c0..a0e8d66d1 100644 --- a/vendor/helm.sh/helm/v3/pkg/strvals/parser.go +++ b/vendor/helm.sh/helm/v3/pkg/strvals/parser.go @@ -436,7 +436,7 @@ func (t *parser) listItem(list []interface{}, i, nestedNameLevel int) ([]interfa // check for an empty value // read and consume optional spaces until comma or EOF (empty val) or any other char (not empty val) -// comma and spaces are consumed, while any other char is not cosumed +// comma and spaces are consumed, while any other char is not consumed func (t *parser) emptyVal() (bool, error) { for { r, _, e := t.sc.ReadRune() diff --git a/vendor/helm.sh/helm/v3/pkg/time/time.go b/vendor/helm.sh/helm/v3/pkg/time/time.go index 44f3fedfb..1abe8ae3d 100644 --- a/vendor/helm.sh/helm/v3/pkg/time/time.go +++ b/vendor/helm.sh/helm/v3/pkg/time/time.go @@ -15,7 +15,7 @@ limitations under the License. */ // Package time contains a wrapper for time.Time in the standard library and -// associated methods. This package mainly exists to workaround an issue in Go +// associated methods. This package mainly exists to work around an issue in Go // where the serializer doesn't omit an empty value for time: // https://github.com/golang/go/issues/11939. As such, this can be removed if a // proposal is ever accepted for Go diff --git a/vendor/k8s.io/cli-runtime/pkg/printers/json.go b/vendor/k8s.io/cli-runtime/pkg/printers/json.go index 8ab2235f8..7d14a4e5a 100644 --- a/vendor/k8s.io/cli-runtime/pkg/printers/json.go +++ b/vendor/k8s.io/cli-runtime/pkg/printers/json.go @@ -19,6 +19,7 @@ package printers import ( "bytes" "encoding/json" + "errors" "fmt" "io" "reflect" @@ -36,13 +37,13 @@ func (p *JSONPrinter) PrintObj(obj runtime.Object, w io.Writer) error { // we need an actual value in order to retrieve the package path for an object. // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers. if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } switch obj := obj.(type) { case *metav1.WatchEvent: if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj.Object.Object)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } data, err := json.Marshal(obj) if err != nil { diff --git a/vendor/k8s.io/cli-runtime/pkg/printers/jsonpath.go b/vendor/k8s.io/cli-runtime/pkg/printers/jsonpath.go index 769960d66..216449ec4 100644 --- a/vendor/k8s.io/cli-runtime/pkg/printers/jsonpath.go +++ b/vendor/k8s.io/cli-runtime/pkg/printers/jsonpath.go @@ -19,6 +19,7 @@ package printers import ( "bytes" "encoding/json" + "errors" "fmt" "io" "reflect" @@ -119,7 +120,7 @@ func (j *JSONPathPrinter) PrintObj(obj runtime.Object, w io.Writer) error { // we need an actual value in order to retrieve the package path for an object. // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers. if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } var queryObj interface{} = obj diff --git a/vendor/k8s.io/cli-runtime/pkg/printers/name.go b/vendor/k8s.io/cli-runtime/pkg/printers/name.go index 086166af2..1d2fe7f96 100644 --- a/vendor/k8s.io/cli-runtime/pkg/printers/name.go +++ b/vendor/k8s.io/cli-runtime/pkg/printers/name.go @@ -17,6 +17,7 @@ limitations under the License. package printers import ( + "errors" "fmt" "io" "reflect" @@ -52,7 +53,7 @@ func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error { // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers. // we need an actual value in order to retrieve the package path for an object. if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } if meta.IsListType(obj) { diff --git a/vendor/k8s.io/cli-runtime/pkg/printers/template.go b/vendor/k8s.io/cli-runtime/pkg/printers/template.go index ccff54226..4b08573ce 100644 --- a/vendor/k8s.io/cli-runtime/pkg/printers/template.go +++ b/vendor/k8s.io/cli-runtime/pkg/printers/template.go @@ -18,6 +18,7 @@ package printers import ( "encoding/base64" + "errors" "fmt" "io" "reflect" @@ -61,7 +62,7 @@ func (p *GoTemplatePrinter) AllowMissingKeys(allow bool) { // PrintObj formats the obj with the Go Template. func (p *GoTemplatePrinter) PrintObj(obj runtime.Object, w io.Writer) error { if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } var data []byte diff --git a/vendor/k8s.io/cli-runtime/pkg/printers/yaml.go b/vendor/k8s.io/cli-runtime/pkg/printers/yaml.go index 9c444bdc2..8c6be82fe 100644 --- a/vendor/k8s.io/cli-runtime/pkg/printers/yaml.go +++ b/vendor/k8s.io/cli-runtime/pkg/printers/yaml.go @@ -17,6 +17,7 @@ limitations under the License. package printers import ( + "errors" "fmt" "io" "reflect" @@ -42,7 +43,7 @@ func (p *YAMLPrinter) PrintObj(obj runtime.Object, w io.Writer) error { // we need an actual value in order to retrieve the package path for an object. // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers. if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } count := atomic.AddInt64(&p.printCount, 1) @@ -55,7 +56,7 @@ func (p *YAMLPrinter) PrintObj(obj runtime.Object, w io.Writer) error { switch obj := obj.(type) { case *metav1.WatchEvent: if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj.Object.Object)).Type().PkgPath()) { - return fmt.Errorf(InternalObjectPrinterErr) + return errors.New(InternalObjectPrinterErr) } data, err := yaml.Marshal(obj) if err != nil { diff --git a/vendor/k8s.io/cli-runtime/pkg/resource/builder.go b/vendor/k8s.io/cli-runtime/pkg/resource/builder.go index 47ec83bbb..5f8fdcd9b 100644 --- a/vendor/k8s.io/cli-runtime/pkg/resource/builder.go +++ b/vendor/k8s.io/cli-runtime/pkg/resource/builder.go @@ -1030,7 +1030,7 @@ func (b *Builder) visitByResource() *Result { if b.allNamespace { errMsg = "a resource cannot be retrieved by name across all namespaces" } - return result.withError(fmt.Errorf(errMsg)) + return result.withError(errors.New(errMsg)) } } @@ -1093,7 +1093,7 @@ func (b *Builder) visitByName() *Result { if b.allNamespace { errMsg = "a resource cannot be retrieved by name across all namespaces" } - return result.withError(fmt.Errorf(errMsg)) + return result.withError(errors.New(errMsg)) } } diff --git a/vendor/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go b/vendor/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go index b9000a08a..15db8e43d 100644 --- a/vendor/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go +++ b/vendor/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go @@ -21,11 +21,11 @@ import ( "fmt" openapi_v2 "github.com/google/gnostic-models/openapiv2" - yaml "gopkg.in/yaml.v2" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" + yaml "sigs.k8s.io/yaml/goyaml.v2" ) func NewQueryParamVerifier(dynamicClient dynamic.Interface, openAPIGetter discovery.OpenAPISchemaInterface, queryParam VerifiableQueryParam) *QueryParamVerifier { diff --git a/vendor/modules.txt b/vendor/modules.txt index eb6ed4e54..ca29bda79 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -27,9 +27,6 @@ github.com/Masterminds/sprig/v3 # github.com/Masterminds/squirrel v1.5.4 ## explicit; go 1.14 github.com/Masterminds/squirrel -# github.com/Microsoft/hcsshim v0.11.4 -## explicit; go 1.18 -github.com/Microsoft/hcsshim/osversion # github.com/NVIDIA/go-nvlib v0.7.0 ## explicit; go 1.20 github.com/NVIDIA/go-nvlib/pkg/nvmdev @@ -74,8 +71,8 @@ github.com/chai2010/gettext-go github.com/chai2010/gettext-go/mo github.com/chai2010/gettext-go/plural github.com/chai2010/gettext-go/po -# github.com/containerd/containerd v1.7.12 -## explicit; go 1.19 +# github.com/containerd/containerd v1.7.23 +## explicit; go 1.21 github.com/containerd/containerd/archive/compression github.com/containerd/containerd/content github.com/containerd/containerd/content/local @@ -85,9 +82,7 @@ github.com/containerd/containerd/images github.com/containerd/containerd/labels github.com/containerd/containerd/log github.com/containerd/containerd/pkg/randutil -github.com/containerd/containerd/platforms github.com/containerd/containerd/reference -github.com/containerd/containerd/reference/docker github.com/containerd/containerd/remotes github.com/containerd/containerd/remotes/docker github.com/containerd/containerd/remotes/docker/auth @@ -95,19 +90,25 @@ github.com/containerd/containerd/remotes/docker/schema1 github.com/containerd/containerd/remotes/errors github.com/containerd/containerd/tracing github.com/containerd/containerd/version +# github.com/containerd/errdefs v0.3.0 +## explicit; go 1.20 +github.com/containerd/errdefs # github.com/containerd/log v0.1.0 ## explicit; go 1.20 github.com/containerd/log +# github.com/containerd/platforms v0.2.1 +## explicit; go 1.20 +github.com/containerd/platforms # github.com/cpuguy83/go-md2man/v2 v2.0.5 ## explicit; go 1.11 github.com/cpuguy83/go-md2man/v2/md2man -# github.com/cyphar/filepath-securejoin v0.3.1 -## explicit; go 1.20 +# github.com/cyphar/filepath-securejoin v0.3.4 +## explicit; go 1.21 github.com/cyphar/filepath-securejoin # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew -# github.com/distribution/reference v0.5.0 +# github.com/distribution/reference v0.6.0 ## explicit; go 1.20 github.com/distribution/reference # github.com/docker/cli v25.0.1+incompatible @@ -339,8 +340,8 @@ github.com/mitchellh/go-wordwrap # github.com/mitchellh/reflectwalk v1.0.2 ## explicit github.com/mitchellh/reflectwalk -# github.com/mittwald/go-helm-client v0.12.14 -## explicit; go 1.22.0 +# github.com/mittwald/go-helm-client v0.12.16 +## explicit; go 1.23.0 github.com/mittwald/go-helm-client github.com/mittwald/go-helm-client/values # github.com/moby/locker v1.0.1 @@ -589,14 +590,6 @@ go.opentelemetry.io/otel/metric/embedded ## explicit; go 1.21 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded -# go.starlark.net v0.0.0-20231121155337-90ade8b19d09 -## explicit; go 1.18 -go.starlark.net/internal/compile -go.starlark.net/internal/spell -go.starlark.net/resolve -go.starlark.net/starlark -go.starlark.net/starlarkstruct -go.starlark.net/syntax # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr @@ -611,7 +604,7 @@ 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.28.0 +# golang.org/x/crypto v0.31.0 ## explicit; go 1.20 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish @@ -648,19 +641,19 @@ golang.org/x/net/websocket ## explicit; go 1.18 golang.org/x/oauth2 golang.org/x/oauth2/internal -# golang.org/x/sync v0.8.0 +# golang.org/x/sync v0.10.0 ## explicit; go 1.18 golang.org/x/sync/errgroup golang.org/x/sync/semaphore -# golang.org/x/sys v0.26.0 +# golang.org/x/sys v0.28.0 ## explicit; go 1.18 golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.25.0 +# golang.org/x/term v0.27.0 ## explicit; go 1.18 golang.org/x/term -# golang.org/x/text v0.19.0 +# golang.org/x/text v0.21.0 ## explicit; go 1.18 golang.org/x/text/encoding golang.org/x/text/encoding/charmap @@ -748,13 +741,10 @@ gopkg.in/evanphx/json-patch.v4 # gopkg.in/inf.v0 v0.9.1 ## explicit gopkg.in/inf.v0 -# gopkg.in/yaml.v2 v2.4.0 -## explicit; go 1.15 -gopkg.in/yaml.v2 # gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 -# helm.sh/helm/v3 v3.16.1 +# helm.sh/helm/v3 v3.16.4 ## explicit; go 1.22.0 helm.sh/helm/v3/internal/fileutil helm.sh/helm/v3/internal/resolver @@ -937,8 +927,8 @@ k8s.io/apimachinery/third_party/forked/golang/reflect # k8s.io/apiserver v0.32.0 ## explicit; go 1.23.0 k8s.io/apiserver/pkg/endpoints/deprecation -# k8s.io/cli-runtime v0.31.1 -## explicit; go 1.22.0 +# k8s.io/cli-runtime v0.32.0 +## explicit; go 1.23.0 k8s.io/cli-runtime/pkg/genericclioptions k8s.io/cli-runtime/pkg/genericiooptions k8s.io/cli-runtime/pkg/printers @@ -1262,7 +1252,7 @@ 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/validation/spec -# k8s.io/kubectl v0.31.0 +# k8s.io/kubectl v0.31.3 ## explicit; go 1.22.0 k8s.io/kubectl/pkg/cmd/util k8s.io/kubectl/pkg/drain @@ -1351,8 +1341,8 @@ sigs.k8s.io/controller-runtime/pkg/webhook/internal/metrics ## explicit; go 1.21 sigs.k8s.io/json sigs.k8s.io/json/internal/golang/encoding/json -# sigs.k8s.io/kustomize/api v0.17.2 -## explicit; go 1.21 +# sigs.k8s.io/kustomize/api v0.18.0 +## explicit; go 1.22.7 sigs.k8s.io/kustomize/api/filters/annotations sigs.k8s.io/kustomize/api/filters/fieldspec sigs.k8s.io/kustomize/api/filters/filtersutil @@ -1397,8 +1387,8 @@ sigs.k8s.io/kustomize/api/provider sigs.k8s.io/kustomize/api/resmap sigs.k8s.io/kustomize/api/resource sigs.k8s.io/kustomize/api/types -# sigs.k8s.io/kustomize/kyaml v0.17.1 -## explicit; go 1.21 +# sigs.k8s.io/kustomize/kyaml v0.18.1 +## explicit; go 1.22.7 sigs.k8s.io/kustomize/kyaml/comments sigs.k8s.io/kustomize/kyaml/errors sigs.k8s.io/kustomize/kyaml/ext @@ -1407,10 +1397,7 @@ sigs.k8s.io/kustomize/kyaml/filesys sigs.k8s.io/kustomize/kyaml/fn/runtime/container sigs.k8s.io/kustomize/kyaml/fn/runtime/exec sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil -sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark -sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util sigs.k8s.io/kustomize/kyaml/kio -sigs.k8s.io/kustomize/kyaml/kio/filters sigs.k8s.io/kustomize/kyaml/kio/kioutil sigs.k8s.io/kustomize/kyaml/openapi sigs.k8s.io/kustomize/kyaml/openapi/kubernetesapi @@ -1430,7 +1417,6 @@ sigs.k8s.io/kustomize/kyaml/yaml/internal/k8sgen/pkg/util/sets sigs.k8s.io/kustomize/kyaml/yaml/internal/k8sgen/pkg/util/validation sigs.k8s.io/kustomize/kyaml/yaml/internal/k8sgen/pkg/util/validation/field sigs.k8s.io/kustomize/kyaml/yaml/merge2 -sigs.k8s.io/kustomize/kyaml/yaml/merge3 sigs.k8s.io/kustomize/kyaml/yaml/schema sigs.k8s.io/kustomize/kyaml/yaml/walk # sigs.k8s.io/structured-merge-diff/v4 v4.4.2 diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go index c93c18c00..06d13b526 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go @@ -10,6 +10,7 @@ import ( "os/exec" "path/filepath" "regexp" + "slices" "strings" "sigs.k8s.io/kustomize/api/resmap" @@ -62,6 +63,9 @@ func (p *HelmChartInflationGeneratorPlugin) Config( if len(h.GeneralConfig().HelmConfig.ApiVersions) != 0 { p.HelmChart.ApiVersions = h.GeneralConfig().HelmConfig.ApiVersions } + if h.GeneralConfig().HelmConfig.Debug { + p.HelmChart.Debug = h.GeneralConfig().HelmConfig.Debug + } p.h = h if err = yaml.Unmarshal(config, p); err != nil { @@ -168,13 +172,17 @@ func (p *HelmChartInflationGeneratorPlugin) runHelmCommand( fmt.Sprintf("HELM_DATA_HOME=%s/.data", p.ConfigHome)} cmd.Env = append(os.Environ(), env...) err := cmd.Run() + errorOutput := stderr.String() + if slices.Contains(args, "--debug") { + errorOutput = " Helm stack trace:\n" + errorOutput + "\nHelm template:\n" + stdout.String() + "\n" + } if err != nil { helm := p.h.GeneralConfig().HelmConfig.Command err = errors.WrapPrefixf( fmt.Errorf( "unable to run: '%s %s' with env=%s (is '%s' installed?): %w", helm, strings.Join(args, " "), env, helm, err), - stderr.String(), + errorOutput, ) } return stdout.Bytes(), err diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go index c50f627fe..90e290719 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go @@ -151,6 +151,9 @@ func gvkLessThan(gvk1, gvk2 resid.Gvk, typeOrders map[string]int) bool { if index1 != index2 { return index1 < index2 } + if (gvk1.Kind == types.NamespaceKind && gvk2.Kind == types.NamespaceKind) && (gvk1.Group == "" || gvk2.Group == "") { + return legacyGVKSortString(gvk1) > legacyGVKSortString(gvk2) + } return legacyGVKSortString(gvk1) < legacyGVKSortString(gvk2) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/konfig/builtinpluginconsts/namereference.go b/vendor/sigs.k8s.io/kustomize/api/internal/konfig/builtinpluginconsts/namereference.go index 658b0c34b..383dcf83e 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/konfig/builtinpluginconsts/namereference.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/konfig/builtinpluginconsts/namereference.go @@ -421,6 +421,13 @@ nameReference: fieldSpecs: - path: spec/ingressClassName kind: Ingress + +- kind: ValidatingAdmissionPolicy + group: admissionregistration.k8s.io + fieldSpecs: + - path: spec/policyName + kind: ValidatingAdmissionPolicyBinding + group: admissionregistration.k8s.io ` ) diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/fnplugin/fnplugin.go b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/fnplugin/fnplugin.go index 3a033d727..0ec067562 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/fnplugin/fnplugin.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/fnplugin/fnplugin.go @@ -77,7 +77,6 @@ func NewFnPlugin(o *types.FnPluginLoadingOptions) *FnPlugin { runFns: runfn.RunFns{ Functions: []*yaml.RNode{}, Network: o.Network, - EnableStarlark: o.EnableStar, EnableExec: o.EnableExec, StorageMounts: toStorageMounts(o.Mounts), Env: o.Env, diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go index 44c82bc59..5f1d1095a 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go @@ -449,9 +449,6 @@ func (kt *KustTarget) accumulateResources( ra, err = kt.accumulateDirectory(ra, ldr, false) } if err != nil { - if kusterr.IsMalformedYAMLError(errF) { // Some error occurred while tyring to decode YAML file - return nil, errF - } return nil, errors.WrapPrefixf( err, "accumulation err='%s'", errF.Error()) } @@ -460,7 +457,7 @@ func (kt *KustTarget) accumulateResources( return ra, nil } -// accumulateResources fills the given resourceAccumulator +// accumulateComponents fills the given resourceAccumulator // with resources read from the given list of paths. func (kt *KustTarget) accumulateComponents( ra *accumulator.ResAccumulator, paths []string) (*accumulator.ResAccumulator, error) { diff --git a/vendor/sigs.k8s.io/kustomize/api/resource/factory.go b/vendor/sigs.k8s.io/kustomize/api/resource/factory.go index fef2f6e49..a42f93bb8 100644 --- a/vendor/sigs.k8s.io/kustomize/api/resource/factory.go +++ b/vendor/sigs.k8s.io/kustomize/api/resource/factory.go @@ -202,7 +202,10 @@ func (rf *Factory) inlineAnyEmbeddedLists( } items, ok := m["items"] if !ok { - // treat as an empty list + // Items field is not present. + // This is not a collections resource. + // read more https://kubernetes.io/docs/reference/using-api/api-concepts/#collections + result = append(result, n0) continue } slice, ok := items.([]interface{}) diff --git a/vendor/sigs.k8s.io/kustomize/api/types/helmchartargs.go b/vendor/sigs.k8s.io/kustomize/api/types/helmchartargs.go index 1ed89c01c..b96fbfb16 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/helmchartargs.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/helmchartargs.go @@ -96,6 +96,9 @@ type HelmChart struct { // SkipTests skips tests from templated output. SkipTests bool `json:"skipTests,omitempty" yaml:"skipTests,omitempty"` + + // debug enables debug output from the Helm chart inflator generator. + Debug bool `json:"debug,omitempty" yaml:"debug,omitempty"` } // HelmChartArgs contains arguments to helm. @@ -188,5 +191,8 @@ func (h HelmChart) AsHelmArgs(absChartHome string) []string { if h.SkipHooks { args = append(args, "--no-hooks") } + if h.Debug { + args = append(args, "--debug") + } return args } diff --git a/vendor/sigs.k8s.io/kustomize/api/types/kustomization.go b/vendor/sigs.k8s.io/kustomize/api/types/kustomization.go index f86ec0b9e..6caa29664 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/kustomization.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/kustomization.go @@ -22,6 +22,7 @@ const ( MetadataNamespacePath = "metadata/namespace" MetadataNamespaceApiVersion = "v1" MetadataNamePath = "metadata/name" + NamespaceKind = "Namespace" OriginAnnotations = "originAnnotations" TransformerAnnotations = "transformerAnnotations" @@ -55,6 +56,7 @@ type Kustomization struct { // Namespace to add to all objects. Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` + // Deprecated: Use the Labels field instead, which provides a superset of the functionality of CommonLabels. // CommonLabels to add to all objects and selectors. CommonLabels map[string]string `json:"commonLabels,omitempty" yaml:"commonLabels,omitempty"` diff --git a/vendor/sigs.k8s.io/kustomize/api/types/pluginconfig.go b/vendor/sigs.k8s.io/kustomize/api/types/pluginconfig.go index aa511ae79..9721eb724 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/pluginconfig.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/pluginconfig.go @@ -8,6 +8,7 @@ type HelmConfig struct { Command string ApiVersions []string KubeVersion string + Debug bool } // PluginConfig holds plugin configuration. @@ -27,7 +28,6 @@ type PluginConfig struct { func EnabledPluginConfig(b BuiltinPluginLoadingOptions) (pc *PluginConfig) { pc = MakePluginConfig(PluginRestrictionsNone, b) - pc.FnpLoadingOptions.EnableStar = true pc.HelmConfig.Enabled = true // If this command is not on PATH, tests needing it should skip. pc.HelmConfig.Command = "helmV3" diff --git a/vendor/sigs.k8s.io/kustomize/api/types/pluginrestrictions.go b/vendor/sigs.k8s.io/kustomize/api/types/pluginrestrictions.go index 88b03b3f5..0e4ee42e4 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/pluginrestrictions.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/pluginrestrictions.go @@ -46,8 +46,6 @@ const ( type FnPluginLoadingOptions struct { // Allow to run executables EnableExec bool - // Allow to run starlark - EnableStar bool // Allow container access to network Network bool NetworkName string diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/container/container.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/container/container.go index 76b51a8c5..62aa76f53 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/container/container.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/container/container.go @@ -167,7 +167,7 @@ func (c *Filter) setupExec() error { return nil } -// getArgs returns the command + args to run to spawn the container +// getCommand returns the command + args to run to spawn the container func (c *Filter) getCommand() (string, []string) { network := runtimeutil.NetworkNameNone if c.ContainerSpec.Network { diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil/functiontypes.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil/functiontypes.go index f0448ea28..f56962c14 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil/functiontypes.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil/functiontypes.go @@ -132,9 +132,6 @@ type FunctionSpec struct { // Container is the spec for running a function as a container Container ContainerSpec `json:"container,omitempty" yaml:"container,omitempty"` - // Starlark is the spec for running a function as a starlark script - Starlark StarlarkSpec `json:"starlark,omitempty" yaml:"starlark,omitempty"` - // ExecSpec is the spec for running a function as an executable Exec ExecSpec `json:"exec,omitempty" yaml:"exec,omitempty"` } @@ -158,17 +155,6 @@ type ContainerSpec struct { Env []string `json:"envs,omitempty" yaml:"envs,omitempty"` } -// StarlarkSpec defines how to run a function as a starlark program -type StarlarkSpec struct { - Name string `json:"name,omitempty" yaml:"name,omitempty"` - - // Path specifies a path to a starlark script - Path string `json:"path,omitempty" yaml:"path,omitempty"` - - // URL specifies a url containing a starlark script - URL string `json:"url,omitempty" yaml:"url,omitempty"` -} - // StorageMount represents a container's mounted storage option(s) type StorageMount struct { // Type of mount e.g. bind mount, local volume, etc. diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/context.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/context.go deleted file mode 100644 index bbf07f66c..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/context.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package starlark - -import ( - "encoding/json" - "os" - "strings" - - "go.starlark.net/starlark" - "go.starlark.net/starlarkstruct" - "sigs.k8s.io/kustomize/kyaml/errors" - "sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util" - "sigs.k8s.io/kustomize/kyaml/openapi" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -type Context struct { - resourceList starlark.Value -} - -func (c *Context) predeclared() (starlark.StringDict, error) { - e, err := env() - if err != nil { - return nil, err - } - oa, err := oa() - if err != nil { - return nil, err - } - dict := starlark.StringDict{ - "resource_list": c.resourceList, - "open_api": oa, - "environment": e, - } - - return starlark.StringDict{ - "ctx": starlarkstruct.FromStringDict(starlarkstruct.Default, dict), - }, nil -} - -func oa() (starlark.Value, error) { - return interfaceToValue(openapi.Schema()) -} - -func env() (starlark.Value, error) { - env := map[string]interface{}{} - for _, e := range os.Environ() { - pair := strings.SplitN(e, "=", 2) - if len(pair) < 2 { - continue - } - env[pair[0]] = pair[1] - } - value, err := util.Marshal(env) - if err != nil { - return nil, errors.Wrap(err) - } - return value, nil -} - -func interfaceToValue(i interface{}) (starlark.Value, error) { - b, err := json.Marshal(i) - if err != nil { - return nil, err - } - - var in map[string]interface{} - if err := yaml.Unmarshal(b, &in); err != nil { - return nil, errors.Wrap(err) - } - - value, err := util.Marshal(in) - if err != nil { - return nil, errors.Wrap(err) - } - return value, nil -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/doc.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/doc.go deleted file mode 100644 index 70f0a2c7b..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/doc.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -// Package starlark contains a kio.Filter which can be applied to resources to transform -// them through starlark program. -// -// Starlark has become a popular runtime embedding in go programs, especially for Kubernetes -// and data processing. -// Examples: https://github.com/cruise-automation/isopod, https://qri.io/docs/starlark/starlib, -// https://github.com/stripe/skycfg, https://github.com/k14s/ytt -// -// The resources are provided to the starlark program through the global variable "resourceList". -// "resourceList" is a dictionary containing an "items" field with a list of resources. -// The starlark modified "resourceList" is the Filter output. -// -// After being run through the starlark program, the filter will copy the comments from the input -// resources to restore them -- due to them being dropped as a result of serializing the resources -// as starlark values. -// -// "resourceList" may also contain a "functionConfig" entry to configure the starlark script itself. -// Changes made by the starlark program to the "functionConfig" will be reflected in the -// Filter.FunctionConfig value. -// -// The Filter will also format the output so that output has the preferred field ordering -// rather than an alphabetical field ordering. -// -// The resourceList variable adheres to the kustomize function spec as specified by: -// https://github.com/kubernetes-sigs/kustomize/blob/master/cmd/config/docs/api-conventions/functions-spec.md -// -// All items in the resourceList are resources represented as starlark dictionaries/ -// The items in the resourceList respect the io spec specified by: -// https://github.com/kubernetes-sigs/kustomize/blob/master/cmd/config/docs/api-conventions/config-io.md -// -// The starlark language spec can be found here: -// https://github.com/google/starlark-go/blob/master/doc/spec.md -package starlark diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/starlark.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/starlark.go deleted file mode 100644 index aeeeb81ed..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/starlark.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package starlark - -import ( - "bytes" - "fmt" - "io" - "net/http" - "os" - - "go.starlark.net/starlark" - "sigs.k8s.io/kustomize/kyaml/errors" - "sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil" - "sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util" - "sigs.k8s.io/kustomize/kyaml/kio/filters" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -// Filter transforms a set of resources through the provided program -type Filter struct { - Name string - - // Program is a starlark script which will be run against the resources - Program string - - // URL is the url of a starlark program to fetch and run - URL string - - // Path is the path to a starlark program to read and run - Path string - - runtimeutil.FunctionFilter -} - -func (sf *Filter) String() string { - return fmt.Sprintf( - "name: %v path: %v url: %v program: %v", sf.Name, sf.Path, sf.URL, sf.Program) -} - -func (sf *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { - if err := sf.setup(); err != nil { - return nil, err - } - sf.FunctionFilter.Run = sf.Run - - return sf.FunctionFilter.Filter(nodes) -} - -func (sf *Filter) setup() error { - if (sf.URL != "" && sf.Path != "") || - (sf.URL != "" && sf.Program != "") || - (sf.Path != "" && sf.Program != "") { - return errors.Errorf("Filter Path, Program and URL are mutually exclusive") - } - - // read the program from a file - if sf.Path != "" { - b, err := os.ReadFile(sf.Path) - if err != nil { - return err - } - sf.Program = string(b) - } - - // read the program from a URL - if sf.URL != "" { - err := func() error { - resp, err := http.Get(sf.URL) - if err != nil { - return err - } - defer resp.Body.Close() - b, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - sf.Program = string(b) - return nil - }() - if err != nil { - return err - } - } - - return nil -} - -func (sf *Filter) Run(reader io.Reader, writer io.Writer) error { - // retain map of inputs to outputs by id so if the name is changed by the - // starlark program, we are able to match the same resources - value, err := sf.readResourceList(reader) - if err != nil { - return errors.Wrap(err) - } - - // run the starlark as program as transformation function - thread := &starlark.Thread{Name: sf.Name} - - ctx := &Context{resourceList: value} - pd, err := ctx.predeclared() - if err != nil { - return errors.Wrap(err) - } - _, err = starlark.ExecFile(thread, sf.Name, sf.Program, pd) - if err != nil { - return errors.Wrap(err) - } - - return sf.writeResourceList(value, writer) -} - -// inputToResourceList transforms input into a starlark.Value -func (sf *Filter) readResourceList(reader io.Reader) (starlark.Value, error) { - // read and parse the inputs - rl := bytes.Buffer{} - _, err := rl.ReadFrom(reader) - if err != nil { - return nil, errors.Wrap(err) - } - rn, err := yaml.Parse(rl.String()) - if err != nil { - return nil, errors.Wrap(err) - } - - // convert to a starlark value - b, err := yaml.Marshal(rn.Document()) // convert to bytes - if err != nil { - return nil, errors.Wrap(err) - } - var in map[string]interface{} - err = yaml.Unmarshal(b, &in) // convert to map[string]interface{} - if err != nil { - return nil, errors.Wrap(err) - } - return util.Marshal(in) // convert to starlark value -} - -// resourceListToOutput converts the output of the starlark program to the filter output -func (sf *Filter) writeResourceList(value starlark.Value, writer io.Writer) error { - // convert the modified resourceList back into a slice of RNodes - // by first converting to a map[string]interface{} - out, err := util.Unmarshal(value) - if err != nil { - return errors.Wrap(err) - } - b, err := yaml.Marshal(out) - if err != nil { - return errors.Wrap(err) - } - - rl, err := yaml.Parse(string(b)) - if err != nil { - return errors.Wrap(err) - } - - // preserve the comments from the input - items, err := rl.Pipe(yaml.Lookup("items")) - if err != nil { - return errors.Wrap(err) - } - err = items.VisitElements(func(node *yaml.RNode) error { - // starlark will serialize the resources sorting the fields alphabetically, - // format them to have a better ordering - _, err := filters.FormatFilter{}.Filter([]*yaml.RNode{node}) - return err - }) - if err != nil { - return errors.Wrap(err) - } - - s, err := rl.String() - if err != nil { - return errors.Wrap(err) - } - - _, err = writer.Write([]byte(s)) - return err -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/LICENSE b/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/LICENSE deleted file mode 100644 index 31f292dce..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 QRI, Inc. - -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/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/doc.go b/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/doc.go deleted file mode 100644 index 035b47921..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/doc.go +++ /dev/null @@ -1,25 +0,0 @@ -// The MIT License (MIT) - -// Copyright (c) 2018 QRI, Inc. - -// 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 util is forked from https://github.com/qri-io/starlib in order to prune -// excessive transitive dependencies from pulling in that library. -package util diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/util.go b/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/util.go deleted file mode 100644 index 6bc4fba0f..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util/util.go +++ /dev/null @@ -1,275 +0,0 @@ -// The MIT License (MIT) - -// Copyright (c) 2018 QRI, Inc. - -// 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 util - -import ( - "fmt" - - "go.starlark.net/starlark" - "go.starlark.net/starlarkstruct" - "sigs.k8s.io/kustomize/kyaml/errors" -) - -// // asString unquotes a starlark string value -// func asString(x starlark.Value) (string, error) { -// return strconv.Unquote(x.String()) -// } - -// IsEmptyString checks is a starlark string is empty ("" for a go string) -// starlark.String.String performs repr-style quotation, which is necessary -// for the starlark.Value contract but a frequent source of errors in API -// clients. This helper method makes sure it'll work properly -func IsEmptyString(s starlark.String) bool { - return s.String() == `""` -} - -// Unmarshal decodes a starlark.Value into it's golang counterpart -// -//nolint:nakedret -func Unmarshal(x starlark.Value) (val interface{}, err error) { - switch v := x.(type) { - case starlark.NoneType: - val = nil - case starlark.Bool: - val = v.Truth() == starlark.True - case starlark.Int: - val, err = starlark.AsInt32(x) - case starlark.Float: - if f, ok := starlark.AsFloat(x); !ok { - err = fmt.Errorf("couldn't parse float") - } else { - val = f - } - case starlark.String: - val = v.GoString() - // case starlibtime.Time: - // val = time.Time(v) - case *starlark.Dict: - var ( - dictVal starlark.Value - pval interface{} - kval interface{} - keys []interface{} - vals []interface{} - // key as interface if found one key is not a string - ki bool - ) - - for _, k := range v.Keys() { - dictVal, _, err = v.Get(k) - if err != nil { - return - } - - pval, err = Unmarshal(dictVal) - if err != nil { - err = fmt.Errorf("unmarshaling starlark value: %w", err) - return - } - - kval, err = Unmarshal(k) - if err != nil { - err = fmt.Errorf("unmarshaling starlark key: %w", err) - return - } - - if _, ok := kval.(string); !ok { - // found key as not a string - ki = true - } - - keys = append(keys, kval) - vals = append(vals, pval) - } - - // prepare result - - rs := map[string]interface{}{} - ri := map[interface{}]interface{}{} - - for i, key := range keys { - // key as interface - if ki { - ri[key] = vals[i] - } else { - rs[key.(string)] = vals[i] - } - } - - if ki { - val = ri // map[interface{}]interface{} - } else { - val = rs // map[string]interface{} - } - case *starlark.List: - var ( - i int - listVal starlark.Value - iter = v.Iterate() - value = make([]interface{}, v.Len()) - ) - - defer iter.Done() - for iter.Next(&listVal) { - value[i], err = Unmarshal(listVal) - if err != nil { - return - } - i++ - } - val = value - case starlark.Tuple: - var ( - i int - tupleVal starlark.Value - iter = v.Iterate() - value = make([]interface{}, v.Len()) - ) - - defer iter.Done() - for iter.Next(&tupleVal) { - value[i], err = Unmarshal(tupleVal) - if err != nil { - return - } - i++ - } - val = value - case *starlark.Set: - fmt.Println("errnotdone: SET") - err = fmt.Errorf("sets aren't yet supported") - case *starlarkstruct.Struct: - if _var, ok := v.Constructor().(Unmarshaler); ok { - err = _var.UnmarshalStarlark(x) - if err != nil { - err = errors.WrapPrefixf(err, "failed marshal %q to Starlark object", v.Constructor().Type()) - return - } - val = _var - } else { - err = fmt.Errorf("constructor object from *starlarkstruct.Struct not supported Marshaler to starlark object: %s", v.Constructor().Type()) - } - default: - fmt.Println("errbadtype:", x.Type()) - err = fmt.Errorf("unrecognized starlark type: %s", x.Type()) - } - return -} - -// Marshal turns go values into starlark types -// -//nolint:nakedret -func Marshal(data interface{}) (v starlark.Value, err error) { - switch x := data.(type) { - case nil: - v = starlark.None - case bool: - v = starlark.Bool(x) - case string: - v = starlark.String(x) - case int: - v = starlark.MakeInt(x) - case int8: - v = starlark.MakeInt(int(x)) - case int16: - v = starlark.MakeInt(int(x)) - case int32: - v = starlark.MakeInt(int(x)) - case int64: - v = starlark.MakeInt64(x) - case uint: - v = starlark.MakeUint(x) - case uint8: - v = starlark.MakeUint(uint(x)) - case uint16: - v = starlark.MakeUint(uint(x)) - case uint32: - v = starlark.MakeUint(uint(x)) - case uint64: - v = starlark.MakeUint64(x) - case float32: - v = starlark.Float(float64(x)) - case float64: - v = starlark.Float(x) - // case time.Time: - // v = starlibtime.Time(x) - case []interface{}: - var elems = make([]starlark.Value, len(x)) - for i, val := range x { - elems[i], err = Marshal(val) - if err != nil { - return - } - } - v = starlark.NewList(elems) - case map[interface{}]interface{}: - dict := &starlark.Dict{} - var elem starlark.Value - for ki, val := range x { - var key starlark.Value - key, err = Marshal(ki) - if err != nil { - return - } - - elem, err = Marshal(val) - if err != nil { - return - } - if err = dict.SetKey(key, elem); err != nil { - return - } - } - v = dict - case map[string]interface{}: - dict := &starlark.Dict{} - var elem starlark.Value - for key, val := range x { - elem, err = Marshal(val) - if err != nil { - return - } - if err = dict.SetKey(starlark.String(key), elem); err != nil { - return - } - } - v = dict - case Marshaler: - v, err = x.MarshalStarlark() - default: - return starlark.None, fmt.Errorf("unrecognized type: %#v", x) - } - return -} - -// Unmarshaler is the interface use to unmarshal starlark custom types. -type Unmarshaler interface { - // UnmarshalStarlark unmarshal a starlark object to custom type. - UnmarshalStarlark(starlark.Value) error -} - -// Marshaler is the interface use to marshal starlark custom types. -type Marshaler interface { - // MarshalStarlark marshal a custom type to starlark object. - MarshalStarlark() (starlark.Value, error) -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/filters.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/filters.go deleted file mode 100644 index 8d7968b3c..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/filters.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters - -import ( - "fmt" - "sort" - "strings" - - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/kio/kioutil" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -// Filters are the list of known filters for unmarshalling a filter into a concrete -// implementation. -var Filters = map[string]func() kio.Filter{ - "FileSetter": func() kio.Filter { return &FileSetter{} }, - "FormatFilter": func() kio.Filter { return &FormatFilter{} }, - "GrepFilter": func() kio.Filter { return GrepFilter{} }, - "MatchModifier": func() kio.Filter { return &MatchModifyFilter{} }, - "Modifier": func() kio.Filter { return &Modifier{} }, -} - -// filter wraps a kio.filter so that it can be unmarshalled from yaml. -type KFilter struct { - kio.Filter -} - -func (t KFilter) MarshalYAML() (interface{}, error) { - return t.Filter, nil -} - -func (t *KFilter) UnmarshalYAML(unmarshal func(interface{}) error) error { - i := map[string]interface{}{} - if err := unmarshal(i); err != nil { - return err - } - meta := &yaml.ResourceMeta{} - if err := unmarshal(meta); err != nil { - return err - } - filter, found := Filters[meta.Kind] - if !found { - var knownFilters []string - for k := range Filters { - knownFilters = append(knownFilters, k) - } - sort.Strings(knownFilters) - return fmt.Errorf("unsupported filter Kind %v: may be one of: [%s]", - meta, strings.Join(knownFilters, ",")) - } - t.Filter = filter() - - return unmarshal(t.Filter) -} - -// Modifier modifies the input Resources by invoking the provided pipeline. -// Modifier will return any Resources for which the pipeline does not return an error. -type Modifier struct { - Kind string `yaml:"kind,omitempty"` - - Filters yaml.YFilters `yaml:"pipeline,omitempty"` -} - -var _ kio.Filter = &Modifier{} - -func (f Modifier) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - for i := range input { - if _, err := input[i].Pipe(f.Filters.Filters()...); err != nil { - return nil, err - } - } - return input, nil -} - -type MatchModifyFilter struct { - Kind string `yaml:"kind,omitempty"` - - MatchFilters []yaml.YFilters `yaml:"match,omitempty"` - - ModifyFilters yaml.YFilters `yaml:"modify,omitempty"` -} - -var _ kio.Filter = &MatchModifyFilter{} - -func (f MatchModifyFilter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - var matches = input - var err error - for _, filter := range f.MatchFilters { - matches, err = MatchFilter{Filters: filter}.Filter(matches) - if err != nil { - return nil, err - } - } - _, err = Modifier{Filters: f.ModifyFilters}.Filter(matches) - if err != nil { - return nil, err - } - return input, nil -} - -type MatchFilter struct { - Kind string `yaml:"kind,omitempty"` - - Filters yaml.YFilters `yaml:"pipeline,omitempty"` -} - -var _ kio.Filter = &MatchFilter{} - -func (f MatchFilter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - var output []*yaml.RNode - for i := range input { - if v, err := input[i].Pipe(f.Filters.Filters()...); err != nil { - return nil, err - } else if v == nil { - continue - } - output = append(output, input[i]) - } - return output, nil -} - -type FilenameFmtVerb string - -const ( - // KindFmt substitutes kind - KindFmt FilenameFmtVerb = "%k" - - // NameFmt substitutes metadata.name - NameFmt FilenameFmtVerb = "%n" - - // NamespaceFmt substitutes metdata.namespace - NamespaceFmt FilenameFmtVerb = "%s" -) - -// FileSetter sets the file name and mode annotations on Resources. -type FileSetter struct { - Kind string `yaml:"kind,omitempty"` - - // FilenamePattern is the pattern to use for generating filenames. FilenameFmtVerb - // FielnameFmtVerbs may be specified to substitute Resource metadata into the filename. - FilenamePattern string `yaml:"filenamePattern,omitempty"` - - // Mode is the filemode to write. - Mode string `yaml:"mode,omitempty"` - - // Override will override the existing filename if it is set on the pattern. - // Otherwise the existing filename is kept. - Override bool `yaml:"override,omitempty"` -} - -var _ kio.Filter = &FileSetter{} - -const DefaultFilenamePattern = "%n_%k.yaml" - -func (f *FileSetter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - if f.Mode == "" { - f.Mode = fmt.Sprintf("%d", 0600) - } - if f.FilenamePattern == "" { - f.FilenamePattern = DefaultFilenamePattern - } - - resources := map[string][]*yaml.RNode{} - for i := range input { - if err := kioutil.CopyLegacyAnnotations(input[i]); err != nil { - return nil, err - } - - m, err := input[i].GetMeta() - if err != nil { - return nil, err - } - file := f.FilenamePattern - file = strings.ReplaceAll(file, string(KindFmt), strings.ToLower(m.Kind)) - file = strings.ReplaceAll(file, string(NameFmt), strings.ToLower(m.Name)) - file = strings.ReplaceAll(file, string(NamespaceFmt), strings.ToLower(m.Namespace)) - - if _, found := m.Annotations[kioutil.PathAnnotation]; !found || f.Override { - if _, err := input[i].Pipe(yaml.SetAnnotation(kioutil.PathAnnotation, file)); err != nil { - return nil, err - } - if _, err := input[i].Pipe(yaml.SetAnnotation(kioutil.LegacyPathAnnotation, file)); err != nil { - return nil, err - } - } - resources[file] = append(resources[file], input[i]) - } - - var output []*yaml.RNode - for i := range resources { - if err := kioutil.SortNodes(resources[i]); err != nil { - return nil, err - } - for j := range resources[i] { - if _, err := resources[i][j].Pipe( - yaml.SetAnnotation(kioutil.IndexAnnotation, fmt.Sprintf("%d", j))); err != nil { - return nil, err - } - if _, err := resources[i][j].Pipe( - yaml.SetAnnotation(kioutil.LegacyIndexAnnotation, fmt.Sprintf("%d", j))); err != nil { - return nil, err - } - output = append(output, resources[i][j]) - } - } - return output, nil -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/fmtr.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/fmtr.go deleted file mode 100644 index 7f2acbda4..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/fmtr.go +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -// Package yamlfmt contains libraries for formatting yaml files containing -// Kubernetes Resource configuration. -// -// Yaml files are formatted by: -// - Sorting fields and map values -// - Sorting unordered lists for whitelisted types -// - Applying a canonical yaml Style -// -// Fields are ordered using a relative ordering applied to commonly -// encountered Resource fields. All Resources, including non-builtin -// Resources such as CRDs, share the same field precedence. -// -// Fields that do not appear in the explicit ordering are ordered -// lexicographically. -// -// A subset of well known known unordered lists are sorted by element field -// values. -package filters - -import ( - "bytes" - "fmt" - "io" - "sort" - - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/openapi" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -type FormattingStrategy = string - -const ( - // NoFmtAnnotation determines if the resource should be formatted. - FmtAnnotation string = "config.kubernetes.io/formatting" - - // FmtStrategyStandard means the resource will be formatted according - // to the default rules. - FmtStrategyStandard FormattingStrategy = "standard" - - // FmtStrategyNone means the resource will not be formatted. - FmtStrategyNone FormattingStrategy = "none" -) - -// FormatInput returns the formatted input. -func FormatInput(input io.Reader) (*bytes.Buffer, error) { - buff := &bytes.Buffer{} - err := kio.Pipeline{ - Inputs: []kio.Reader{&kio.ByteReader{Reader: input}}, - Filters: []kio.Filter{FormatFilter{}}, - Outputs: []kio.Writer{kio.ByteWriter{Writer: buff}}, - }.Execute() - - return buff, err -} - -// FormatFileOrDirectory reads the file or directory and formats each file's -// contents by writing it back to the file. -func FormatFileOrDirectory(path string) error { - return kio.Pipeline{ - Inputs: []kio.Reader{kio.LocalPackageReader{ - PackagePath: path, - }}, - Filters: []kio.Filter{FormatFilter{}}, - Outputs: []kio.Writer{kio.LocalPackageWriter{PackagePath: path}}, - }.Execute() -} - -type FormatFilter struct { - Process func(n *yaml.Node) error - UseSchema bool -} - -var _ kio.Filter = FormatFilter{} - -func (f FormatFilter) Filter(slice []*yaml.RNode) ([]*yaml.RNode, error) { - for i := range slice { - fmtStrategy, err := getFormattingStrategy(slice[i]) - if err != nil { - return nil, err - } - - if fmtStrategy == FmtStrategyNone { - continue - } - - kindNode, err := slice[i].Pipe(yaml.Get("kind")) - if err != nil { - return nil, err - } - if kindNode == nil { - continue - } - apiVersionNode, err := slice[i].Pipe(yaml.Get("apiVersion")) - if err != nil { - return nil, err - } - if apiVersionNode == nil { - continue - } - kind, apiVersion := kindNode.YNode().Value, apiVersionNode.YNode().Value - var s *openapi.ResourceSchema - if f.UseSchema { - s = openapi.SchemaForResourceType(yaml.TypeMeta{APIVersion: apiVersion, Kind: kind}) - } else { - s = nil - } - err = (&formatter{apiVersion: apiVersion, kind: kind, process: f.Process}). - fmtNode(slice[i].YNode(), "", s) - if err != nil { - return nil, err - } - } - return slice, nil -} - -// getFormattingStrategy looks for the formatting annotation to determine -// which strategy should be used for formatting. The default is standard -// if no annotation is found. -func getFormattingStrategy(node *yaml.RNode) (FormattingStrategy, error) { - value, err := node.Pipe(yaml.GetAnnotation(FmtAnnotation)) - if err != nil || value == nil { - return FmtStrategyStandard, err - } - - fmtStrategy := value.YNode().Value - - switch fmtStrategy { - case FmtStrategyStandard: - return FmtStrategyStandard, nil - case FmtStrategyNone: - return FmtStrategyNone, nil - default: - return "", fmt.Errorf( - "formatting annotation has illegal value %s", fmtStrategy) - } -} - -type formatter struct { - apiVersion string - kind string - process func(n *yaml.Node) error -} - -// fmtNode recursively formats the Document Contents. -// See: https://godoc.org/gopkg.in/yaml.v3#Node -func (f *formatter) fmtNode(n *yaml.Node, path string, schema *openapi.ResourceSchema) error { - if n.Kind == yaml.ScalarNode && schema != nil && schema.Schema != nil { - // ensure values that are interpreted as non-string values (e.g. "true") - // are properly quoted - yaml.FormatNonStringStyle(n, *schema.Schema) - } - - // sort the order of mapping fields - if n.Kind == yaml.MappingNode { - sort.Sort(sortedMapContents(*n)) - } - - // sort the order of sequence elements if it is whitelisted - if n.Kind == yaml.SequenceNode { - if yaml.WhitelistedListSortKinds.Has(f.kind) && - yaml.WhitelistedListSortApis.Has(f.apiVersion) { - if sortField, found := yaml.WhitelistedListSortFields[path]; found { - sort.Sort(sortedSeqContents{Node: *n, sortField: sortField}) - } - } - } - - // format the Content - for i := range n.Content { - // MappingNode are structured as having their fields as Content, - // with the field-key and field-value alternating. e.g. Even elements - // are the keys and odd elements are the values - isFieldKey := n.Kind == yaml.MappingNode && i%2 == 0 - isFieldValue := n.Kind == yaml.MappingNode && i%2 == 1 - isElement := n.Kind == yaml.SequenceNode - - // run the process callback on the node if it has been set - // don't process keys: their format should be fixed - if f.process != nil && !isFieldKey { - if err := f.process(n.Content[i]); err != nil { - return err - } - } - - // get the schema for this Node - p := path - var s *openapi.ResourceSchema - switch { - case isFieldValue: - // if the node is a field, lookup the schema using the field name - p = fmt.Sprintf("%s.%s", path, n.Content[i-1].Value) - if schema != nil { - s = schema.Field(n.Content[i-1].Value) - } - case isElement: - // if the node is a list element, lookup the schema for the array items - if schema != nil { - s = schema.Elements() - } - } - // format the node using the schema - err := f.fmtNode(n.Content[i], p, s) - if err != nil { - return err - } - } - return nil -} - -// sortedMapContents sorts the Contents field of a MappingNode by the field names using a statically -// defined field precedence, and falling back on lexicographical sorting -type sortedMapContents yaml.Node - -func (s sortedMapContents) Len() int { - return len(s.Content) / 2 -} -func (s sortedMapContents) Swap(i, j int) { - // yaml MappingNode Contents are a list of field names followed by - // field values, rather than a list of field pairs. - // increment. - // - // e.g. ["field1Name", "field1Value", "field2Name", "field2Value"] - iFieldNameIndex := i * 2 - jFieldNameIndex := j * 2 - iFieldValueIndex := iFieldNameIndex + 1 - jFieldValueIndex := jFieldNameIndex + 1 - - // swap field names - s.Content[iFieldNameIndex], s.Content[jFieldNameIndex] = - s.Content[jFieldNameIndex], s.Content[iFieldNameIndex] - - // swap field values - s.Content[iFieldValueIndex], s.Content[jFieldValueIndex] = s. - Content[jFieldValueIndex], s.Content[iFieldValueIndex] -} - -func (s sortedMapContents) Less(i, j int) bool { - iFieldNameIndex := i * 2 - jFieldNameIndex := j * 2 - iFieldName := s.Content[iFieldNameIndex].Value - jFieldName := s.Content[jFieldNameIndex].Value - - // order by their precedence values looked up from the index - iOrder, foundI := yaml.FieldOrder[iFieldName] - jOrder, foundJ := yaml.FieldOrder[jFieldName] - if foundI && foundJ { - return iOrder < jOrder - } - - // known fields come before unknown fields - if foundI { - return true - } - if foundJ { - return false - } - - // neither field is known, sort them lexicographically - return iFieldName < jFieldName -} - -// sortedSeqContents sorts the Contents field of a SequenceNode by the value of -// the elements sortField. -// e.g. it will sort spec.template.spec.containers by the value of the container `name` field -type sortedSeqContents struct { - yaml.Node - sortField string -} - -func (s sortedSeqContents) Len() int { - return len(s.Content) -} -func (s sortedSeqContents) Swap(i, j int) { - s.Content[i], s.Content[j] = s.Content[j], s.Content[i] -} -func (s sortedSeqContents) Less(i, j int) bool { - // primitive lists -- sort by the element's primitive values - if s.sortField == "" { - iValue := s.Content[i].Value - jValue := s.Content[j].Value - return iValue < jValue - } - - // map lists -- sort by the element's sortField values - var iValue, jValue string - for a := range s.Content[i].Content { - if a%2 != 0 { - continue // not a fieldNameIndex - } - // locate the index of the sortField field - if s.Content[i].Content[a].Value == s.sortField { - // a is the yaml node for the field key, a+1 is the node for the field value - iValue = s.Content[i].Content[a+1].Value - } - } - for a := range s.Content[j].Content { - if a%2 != 0 { - continue // not a fieldNameIndex - } - - // locate the index of the sortField field - if s.Content[j].Content[a].Value == s.sortField { - // a is the yaml node for the field key, a+1 is the node for the field value - jValue = s.Content[j].Content[a+1].Value - } - } - - // compare the field values - return iValue < jValue -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/grep.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/grep.go deleted file mode 100644 index 2eb8a8886..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/grep.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters - -import ( - "regexp" - "strings" - - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -type GrepType int - -const ( - Regexp GrepType = 1 << iota - GreaterThanEq - GreaterThan - LessThan - LessThanEq -) - -// GrepFilter filters RNodes with a matching field -type GrepFilter struct { - Path []string `yaml:"path,omitempty"` - Value string `yaml:"value,omitempty"` - MatchType GrepType `yaml:"matchType,omitempty"` - InvertMatch bool `yaml:"invertMatch,omitempty"` - Compare func(a, b string) (int, error) -} - -var _ kio.Filter = GrepFilter{} - -func (f GrepFilter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - // compile the regular expression 1 time if we are matching using regex - var reg *regexp.Regexp - var err error - if f.MatchType == Regexp || f.MatchType == 0 { - reg, err = regexp.Compile(f.Value) - if err != nil { - return nil, err - } - } - - var output kio.ResourceNodeSlice - for i := range input { - node := input[i] - val, err := node.Pipe(&yaml.PathMatcher{Path: f.Path}) - if err != nil { - return nil, err - } - if val == nil || len(val.Content()) == 0 { - if f.InvertMatch { - output = append(output, input[i]) - } - continue - } - found := false - err = val.VisitElements(func(elem *yaml.RNode) error { - // get the value - var str string - if f.MatchType == Regexp { - style := elem.YNode().Style - defer func() { elem.YNode().Style = style }() - elem.YNode().Style = yaml.FlowStyle - str, err = elem.String() - if err != nil { - return err - } - str = strings.TrimSpace(strings.ReplaceAll(str, `"`, "")) - } else { - // if not regexp, then it needs to parse into a quantity and comments will - // break that - str = elem.YNode().Value - if str == "" { - return nil - } - } - - if f.MatchType == Regexp || f.MatchType == 0 { - if reg.MatchString(str) { - found = true - } - return nil - } - - comp, err := f.Compare(str, f.Value) - if err != nil { - return err - } - - if f.MatchType == GreaterThan && comp > 0 { - found = true - } - if f.MatchType == GreaterThanEq && comp >= 0 { - found = true - } - if f.MatchType == LessThan && comp < 0 { - found = true - } - if f.MatchType == LessThanEq && comp <= 0 { - found = true - } - return nil - }) - if err != nil { - return nil, err - } - if found == f.InvertMatch { - continue - } - - output = append(output, input[i]) - } - return output, nil -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/local.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/local.go deleted file mode 100644 index bdac1a28f..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/local.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters - -import ( - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -const LocalConfigAnnotation = "config.kubernetes.io/local-config" - -// IsLocalConfig filters Resources using the config.kubernetes.io/local-config annotation -type IsLocalConfig struct { - // IncludeLocalConfig will include local-config if set to true - IncludeLocalConfig bool `yaml:"includeLocalConfig,omitempty"` - - // ExcludeNonLocalConfig will exclude non local-config if set to true - ExcludeNonLocalConfig bool `yaml:"excludeNonLocalConfig,omitempty"` -} - -// Filter implements kio.Filter -func (c *IsLocalConfig) Filter(inputs []*yaml.RNode) ([]*yaml.RNode, error) { - var out []*yaml.RNode - for i := range inputs { - meta, err := inputs[i].GetMeta() - if err != nil { - return nil, err - } - _, local := meta.Annotations[LocalConfigAnnotation] - - if local && c.IncludeLocalConfig { - out = append(out, inputs[i]) - } else if !local && !c.ExcludeNonLocalConfig { - out = append(out, inputs[i]) - } - } - return out, nil -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge.go deleted file mode 100644 index 5159052cc..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -// Package merge contains libraries for merging Resources and Patches -package filters - -import ( - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/yaml" - "sigs.k8s.io/kustomize/kyaml/yaml/merge2" -) - -// MergeFilter merges Resources with the Group/Version/Kind/Namespace/Name together using -// a 2-way merge strategy. -// -// - Fields set to null in the source will be cleared from the destination -// - Fields with matching keys will be merged recursively -// - Lists with an associative key (e.g. name) will have their elements merged using the key -// - List without an associative key will have the dest list replaced by the source list -type MergeFilter struct { - Reverse bool -} - -var _ kio.Filter = MergeFilter{} - -type mergeKey struct { - apiVersion string - kind string - namespace string - name string -} - -// MergeFilter implements kio.Filter by merging Resources with the same G/V/K/NS/N -func (c MergeFilter) Filter(input []*yaml.RNode) ([]*yaml.RNode, error) { - // invert the merge precedence - if c.Reverse { - for i, j := 0, len(input)-1; i < j; i, j = i+1, j-1 { - input[i], input[j] = input[j], input[i] - } - } - - // index the Resources by G/V/K/NS/N - index := map[mergeKey][]*yaml.RNode{} - // retain the original ordering - var order []mergeKey - for i := range input { - meta, err := input[i].GetMeta() - if err != nil { - return nil, err - } - key := mergeKey{ - apiVersion: meta.APIVersion, - kind: meta.Kind, - namespace: meta.Namespace, - name: meta.Name, - } - if _, found := index[key]; !found { - order = append(order, key) - } - index[key] = append(index[key], input[i]) - } - - // merge each of the G/V/K/NS/N lists - var output []*yaml.RNode - var err error - for _, k := range order { - var merged *yaml.RNode - resources := index[k] - for i := range resources { - patch := resources[i] - if merged == nil { - // first resources, don't merge it - merged = resources[i] - } else { - merged, err = merge2.Merge(patch, merged, yaml.MergeOptions{ - ListIncreaseDirection: yaml.MergeOptionsListPrepend, - }) - if err != nil { - return nil, err - } - } - } - output = append(output, merged) - } - return output, nil -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge3.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge3.go deleted file mode 100644 index de8bf6f67..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/merge3.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters - -import ( - "fmt" - - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/kio/kioutil" - "sigs.k8s.io/kustomize/kyaml/yaml" - "sigs.k8s.io/kustomize/kyaml/yaml/merge3" -) - -const ( - mergeSourceAnnotation = "config.kubernetes.io/merge-source" - mergeSourceOriginal = "original" - mergeSourceUpdated = "updated" - mergeSourceDest = "dest" -) - -// ResourceMatcher interface is used to match two resources based on IsSameResource implementation -// This is the way to group same logical resources in upstream, local and origin for merge -// The default way to group them is using GVKNN similar to how kubernetes server identifies resources -// Users of this library might have their own interpretation of grouping similar resources -// for e.g. if consumer adds a name-prefix to local resource, it should not be treated as new resource -// for updates etc. -// Hence, the callers of this library may pass different implementation for IsSameResource -type ResourceMatcher interface { - IsSameResource(node1, node2 *yaml.RNode) bool -} - -// ResourceMergeStrategy is the return type from the Handle function in the -// ResourceHandler interface. It determines which version of a resource should -// be included in the output (if any). -type ResourceMergeStrategy int - -const ( - // Merge means the output to dest should be the 3-way merge of original, - // updated and dest. - Merge ResourceMergeStrategy = iota - // KeepDest means the version of the resource in dest should be the output. - KeepDest - // KeepUpdated means the version of the resource in updated should be the - // output. - KeepUpdated - // KeepOriginal means the version of the resource in original should be the - // output. - KeepOriginal - // Skip means the resource should not be included in the output. - Skip -) - -// ResourceHandler interface is used to determine what should be done for a -// resource once the versions in original, updated and dest has been -// identified based on the ResourceMatcher. This allows users to customize -// what should be the result in dest if a resource has been deleted from -// upstream. -type ResourceHandler interface { - Handle(original, updated, dest *yaml.RNode) (ResourceMergeStrategy, error) -} - -// Merge3 performs a 3-way merge on the original, updated, and destination packages. -type Merge3 struct { - OriginalPath string - UpdatedPath string - DestPath string - MatchFilesGlob []string - Matcher ResourceMatcher - Handler ResourceHandler -} - -func (m Merge3) Merge() error { - // Read the destination package. The ReadWriter will take take of deleting files - // for removed resources. - var inputs []kio.Reader - dest := &kio.LocalPackageReadWriter{ - PackagePath: m.DestPath, - MatchFilesGlob: m.MatchFilesGlob, - SetAnnotations: map[string]string{mergeSourceAnnotation: mergeSourceDest}, - } - inputs = append(inputs, dest) - - // Read the original package - inputs = append(inputs, kio.LocalPackageReader{ - PackagePath: m.OriginalPath, - MatchFilesGlob: m.MatchFilesGlob, - SetAnnotations: map[string]string{mergeSourceAnnotation: mergeSourceOriginal}, - }) - - // Read the updated package - inputs = append(inputs, kio.LocalPackageReader{ - PackagePath: m.UpdatedPath, - MatchFilesGlob: m.MatchFilesGlob, - SetAnnotations: map[string]string{mergeSourceAnnotation: mergeSourceUpdated}, - }) - - return kio.Pipeline{ - Inputs: inputs, - Filters: []kio.Filter{m}, - Outputs: []kio.Writer{dest}, - }.Execute() -} - -// Filter combines Resources with the same GVK + N + NS into tuples, and then merges them -func (m Merge3) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { - // index the nodes by their identity - matcher := m.Matcher - if matcher == nil { - matcher = &DefaultGVKNNMatcher{MergeOnPath: true} - } - handler := m.Handler - if handler == nil { - handler = &DefaultResourceHandler{} - } - - tl := tuples{matcher: matcher} - for i := range nodes { - if err := tl.add(nodes[i]); err != nil { - return nil, err - } - } - - // iterate over the inputs, merging as needed - var output []*yaml.RNode - for i := range tl.list { - t := tl.list[i] - strategy, err := handler.Handle(t.original, t.updated, t.dest) - if err != nil { - return nil, err - } - switch strategy { - case Merge: - node, err := t.merge() - if err != nil { - return nil, err - } - if node != nil { - output = append(output, node) - } - case KeepDest: - output = append(output, t.dest) - case KeepUpdated: - output = append(output, t.updated) - case KeepOriginal: - output = append(output, t.original) - case Skip: - // do nothing - } - } - return output, nil -} - -// tuples combines nodes with the same GVK + N + NS -type tuples struct { - list []*tuple - - // matcher matches the resources for merge - matcher ResourceMatcher -} - -// DefaultGVKNNMatcher holds the default matching of resources implementation based on -// Group, Version, Kind, Name and Namespace of the resource -type DefaultGVKNNMatcher struct { - // MergeOnPath will use the relative filepath as part of the merge key. - // This may be necessary if the directory contains multiple copies of - // the same resource, or resources patches. - MergeOnPath bool -} - -// IsSameResource returns true if metadata of node1 and metadata of node2 belongs to same logical resource -func (dm *DefaultGVKNNMatcher) IsSameResource(node1, node2 *yaml.RNode) bool { - if node1 == nil || node2 == nil { - return false - } - if err := kioutil.CopyLegacyAnnotations(node1); err != nil { - return false - } - if err := kioutil.CopyLegacyAnnotations(node2); err != nil { - return false - } - - meta1, err := node1.GetMeta() - if err != nil { - return false - } - - meta2, err := node2.GetMeta() - if err != nil { - return false - } - - if meta1.Name != meta2.Name { - return false - } - if meta1.Namespace != meta2.Namespace { - return false - } - if meta1.APIVersion != meta2.APIVersion { - return false - } - if meta1.Kind != meta2.Kind { - return false - } - if dm.MergeOnPath { - // directories may contain multiple copies of a resource with the same - // name, namespace, apiVersion and kind -- e.g. kustomize patches, or - // multiple environments - // mergeOnPath configures the merge logic to use the path as part of the - // resource key - if meta1.Annotations[kioutil.PathAnnotation] != meta2.Annotations[kioutil.PathAnnotation] { - return false - } - } - return true -} - -// add adds a node to the list, combining it with an existing matching Resource if found -func (ts *tuples) add(node *yaml.RNode) error { - for i := range ts.list { - t := ts.list[i] - if ts.matcher.IsSameResource(addedNode(t), node) { - return t.add(node) - } - } - t := &tuple{} - if err := t.add(node); err != nil { - return err - } - ts.list = append(ts.list, t) - return nil -} - -// addedNode returns one on the existing added nodes in the tuple -func addedNode(t *tuple) *yaml.RNode { - if t.updated != nil { - return t.updated - } - if t.original != nil { - return t.original - } - return t.dest -} - -// tuple wraps an original, updated, and dest tuple for a given Resource -type tuple struct { - original *yaml.RNode - updated *yaml.RNode - dest *yaml.RNode -} - -// add sets the corresponding tuple field for the node -func (t *tuple) add(node *yaml.RNode) error { - meta, err := node.GetMeta() - if err != nil { - return err - } - switch meta.Annotations[mergeSourceAnnotation] { - case mergeSourceDest: - if t.dest != nil { - return duplicateError("local", meta.Annotations[kioutil.PathAnnotation]) - } - t.dest = node - case mergeSourceOriginal: - if t.original != nil { - return duplicateError("original upstream", meta.Annotations[kioutil.PathAnnotation]) - } - t.original = node - case mergeSourceUpdated: - if t.updated != nil { - return duplicateError("updated upstream", meta.Annotations[kioutil.PathAnnotation]) - } - t.updated = node - default: - return fmt.Errorf("no source annotation for Resource") - } - return nil -} - -// merge performs a 3-way merge on the tuple -func (t *tuple) merge() (*yaml.RNode, error) { - return merge3.Merge(t.dest, t.original, t.updated) -} - -// duplicateError returns duplicate resources error -func duplicateError(source, filePath string) error { - return fmt.Errorf(`found duplicate %q resources in file %q, please refer to "update" documentation for the fix`, source, filePath) -} - -// DefaultResourceHandler is the default implementation of the ResourceHandler -// interface. It uses the following rules: -// * Keep dest if resource only exists in dest. -// * Keep updated if resource added in updated. -// * Delete dest if updated has been deleted. -// * Don't add the resource back if removed from dest. -// * Otherwise merge. -type DefaultResourceHandler struct{} - -func (*DefaultResourceHandler) Handle(original, updated, dest *yaml.RNode) (ResourceMergeStrategy, error) { - switch { - case original == nil && updated == nil && dest != nil: - // added locally -- keep dest - return KeepDest, nil - case updated != nil && dest == nil: - // added in the update -- add update - return KeepUpdated, nil - case original != nil && updated == nil: - // deleted in the update - return Skip, nil - case original != nil && dest == nil: - // deleted locally - return Skip, nil - default: - // dest and updated are non-nil -- merge them - return Merge, nil - } -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/modify.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/modify.go deleted file mode 100644 index b1090302a..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/modify.go +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/stripcomments.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/stripcomments.go deleted file mode 100644 index 8e9ecb3f2..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/filters/stripcomments.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package filters - -import ( - "sigs.k8s.io/kustomize/kyaml/kio" - "sigs.k8s.io/kustomize/kyaml/yaml" -) - -type StripCommentsFilter struct{} - -var _ kio.Filter = StripCommentsFilter{} - -func (f StripCommentsFilter) Filter(slice []*yaml.RNode) ([]*yaml.RNode, error) { - for i := range slice { - stripComments(slice[i].YNode()) - } - return slice, nil -} - -func stripComments(node *yaml.Node) { - if node == nil { - return - } - node.HeadComment = "" - node.LineComment = "" - node.FootComment = "" - for i := range node.Content { - stripComments(node.Content[i]) - } -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/ignorefilesmatcher.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/ignorefilesmatcher.go index 0ba3d8382..5ef48d7e3 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/ignorefilesmatcher.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/kio/ignorefilesmatcher.go @@ -86,7 +86,7 @@ func (i *ignoreFilesMatcher) matchFile(path string) bool { return i.matchers[len(i.matchers)-1].matcher.Match(path, false) } -// matchFile checks whether the directory given by the provided path matches +// matchDir checks whether the directory given by the provided path matches // any of the patterns in the .krmignore file for the package. func (i *ignoreFilesMatcher) matchDir(path string) bool { if len(i.matchers) == 0 { diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/openapi/kustomizationapi/swagger.go b/vendor/sigs.k8s.io/kustomize/kyaml/openapi/kustomizationapi/swagger.go index 49647be4b..421f70f7c 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/openapi/kustomizationapi/swagger.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/openapi/kustomizationapi/swagger.go @@ -64,7 +64,7 @@ func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } -// Mode return file modify time +// ModTime return file modify time func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/openapi/openapi.go b/vendor/sigs.k8s.io/kustomize/kyaml/openapi/openapi.go index 41ee0afc5..aa1c8d4a8 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/openapi/openapi.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/openapi/openapi.go @@ -182,7 +182,7 @@ type ResourceSchema struct { Schema *spec.Schema } -// IsEmpty returns true if the ResourceSchema is empty +// IsMissingOrNull returns true if the ResourceSchema is missing or null func (rs *ResourceSchema) IsMissingOrNull() bool { if rs == nil || rs.Schema == nil { return true diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go index 6b36d7d3a..777d3f87c 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go @@ -19,7 +19,6 @@ import ( "sigs.k8s.io/kustomize/kyaml/fn/runtime/container" "sigs.k8s.io/kustomize/kyaml/fn/runtime/exec" "sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil" - "sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark" "sigs.k8s.io/kustomize/kyaml/kio" "sigs.k8s.io/kustomize/kyaml/kio/kioutil" "sigs.k8s.io/kustomize/kyaml/yaml" @@ -61,9 +60,6 @@ type RunFns struct { // and only use explicit sources NoFunctionsFromInput *bool - // EnableStarlark will enable functions run as starlark scripts - EnableStarlark bool - // EnableExec will enable exec functions EnableExec bool @@ -209,8 +205,6 @@ func (r RunFns) runFunctions( identifier = filter.Image case *exec.Filter: identifier = filter.Path - case *starlark.Filter: - identifier = filter.String() default: identifier = "unknown-type function" } @@ -496,41 +490,6 @@ func (r *RunFns) ffp(spec runtimeutil.FunctionSpec, api *yaml.RNode, currentUser cf.Exec.DeferFailure = spec.DeferFailure return cf, nil } - if r.EnableStarlark && (spec.Starlark.Path != "" || spec.Starlark.URL != "") { - // the script path is relative to the function config file - m, err := api.GetMeta() - if err != nil { - return nil, errors.Wrap(err) - } - - var p string - if spec.Starlark.Path != "" { - pathAnno := m.Annotations[kioutil.PathAnnotation] - if pathAnno == "" { - pathAnno = m.Annotations[kioutil.LegacyPathAnnotation] - } - p = filepath.ToSlash(path.Clean(pathAnno)) - - spec.Starlark.Path = filepath.ToSlash(path.Clean(spec.Starlark.Path)) - if filepath.IsAbs(spec.Starlark.Path) || path.IsAbs(spec.Starlark.Path) { - return nil, errors.Errorf( - "absolute function path %s not allowed", spec.Starlark.Path) - } - if strings.HasPrefix(spec.Starlark.Path, "..") { - return nil, errors.Errorf( - "function path %s not allowed to start with ../", spec.Starlark.Path) - } - p = filepath.ToSlash(filepath.Join(r.Path, filepath.Dir(p), spec.Starlark.Path)) - } - - sf := &starlark.Filter{Name: spec.Starlark.Name, Path: p, URL: spec.Starlark.URL} - - sf.FunctionConfig = api - sf.GlobalScope = r.GlobalScope - sf.ResultsFile = resultsFile - sf.DeferFailure = spec.DeferFailure - return sf, nil - } if r.EnableExec && spec.Exec.Path != "" { ef := &exec.Filter{ diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/alias.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/alias.go index 12c72ae83..5908cd7bd 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/alias.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/alias.go @@ -20,7 +20,7 @@ const ( BareSeqNodeWrappingKey = "bareSeqNodeWrappingKey" ) -// SeqIndentType holds the indentation style for sequence nodes +// SequenceIndentStyle holds the indentation style for sequence nodes type SequenceIndentStyle string // EncoderOptions are options that can be used to configure the encoder, diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/merge3.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/merge3.go deleted file mode 100644 index 664270e5b..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/merge3.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -// Package merge contains libraries for merging fields from one RNode to another -// RNode -package merge3 - -import ( - "sigs.k8s.io/kustomize/kyaml/yaml" - "sigs.k8s.io/kustomize/kyaml/yaml/walk" -) - -func Merge(dest, original, update *yaml.RNode) (*yaml.RNode, error) { - // if update == nil && original != nil => declarative deletion - - return walk.Walker{ - Visitor: Visitor{}, - VisitKeysAsScalars: true, - Sources: []*yaml.RNode{dest, original, update}}.Walk() -} - -func MergeStrings(dest, original, update string, infer bool) (string, error) { - srcOriginal, err := yaml.Parse(original) - if err != nil { - return "", err - } - srcUpdated, err := yaml.Parse(update) - if err != nil { - return "", err - } - d, err := yaml.Parse(dest) - if err != nil { - return "", err - } - - result, err := walk.Walker{ - InferAssociativeLists: infer, - Visitor: Visitor{}, - VisitKeysAsScalars: true, - Sources: []*yaml.RNode{d, srcOriginal, srcUpdated}}.Walk() - if err != nil { - return "", err - } - return result.String() -} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/visitor.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/visitor.go deleted file mode 100644 index 978deff0c..000000000 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/merge3/visitor.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package merge3 - -import ( - "sigs.k8s.io/kustomize/kyaml/openapi" - "sigs.k8s.io/kustomize/kyaml/yaml" - "sigs.k8s.io/kustomize/kyaml/yaml/walk" -) - -type ConflictStrategy uint - -const ( - // TODO: Support more strategies - TakeUpdate ConflictStrategy = 1 + iota -) - -type Visitor struct{} - -func (m Visitor) VisitMap(nodes walk.Sources, s *openapi.ResourceSchema) (*yaml.RNode, error) { - if nodes.Updated().IsTaggedNull() || nodes.Dest().IsTaggedNull() { - // explicitly cleared from either dest or update - return walk.ClearNode, nil - } - if nodes.Dest() == nil && nodes.Updated() == nil { - // implicitly cleared missing from both dest and update - return walk.ClearNode, nil - } - - if nodes.Dest() == nil { - // not cleared, but missing from the dest - // initialize a new value that can be recursively merged - return yaml.NewRNode(&yaml.Node{Kind: yaml.MappingNode}), nil - } - - // recursively merge the dest with the original and updated - return nodes.Dest(), nil -} - -func (m Visitor) visitAList(nodes walk.Sources, _ *openapi.ResourceSchema) (*yaml.RNode, error) { - if yaml.IsMissingOrNull(nodes.Updated()) && !yaml.IsMissingOrNull(nodes.Origin()) { - // implicitly cleared from update -- element was deleted - return walk.ClearNode, nil - } - if yaml.IsMissingOrNull(nodes.Dest()) { - // not cleared, but missing from the dest - // initialize a new value that can be recursively merged - return yaml.NewRNode(&yaml.Node{Kind: yaml.SequenceNode}), nil - } - - // recursively merge the dest with the original and updated - return nodes.Dest(), nil -} - -func (m Visitor) VisitScalar(nodes walk.Sources, s *openapi.ResourceSchema) (*yaml.RNode, error) { - if nodes.Updated().IsTaggedNull() || nodes.Dest().IsTaggedNull() { - // explicitly cleared from either dest or update - return nil, nil - } - if yaml.IsMissingOrNull(nodes.Updated()) != yaml.IsMissingOrNull(nodes.Origin()) { - // value added or removed in update - return nodes.Updated(), nil - } - if yaml.IsMissingOrNull(nodes.Updated()) && yaml.IsMissingOrNull(nodes.Origin()) { - // value added or removed in update - return nodes.Dest(), nil - } - - values, err := m.getStrValues(nodes) - if err != nil { - return nil, err - } - - if (values.Dest == "" || values.Dest == values.Origin) && values.Origin != values.Update { - // if local is nil or is unchanged but there is new update - return nodes.Updated(), nil - } - - if nodes.Updated().YNode().Value != nodes.Origin().YNode().Value { - // value changed in update - return nodes.Updated(), nil - } - - // unchanged between origin and update, keep the dest - return nodes.Dest(), nil -} - -func (m Visitor) visitNAList(nodes walk.Sources) (*yaml.RNode, error) { - if nodes.Updated().IsTaggedNull() || nodes.Dest().IsTaggedNull() { - // explicitly cleared from either dest or update - return walk.ClearNode, nil - } - - if yaml.IsMissingOrNull(nodes.Updated()) != yaml.IsMissingOrNull(nodes.Origin()) { - // value added or removed in update - return nodes.Updated(), nil - } - if yaml.IsMissingOrNull(nodes.Updated()) && yaml.IsMissingOrNull(nodes.Origin()) { - // value not present in source or dest - return nodes.Dest(), nil - } - - // compare origin and update values to see if they have changed - values, err := m.getStrValues(nodes) - if err != nil { - return nil, err - } - if values.Update != values.Origin { - // value changed in update - return nodes.Updated(), nil - } - - // unchanged between origin and update, keep the dest - return nodes.Dest(), nil -} - -func (m Visitor) VisitList(nodes walk.Sources, s *openapi.ResourceSchema, kind walk.ListKind) (*yaml.RNode, error) { - if kind == walk.AssociativeList { - return m.visitAList(nodes, s) - } - // non-associative list - return m.visitNAList(nodes) -} - -func (m Visitor) getStrValues(nodes walk.Sources) (strValues, error) { - var uStr, oStr, dStr string - var err error - if nodes.Updated() != nil && nodes.Updated().YNode() != nil { - s := nodes.Updated().YNode().Style - defer func() { - nodes.Updated().YNode().Style = s - }() - nodes.Updated().YNode().Style = yaml.FlowStyle | yaml.SingleQuotedStyle - uStr, err = nodes.Updated().String() - if err != nil { - return strValues{}, err - } - } - if nodes.Origin() != nil && nodes.Origin().YNode() != nil { - s := nodes.Origin().YNode().Style - defer func() { - nodes.Origin().YNode().Style = s - }() - nodes.Origin().YNode().Style = yaml.FlowStyle | yaml.SingleQuotedStyle - oStr, err = nodes.Origin().String() - if err != nil { - return strValues{}, err - } - } - if nodes.Dest() != nil && nodes.Dest().YNode() != nil { - s := nodes.Dest().YNode().Style - defer func() { - nodes.Dest().YNode().Style = s - }() - nodes.Dest().YNode().Style = yaml.FlowStyle | yaml.SingleQuotedStyle - dStr, err = nodes.Dest().String() - if err != nil { - return strValues{}, err - } - } - - return strValues{Origin: oStr, Update: uStr, Dest: dStr}, nil -} - -type strValues struct { - Origin string - Update string - Dest string -} - -var _ walk.Visitor = Visitor{}